Elffuss BraidHub

kikocis/java-driver public

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

Browse the files at this changeset

More than 300 files changed

modified driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java +22 −26
@@ -15,19 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.base.Objects;
19+import com.google.common.reflect.TypeToken;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.net.InetAddress;
2124 import java.nio.ByteBuffer;
2225 import java.util.*;
2326
24-import com.google.common.base.Objects;
25-import com.google.common.reflect.TypeToken;
26-
27-import static com.datastax.driver.core.TypeTokens.listOf;
28-import static com.datastax.driver.core.TypeTokens.mapOf;
29-import static com.datastax.driver.core.TypeTokens.setOf;
30-
3127 abstract class AbstractAddressableByIndexData<T extends SettableByIndexData<T>> extends AbstractGettableByIndexData implements SettableByIndexData<T> {
3228
3329 final ByteBuffer[] values;
@@ -40,7 +36,7 @@
4036 @SuppressWarnings("unchecked")
4137 protected T setValue(int i, ByteBuffer value) {
4238 values[i] = value;
43- return (T)this;
39+ return (T) this;
4440 }
4541
4642 protected ByteBuffer getValue(int i) {
@@ -50,8 +46,8 @@
5046 public T setBool(int i, boolean v) {
5147 TypeCodec<Boolean> codec = codecFor(i, Boolean.class);
5248 ByteBuffer bb;
53- if(codec instanceof TypeCodec.PrimitiveBooleanCodec)
54- bb = ((TypeCodec.PrimitiveBooleanCodec)codec).serializeNoBoxing(v, protocolVersion);
49+ if (codec instanceof TypeCodec.PrimitiveBooleanCodec)
50+ bb = ((TypeCodec.PrimitiveBooleanCodec) codec).serializeNoBoxing(v, protocolVersion);
5551 else
5652 bb = codec.serialize(v, protocolVersion);
5753 return setValue(i, bb);
@@ -60,8 +56,8 @@
6056 public T setByte(int i, byte v) {
6157 TypeCodec<Byte> codec = codecFor(i, Byte.class);
6258 ByteBuffer bb;
63- if(codec instanceof TypeCodec.PrimitiveByteCodec)
64- bb = ((TypeCodec.PrimitiveByteCodec)codec).serializeNoBoxing(v, protocolVersion);
59+ if (codec instanceof TypeCodec.PrimitiveByteCodec)
60+ bb = ((TypeCodec.PrimitiveByteCodec) codec).serializeNoBoxing(v, protocolVersion);
6561 else
6662 bb = codec.serialize(v, protocolVersion);
6763 return setValue(i, bb);
@@ -70,8 +66,8 @@
7066 public T setShort(int i, short v) {
7167 TypeCodec<Short> codec = codecFor(i, Short.class);
7268 ByteBuffer bb;
73- if(codec instanceof TypeCodec.PrimitiveShortCodec)
74- bb = ((TypeCodec.PrimitiveShortCodec)codec).serializeNoBoxing(v, protocolVersion);
69+ if (codec instanceof TypeCodec.PrimitiveShortCodec)
70+ bb = ((TypeCodec.PrimitiveShortCodec) codec).serializeNoBoxing(v, protocolVersion);
7571 else
7672 bb = codec.serialize(v, protocolVersion);
7773 return setValue(i, bb);
@@ -80,8 +76,8 @@
8076 public T setInt(int i, int v) {
8177 TypeCodec<Integer> codec = codecFor(i, Integer.class);
8278 ByteBuffer bb;
83- if(codec instanceof TypeCodec.PrimitiveIntCodec)
84- bb = ((TypeCodec.PrimitiveIntCodec)codec).serializeNoBoxing(v, protocolVersion);
79+ if (codec instanceof TypeCodec.PrimitiveIntCodec)
80+ bb = ((TypeCodec.PrimitiveIntCodec) codec).serializeNoBoxing(v, protocolVersion);
8581 else
8682 bb = codec.serialize(v, protocolVersion);
8783 return setValue(i, bb);
@@ -90,8 +86,8 @@
9086 public T setLong(int i, long v) {
9187 TypeCodec<Long> codec = codecFor(i, Long.class);
9288 ByteBuffer bb;
93- if(codec instanceof TypeCodec.PrimitiveLongCodec)
94- bb = ((TypeCodec.PrimitiveLongCodec)codec).serializeNoBoxing(v, protocolVersion);
89+ if (codec instanceof TypeCodec.PrimitiveLongCodec)
90+ bb = ((TypeCodec.PrimitiveLongCodec) codec).serializeNoBoxing(v, protocolVersion);
9591 else
9692 bb = codec.serialize(v, protocolVersion);
9793 return setValue(i, bb);
@@ -108,8 +104,8 @@
108104 public T setTime(int i, long v) {
109105 TypeCodec<Long> codec = codecFor(i, Long.class);
110106 ByteBuffer bb;
111- if(codec instanceof TypeCodec.PrimitiveLongCodec)
112- bb = ((TypeCodec.PrimitiveLongCodec)codec).serializeNoBoxing(v, protocolVersion);
107+ if (codec instanceof TypeCodec.PrimitiveLongCodec)
108+ bb = ((TypeCodec.PrimitiveLongCodec) codec).serializeNoBoxing(v, protocolVersion);
113109 else
114110 bb = codec.serialize(v, protocolVersion);
115111 return setValue(i, bb);
@@ -118,8 +114,8 @@
118114 public T setFloat(int i, float v) {
119115 TypeCodec<Float> codec = codecFor(i, Float.class);
120116 ByteBuffer bb;
121- if(codec instanceof TypeCodec.PrimitiveFloatCodec)
122- bb = ((TypeCodec.PrimitiveFloatCodec)codec).serializeNoBoxing(v, protocolVersion);
117+ if (codec instanceof TypeCodec.PrimitiveFloatCodec)
118+ bb = ((TypeCodec.PrimitiveFloatCodec) codec).serializeNoBoxing(v, protocolVersion);
123119 else
124120 bb = codec.serialize(v, protocolVersion);
125121 return setValue(i, bb);
@@ -128,8 +124,8 @@
128124 public T setDouble(int i, double v) {
129125 TypeCodec<Double> codec = codecFor(i, Double.class);
130126 ByteBuffer bb;
131- if(codec instanceof TypeCodec.PrimitiveDoubleCodec)
132- bb = ((TypeCodec.PrimitiveDoubleCodec)codec).serializeNoBoxing(v, protocolVersion);
127+ if (codec instanceof TypeCodec.PrimitiveDoubleCodec)
128+ bb = ((TypeCodec.PrimitiveDoubleCodec) codec).serializeNoBoxing(v, protocolVersion);
133129 else
134130 bb = codec.serialize(v, protocolVersion);
135131 return setValue(i, bb);
@@ -241,11 +237,11 @@
241237 if (!(o instanceof AbstractAddressableByIndexData))
242238 return false;
243239
244- AbstractAddressableByIndexData<?> that = (AbstractAddressableByIndexData<?>)o;
240+ AbstractAddressableByIndexData<?> that = (AbstractAddressableByIndexData<?>) o;
245241 if (values.length != that.values.length)
246242 return false;
247243
248- if(this.protocolVersion != that.protocolVersion)
244+ if (this.protocolVersion != that.protocolVersion)
249245 return false;
250246
251247 // Deserializing each value is slightly inefficient, but comparing
modified driver-core/src/main/java/com/datastax/driver/core/AbstractData.java +25 −29
@@ -15,19 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.base.Objects;
19+import com.google.common.reflect.TypeToken;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.net.InetAddress;
2124 import java.nio.ByteBuffer;
2225 import java.util.*;
2326
24-import com.google.common.base.Objects;
25-import com.google.common.reflect.TypeToken;
26-
27-import static com.datastax.driver.core.TypeTokens.listOf;
28-import static com.datastax.driver.core.TypeTokens.mapOf;
29-import static com.datastax.driver.core.TypeTokens.setOf;
30-
3127 // We don't want to expose this one: it's less useful externally and it's a bit ugly to expose anyway (but it's convenient).
3228 abstract class AbstractData<T extends SettableData<T>> extends AbstractGettableData implements SettableData<T> {
3329
@@ -39,7 +35,7 @@
3935 @SuppressWarnings("unchecked")
4036 protected AbstractData(ProtocolVersion protocolVersion, int size) {
4137 super(protocolVersion);
42- this.wrapped = (T)this;
38+ this.wrapped = (T) this;
4339 this.values = new ByteBuffer[size];
4440 }
4541
@@ -74,8 +70,8 @@
7470 public T setBool(int i, boolean v) {
7571 TypeCodec<Boolean> codec = codecFor(i, Boolean.class);
7672 ByteBuffer bb;
77- if(codec instanceof TypeCodec.PrimitiveBooleanCodec)
78- bb = ((TypeCodec.PrimitiveBooleanCodec)codec).serializeNoBoxing(v, protocolVersion);
73+ if (codec instanceof TypeCodec.PrimitiveBooleanCodec)
74+ bb = ((TypeCodec.PrimitiveBooleanCodec) codec).serializeNoBoxing(v, protocolVersion);
7975 else
8076 bb = codec.serialize(v, protocolVersion);
8177 return setValue(i, bb);
@@ -93,8 +89,8 @@
9389 public T setByte(int i, byte v) {
9490 TypeCodec<Byte> codec = codecFor(i, Byte.class);
9591 ByteBuffer bb;
96- if(codec instanceof TypeCodec.PrimitiveByteCodec)
97- bb = ((TypeCodec.PrimitiveByteCodec)codec).serializeNoBoxing(v, protocolVersion);
92+ if (codec instanceof TypeCodec.PrimitiveByteCodec)
93+ bb = ((TypeCodec.PrimitiveByteCodec) codec).serializeNoBoxing(v, protocolVersion);
9894 else
9995 bb = codec.serialize(v, protocolVersion);
10096 return setValue(i, bb);
@@ -112,8 +108,8 @@
112108 public T setShort(int i, short v) {
113109 TypeCodec<Short> codec = codecFor(i, Short.class);
114110 ByteBuffer bb;
115- if(codec instanceof TypeCodec.PrimitiveShortCodec)
116- bb = ((TypeCodec.PrimitiveShortCodec)codec).serializeNoBoxing(v, protocolVersion);
111+ if (codec instanceof TypeCodec.PrimitiveShortCodec)
112+ bb = ((TypeCodec.PrimitiveShortCodec) codec).serializeNoBoxing(v, protocolVersion);
117113 else
118114 bb = codec.serialize(v, protocolVersion);
119115 return setValue(i, bb);
@@ -131,8 +127,8 @@
131127 public T setInt(int i, int v) {
132128 TypeCodec<Integer> codec = codecFor(i, Integer.class);
133129 ByteBuffer bb;
134- if(codec instanceof TypeCodec.PrimitiveIntCodec)
135- bb = ((TypeCodec.PrimitiveIntCodec)codec).serializeNoBoxing(v, protocolVersion);
130+ if (codec instanceof TypeCodec.PrimitiveIntCodec)
131+ bb = ((TypeCodec.PrimitiveIntCodec) codec).serializeNoBoxing(v, protocolVersion);
136132 else
137133 bb = codec.serialize(v, protocolVersion);
138134 return setValue(i, bb);
@@ -150,8 +146,8 @@
150146 public T setLong(int i, long v) {
151147 TypeCodec<Long> codec = codecFor(i, Long.class);
152148 ByteBuffer bb;
153- if(codec instanceof TypeCodec.PrimitiveLongCodec)
154- bb = ((TypeCodec.PrimitiveLongCodec)codec).serializeNoBoxing(v, protocolVersion);
149+ if (codec instanceof TypeCodec.PrimitiveLongCodec)
150+ bb = ((TypeCodec.PrimitiveLongCodec) codec).serializeNoBoxing(v, protocolVersion);
155151 else
156152 bb = codec.serialize(v, protocolVersion);
157153 return setValue(i, bb);
@@ -195,8 +191,8 @@
195191 public T setTime(int i, long v) {
196192 TypeCodec<Long> codec = codecFor(i, Long.class);
197193 ByteBuffer bb;
198- if(codec instanceof TypeCodec.PrimitiveLongCodec)
199- bb = ((TypeCodec.PrimitiveLongCodec)codec).serializeNoBoxing(v, protocolVersion);
194+ if (codec instanceof TypeCodec.PrimitiveLongCodec)
195+ bb = ((TypeCodec.PrimitiveLongCodec) codec).serializeNoBoxing(v, protocolVersion);
200196 else
201197 bb = codec.serialize(v, protocolVersion);
202198 return setValue(i, bb);
@@ -214,8 +210,8 @@
214210 public T setFloat(int i, float v) {
215211 TypeCodec<Float> codec = codecFor(i, Float.class);
216212 ByteBuffer bb;
217- if(codec instanceof TypeCodec.PrimitiveFloatCodec)
218- bb = ((TypeCodec.PrimitiveFloatCodec)codec).serializeNoBoxing(v, protocolVersion);
213+ if (codec instanceof TypeCodec.PrimitiveFloatCodec)
214+ bb = ((TypeCodec.PrimitiveFloatCodec) codec).serializeNoBoxing(v, protocolVersion);
219215 else
220216 bb = codec.serialize(v, protocolVersion);
221217 return setValue(i, bb);
@@ -233,8 +229,8 @@
233229 public T setDouble(int i, double v) {
234230 TypeCodec<Double> codec = codecFor(i, Double.class);
235231 ByteBuffer bb;
236- if(codec instanceof TypeCodec.PrimitiveDoubleCodec)
237- bb = ((TypeCodec.PrimitiveDoubleCodec)codec).serializeNoBoxing(v, protocolVersion);
232+ if (codec instanceof TypeCodec.PrimitiveDoubleCodec)
233+ bb = ((TypeCodec.PrimitiveDoubleCodec) codec).serializeNoBoxing(v, protocolVersion);
238234 else
239235 bb = codec.serialize(v, protocolVersion);
240236 return setValue(i, bb);
@@ -401,7 +397,7 @@
401397 public <K, V> T setMap(int i, Map<K, V> v) {
402398 return setValue(i, codecFor(i).serialize(v, protocolVersion));
403399 }
404-
400+
405401 @Override
406402 public <K, V> T setMap(int i, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass) {
407403 return setValue(i, codecFor(i, TypeTokens.mapOf(keysClass, valuesClass)).serialize(v, protocolVersion));
@@ -441,7 +437,7 @@
441437 public <E> T setSet(int i, Set<E> v) {
442438 return setValue(i, codecFor(i).serialize(v, protocolVersion));
443439 }
444-
440+
445441 @Override
446442 public <E> T setSet(int i, Set<E> v, Class<E> elementsClass) {
447443 return setValue(i, codecFor(i, TypeTokens.setOf(elementsClass)).serialize(v, protocolVersion));
@@ -459,7 +455,7 @@
459455 }
460456 return wrapped;
461457 }
462-
458+
463459 @Override
464460 public <E> T setSet(String name, Set<E> v, Class<E> elementsClass) {
465461 for (int i : getAllIndexesOf(name)) {
@@ -560,11 +556,11 @@
560556 if (!(o instanceof AbstractData))
561557 return false;
562558
563- AbstractData<?> that = (AbstractData<?>)o;
559+ AbstractData<?> that = (AbstractData<?>) o;
564560 if (values.length != that.values.length)
565561 return false;
566562
567- if(this.protocolVersion != that.protocolVersion)
563+ if (this.protocolVersion != that.protocolVersion)
568564 return false;
569565
570566 // Deserializing each value is slightly inefficient, but comparing
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +12 −20
@@ -15,20 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.google.common.reflect.TypeToken;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.net.InetAddress;
2124 import java.nio.ByteBuffer;
2225 import java.util.*;
2326
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-
28-import static com.datastax.driver.core.TypeTokens.listOf;
29-import static com.datastax.driver.core.TypeTokens.mapOf;
30-import static com.datastax.driver.core.TypeTokens.setOf;
31-
3227 abstract class AbstractGettableByIndexData implements GettableByIndexData {
3328
3429 protected final ProtocolVersion protocolVersion;
@@ -42,7 +37,6 @@
4237 *
4338 * @param i the index of the type to fetch.
4439 * @return the type of the value at index {@code i}.
45- *
4640 * @throws IndexOutOfBoundsException if {@code i} is not a valid index.
4741 */
4842 protected abstract DataType getType(int i);
@@ -52,7 +46,6 @@
5246 *
5347 * @param i the index of the name to fetch.
5448 * @return the name corresponding to the value at index {@code i}.
55- *
5649 * @throws IndexOutOfBoundsException if {@code i} is not a valid index.
5750 */
5851 protected abstract String getName(int i);
@@ -62,7 +55,6 @@
6255 *
6356 * @param i the index to fetch.
6457 * @return the value at index {@code i}.
65- *
6658 * @throws IndexOutOfBoundsException if {@code i} is not a valid index.
6759 */
6860 protected abstract ByteBuffer getValue(int i);
@@ -73,7 +65,7 @@
7365 return getCodecRegistry().codecFor(getType(i));
7466 }
7567
76- protected <T> TypeCodec<T> codecFor(int i, Class<T> javaClass){
68+ protected <T> TypeCodec<T> codecFor(int i, Class<T> javaClass) {
7769 return getCodecRegistry().codecFor(getType(i), javaClass);
7870 }
7971
@@ -106,7 +98,7 @@
10698 public boolean getBool(int i) {
10799 ByteBuffer value = getValue(i);
108100 TypeCodec<Boolean> codec = codecFor(i, Boolean.class);
109- if(codec instanceof TypeCodec.PrimitiveBooleanCodec)
101+ if (codec instanceof TypeCodec.PrimitiveBooleanCodec)
110102 return ((TypeCodec.PrimitiveBooleanCodec) codec).deserializeNoBoxing(value, protocolVersion);
111103 else
112104 return codec.deserialize(value, protocolVersion);
@@ -119,7 +111,7 @@
119111 public byte getByte(int i) {
120112 ByteBuffer value = getValue(i);
121113 TypeCodec<Byte> codec = codecFor(i, Byte.class);
122- if(codec instanceof TypeCodec.PrimitiveByteCodec)
114+ if (codec instanceof TypeCodec.PrimitiveByteCodec)
123115 return ((TypeCodec.PrimitiveByteCodec) codec).deserializeNoBoxing(value, protocolVersion);
124116 else
125117 return codec.deserialize(value, protocolVersion);
@@ -132,7 +124,7 @@
132124 public short getShort(int i) {
133125 ByteBuffer value = getValue(i);
134126 TypeCodec<Short> codec = codecFor(i, Short.class);
135- if(codec instanceof TypeCodec.PrimitiveShortCodec)
127+ if (codec instanceof TypeCodec.PrimitiveShortCodec)
136128 return ((TypeCodec.PrimitiveShortCodec) codec).deserializeNoBoxing(value, protocolVersion);
137129 else
138130 return codec.deserialize(value, protocolVersion);
@@ -145,7 +137,7 @@
145137 public int getInt(int i) {
146138 ByteBuffer value = getValue(i);
147139 TypeCodec<Integer> codec = codecFor(i, Integer.class);
148- if(codec instanceof TypeCodec.PrimitiveIntCodec)
140+ if (codec instanceof TypeCodec.PrimitiveIntCodec)
149141 return ((TypeCodec.PrimitiveIntCodec) codec).deserializeNoBoxing(value, protocolVersion);
150142 else
151143 return codec.deserialize(value, protocolVersion);
@@ -158,7 +150,7 @@
158150 public long getLong(int i) {
159151 ByteBuffer value = getValue(i);
160152 TypeCodec<Long> codec = codecFor(i, Long.class);
161- if(codec instanceof TypeCodec.PrimitiveLongCodec)
153+ if (codec instanceof TypeCodec.PrimitiveLongCodec)
162154 return ((TypeCodec.PrimitiveLongCodec) codec).deserializeNoBoxing(value, protocolVersion);
163155 else
164156 return codec.deserialize(value, protocolVersion);
@@ -189,7 +181,7 @@
189181 public long getTime(int i) {
190182 ByteBuffer value = getValue(i);
191183 TypeCodec<Long> codec = codecFor(i, Long.class);
192- if(codec instanceof TypeCodec.PrimitiveLongCodec)
184+ if (codec instanceof TypeCodec.PrimitiveLongCodec)
193185 return ((TypeCodec.PrimitiveLongCodec) codec).deserializeNoBoxing(value, protocolVersion);
194186 else
195187 return codec.deserialize(value, protocolVersion);
@@ -202,7 +194,7 @@
202194 public float getFloat(int i) {
203195 ByteBuffer value = getValue(i);
204196 TypeCodec<Float> codec = codecFor(i, Float.class);
205- if(codec instanceof TypeCodec.PrimitiveFloatCodec)
197+ if (codec instanceof TypeCodec.PrimitiveFloatCodec)
206198 return ((TypeCodec.PrimitiveFloatCodec) codec).deserializeNoBoxing(value, protocolVersion);
207199 else
208200 return codec.deserialize(value, protocolVersion);
@@ -215,7 +207,7 @@
215207 public double getDouble(int i) {
216208 ByteBuffer value = getValue(i);
217209 TypeCodec<Double> codec = codecFor(i, Double.class);
218- if(codec instanceof TypeCodec.PrimitiveDoubleCodec)
210+ if (codec instanceof TypeCodec.PrimitiveDoubleCodec)
219211 return ((TypeCodec.PrimitiveDoubleCodec) codec).deserializeNoBoxing(value, protocolVersion);
220212 else
221213 return codec.deserialize(value, protocolVersion);
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java +5 −7
@@ -15,24 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.reflect.TypeToken;
19+
1820 import java.math.BigDecimal;
1921 import java.math.BigInteger;
2022 import java.net.InetAddress;
2123 import java.nio.ByteBuffer;
2224 import java.util.*;
2325
24-import com.google.common.reflect.TypeToken;
25-
2626 public abstract class AbstractGettableData extends AbstractGettableByIndexData implements GettableData {
2727
2828 /**
2929 * Creates a new AbstractGettableData object.
3030 *
3131 * @param protocolVersion the protocol version in which values returned
32- * by {@link #getValue} will be returned. This must be a protocol version
33- * supported by this driver. In general, the correct value will be the
34- * value returned by {@link ProtocolOptions#getProtocolVersion}.
35- *
32+ * by {@link #getValue} will be returned. This must be a protocol version
33+ * supported by this driver. In general, the correct value will be the
34+ * value returned by {@link ProtocolOptions#getProtocolVersion}.
3635 * @throws IllegalArgumentException if {@code protocolVersion} is not a valid protocol version.
3736 */
3837 protected AbstractGettableData(ProtocolVersion protocolVersion) {
@@ -44,7 +43,6 @@
4443 *
4544 * @param name the name for which to return the index of.
4645 * @return the index for the value coressponding to {@code name}.
47- *
4846 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
4947 */
5048 protected abstract int getIndexOf(String name);
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +27 −15
@@ -15,27 +15,26 @@
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.exceptions.ConnectionException;
20+import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
21+import com.datastax.driver.core.policies.ReconnectionPolicy;
2122 import com.google.common.annotations.VisibleForTesting;
22-import com.google.common.util.concurrent.ListenableFuture;
2323 import com.google.common.util.concurrent.AbstractFuture;
24+import com.google.common.util.concurrent.ListenableFuture;
2425 import org.slf4j.Logger;
2526 import org.slf4j.LoggerFactory;
2627
27-import com.datastax.driver.core.exceptions.AuthenticationException;
28-import com.datastax.driver.core.exceptions.ConnectionException;
29-import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
30-import com.datastax.driver.core.policies.ReconnectionPolicy;
28+import java.util.concurrent.*;
29+import java.util.concurrent.atomic.AtomicReference;
3130
3231 /**
3332 * Manages periodic reconnection attempts after a host has been marked down.
34- * <p>
33+ * <p/>
3534 * Concurrent attempts are handled via the {@link #currentAttempt} reference passed to the constructor.
3635 * For a given reference, only one handler will run at a given time. Additional handlers will cancel
3736 * themselves if they find a previous handler running.
38- * <p>
37+ * <p/>
3938 * This class is designed for concurrency, but instances must not be shared: each thread creates and
4039 * starts its own private handler, all interactions happen through {@link #currentAttempt}.
4140 */
@@ -70,18 +69,31 @@
7069 }
7170
7271 protected abstract Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException;
72+
7373 protected abstract void onReconnection(Connection connection);
7474
75- protected boolean onConnectionException(ConnectionException e, long nextDelayMs) { return true; }
76- protected boolean onUnknownException(Exception e, long nextDelayMs) { return true; }
75+ protected boolean onConnectionException(ConnectionException e, long nextDelayMs) {
76+ return true;
77+ }
78+
79+ protected boolean onUnknownException(Exception e, long nextDelayMs) {
80+ return true;
81+ }
7782
7883 // Retrying on authentication errors makes sense for applications that can update the credentials at runtime, we don't want to force them
7984 // to restart.
80- protected boolean onAuthenticationException(AuthenticationException e, long nextDelayMs) { return true; }
85+ protected boolean onAuthenticationException(AuthenticationException e, long nextDelayMs) {
86+ return true;
87+ }
8188
8289 // Retrying on these errors is unlikely to work
83- protected boolean onUnsupportedProtocolVersionException(UnsupportedProtocolVersionException e, long nextDelayMs) { return false; }
84- protected boolean onClusterNameMismatchException(ClusterNameMismatchException e, long nextDelayMs) { return false; }
90+ protected boolean onUnsupportedProtocolVersionException(UnsupportedProtocolVersionException e, long nextDelayMs) {
91+ return false;
92+ }
93+
94+ protected boolean onClusterNameMismatchException(ClusterNameMismatchException e, long nextDelayMs) {
95+ return false;
96+ }
8597
8698 public void start() {
8799 long firstDelay = (initialDelayMs >= 0) ? initialDelayMs : schedule.nextDelayMs();
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +6 −6
@@ -15,18 +15,18 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Map;
20-import java.util.concurrent.ExecutionException;
21-
2218 import com.google.common.base.Function;
2319 import com.google.common.util.concurrent.Futures;
2420 import com.google.common.util.concurrent.ListenableFuture;
2521 import com.google.common.util.concurrent.Uninterruptibles;
2622
23+import java.nio.ByteBuffer;
24+import java.util.Map;
25+import java.util.concurrent.ExecutionException;
26+
2727 /**
2828 * Abstract implementation of the Session interface.
29- *
29+ * <p/>
3030 * This is primarly intended to make mocking easier.
3131 */
3232 public abstract class AbstractSession implements Session {
@@ -137,7 +137,7 @@
137137 * Prepares the provided query string asynchronously,
138138 * sending along the provided custom payload, if any.
139139 *
140- * @param query the CQL query string to prepare
140+ * @param query the CQL query string to prepare
141141 * @param customPayload the custom payload to send along the query, or {@code null} if no payload is to be sent
142142 * @return a future on the prepared statement corresponding to {@code query}.
143143 */
modified driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java +46 −47
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Collections;
20-import java.util.List;
21-
2218 import com.google.common.base.Objects;
2319 import com.google.common.collect.ImmutableList;
2420 import com.google.common.collect.Lists;
2521
22+import java.nio.ByteBuffer;
23+import java.util.Collections;
24+import java.util.List;
25+
2626 /**
2727 * Describes a CQL aggregate function (created with {@code CREATE AGGREGATE...}).
2828 */
@@ -41,8 +41,8 @@
4141 private final TypeCodec<Object> stateTypeCodec;
4242
4343 private AggregateMetadata(KeyspaceMetadata keyspace, String simpleName, List<DataType> argumentTypes,
44- String finalFuncSimpleName, String finalFuncFullName, Object initCond, DataType returnType,
45- String stateFuncSimpleName, String stateFuncFullName, DataType stateType, TypeCodec<Object> stateTypeCodec) {
44+ String finalFuncSimpleName, String finalFuncFullName, Object initCond, DataType returnType,
45+ String stateFuncSimpleName, String stateFuncFullName, DataType stateType, TypeCodec<Object> stateTypeCodec) {
4646 this.keyspace = keyspace;
4747 this.simpleName = simpleName;
4848 this.argumentTypes = argumentTypes;
@@ -89,7 +89,7 @@
8989 List<DataType> argumentTypes = parseTypes(ksm, row.getList("argument_types", String.class), version, cluster);
9090 String finalFuncSimpleName = row.getString("final_func");
9191 DataType returnType;
92- if(version.getMajor() >= 3) {
92+ if (version.getMajor() >= 3) {
9393 returnType = DataTypeCqlNameParser.parse(row.getString("return_type"), cluster, ksm.getName(), ksm.userTypes, null, false, false);
9494 } else {
9595 returnType = DataTypeClassNameParser.parseOne(row.getString("return_type"), protocolVersion, codecRegistry);
@@ -98,7 +98,7 @@
9898 String stateTypeName = row.getString("state_type");
9999 DataType stateType;
100100 Object initCond;
101- if(version.getMajor() >= 3) {
101+ if (version.getMajor() >= 3) {
102102 stateType = DataTypeCqlNameParser.parse(stateTypeName, cluster, ksm.getName(), ksm.userTypes, null, false, false);
103103 String rawInitCond = row.getString("initcond");
104104 initCond = rawInitCond == null ? null : codecRegistry.codecFor(stateType).parse(rawInitCond);
@@ -112,8 +112,8 @@
112112 String stateFuncFullName = makeStateFuncFullName(stateFuncSimpleName, stateType, argumentTypes);
113113
114114 return new AggregateMetadata(ksm, simpleName, argumentTypes,
115- finalFuncSimpleName, finalFuncFullName, initCond, returnType, stateFuncSimpleName,
116- stateFuncFullName, stateType, codecRegistry.codecFor(stateType));
115+ finalFuncSimpleName, finalFuncFullName, initCond, returnType, stateFuncSimpleName,
116+ stateFuncFullName, stateType, codecRegistry.codecFor(stateType));
117117 }
118118
119119 private static String makeStateFuncFullName(String stateFuncSimpleName, DataType stateType, List<DataType> argumentTypes) {
@@ -143,7 +143,7 @@
143143
144144 /**
145145 * Returns a CQL query representing this function in human readable form.
146- * <p>
146+ * <p/>
147147 * This method is equivalent to {@link #asCQLQuery} but the output is formatted.
148148 *
149149 * @return the CQL query representing this function.
@@ -154,7 +154,7 @@
154154
155155 /**
156156 * Returns a CQL query representing this function.
157- *
157+ * <p/>
158158 * This method returns a single 'CREATE FUNCTION' query corresponding to
159159 * this function definition.
160160 *
@@ -172,26 +172,26 @@
172172 private String asCQLQuery(boolean formatted) {
173173
174174 StringBuilder sb = new StringBuilder("CREATE AGGREGATE ")
175- .append(Metadata.escapeId(keyspace.getName()))
176- .append('.');
175+ .append(Metadata.escapeId(keyspace.getName()))
176+ .append('.');
177177
178178 appendSignature(sb);
179179
180180 TableMetadata.spaceOrNewLine(sb, formatted)
181- .append("SFUNC ")
182- .append(Metadata.escapeId(stateFuncSimpleName))
183- .append(" STYPE ")
184- .append(stateType.asFunctionParameterString());
181+ .append("SFUNC ")
182+ .append(Metadata.escapeId(stateFuncSimpleName))
183+ .append(" STYPE ")
184+ .append(stateType.asFunctionParameterString());
185185
186186 if (finalFuncSimpleName != null)
187187 TableMetadata.spaceOrNewLine(sb, formatted)
188- .append("FINALFUNC ")
189- .append(Metadata.escapeId(finalFuncSimpleName));
188+ .append("FINALFUNC ")
189+ .append(Metadata.escapeId(finalFuncSimpleName));
190190
191191 if (initCond != null)
192192 TableMetadata.spaceOrNewLine(sb, formatted)
193- .append("INITCOND ")
194- .append(stateTypeCodec.format(initCond));
193+ .append("INITCOND ")
194+ .append(stateTypeCodec.format(initCond));
195195
196196 sb.append(';');
197197
@@ -200,8 +200,8 @@
200200
201201 private void appendSignature(StringBuilder sb) {
202202 sb
203- .append(Metadata.escapeId(simpleName))
204- .append('(');
203+ .append(Metadata.escapeId(simpleName))
204+ .append('(');
205205 boolean first = true;
206206 for (DataType type : argumentTypes) {
207207 if (first)
@@ -224,10 +224,10 @@
224224
225225 /**
226226 * Returns the CQL signature of this aggregate.
227- * <p>
227+ * <p/>
228228 * This is the name of the aggregate, followed by the names of the argument types between parentheses,
229229 * like it was specified in the {@code CREATE AGGREGATE...} statement, for example {@code sum(int)}.
230- * <p>
230+ * <p/>
231231 * Note that the returned signature is not qualified with the keyspace name.
232232 *
233233 * @return the signature of this aggregate.
@@ -240,13 +240,12 @@
240240
241241 /**
242242 * Returns the simple name of this aggregate.
243- * <p>
243+ * <p/>
244244 * This is the name of the aggregate, without arguments. Note that aggregates can be overloaded with
245245 * different argument lists, therefore the simple name may not be unique. For example,
246246 * {@code sum(int)} and {@code sum(int,int)} both have the simple name {@code sum}.
247247 *
248248 * @return the simple name of this aggregate.
249- *
250249 * @see #getSignature()
251250 */
252251 public String getSimpleName() {
@@ -264,7 +263,7 @@
264263
265264 /**
266265 * Returns the final function of this aggregate.
267- * <p>
266+ * <p/>
268267 * This is the function specified with {@code FINALFUNC} in the {@code CREATE AGGREGATE...}
269268 * statement. It transforms the final value after the aggregation is complete.
270269 *
@@ -272,13 +271,13 @@
272271 */
273272 public FunctionMetadata getFinalFunc() {
274273 return (finalFuncFullName == null)
275- ? null
276- : keyspace.functions.get(finalFuncFullName);
274+ ? null
275+ : keyspace.functions.get(finalFuncFullName);
277276 }
278277
279278 /**
280279 * Returns the initial state value of this aggregate.
281- * <p>
280+ * <p/>
282281 * This is the value specified with {@code INITCOND} in the {@code CREATE AGGREGATE...}
283282 * statement. It's passed to the initial invocation of the state function (if that function
284283 * does not accept null arguments).
@@ -291,7 +290,7 @@
291290
292291 /**
293292 * Returns the return type of this aggregate.
294- * <p>
293+ * <p/>
295294 * This is the final type of the value computed by this aggregate; in other words, the return
296295 * type of the final function if it is defined, or the state type otherwise.
297296 *
@@ -303,7 +302,7 @@
303302
304303 /**
305304 * Returns the state function of this aggregate.
306- * <p>
305+ * <p/>
307306 * This is the function specified with {@code SFUNC} in the {@code CREATE AGGREGATE...}
308307 * statement. It aggregates the current state with each row to produce a new state.
309308 *
@@ -315,7 +314,7 @@
315314
316315 /**
317316 * Returns the state type of this aggregate.
318- * <p>
317+ * <p/>
319318 * This is the type specified with {@code STYPE} in the {@code CREATE AGGREGATE...}
320319 * statement. It defines the type of the value that is accumulated as the aggregate
321320 * iterates through the rows.
@@ -330,19 +329,19 @@
330329 public boolean equals(Object other) {
331330 if (other == this)
332331 return true;
333-
332+
334333 if (other instanceof AggregateMetadata) {
335- AggregateMetadata that = (AggregateMetadata)other;
334+ AggregateMetadata that = (AggregateMetadata) other;
336335 return this.keyspace.getName().equals(that.keyspace.getName()) &&
337- this.argumentTypes.equals(that.argumentTypes) &&
338- Objects.equal(this.finalFuncFullName, that.finalFuncFullName) &&
339- // Note: this might be a problem if a custom codec has been registered for the initCond's type, with a target Java type that
340- // does not properly implement equals. We don't have any control over this, at worst this would lead to spurious change
341- // notifications.
342- Objects.equal(this.initCond, that.initCond) &&
343- this.returnType.equals(that.returnType) &&
344- this.stateFuncFullName.equals(that.stateFuncFullName) &&
345- this.stateType.equals(that.stateType);
336+ this.argumentTypes.equals(that.argumentTypes) &&
337+ Objects.equal(this.finalFuncFullName, that.finalFuncFullName) &&
338+ // Note: this might be a problem if a custom codec has been registered for the initCond's type, with a target Java type that
339+ // does not properly implement equals. We don't have any control over this, at worst this would lead to spurious change
340+ // notifications.
341+ Objects.equal(this.initCond, that.initCond) &&
342+ this.returnType.equals(that.returnType) &&
343+ this.stateFuncFullName.equals(that.stateFuncFullName) &&
344+ this.stateType.equals(that.stateType);
346345 }
347346 return false;
348347 }
@@ -350,6 +349,6 @@
350349 @Override
351350 public int hashCode() {
352351 return Objects.hashCode(this.keyspace.getName(), this.argumentTypes,
353- this.finalFuncFullName, this.initCond, this.returnType, this.stateFuncFullName, this.stateType);
352+ this.finalFuncFullName, this.initCond, this.returnType, this.stateFuncFullName, this.stateType);
354353 }
355354 }
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +16 −17
@@ -15,12 +15,8 @@
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.ConnectionException;
19+import com.datastax.driver.core.exceptions.DriverInternalError;
2420 import com.google.common.util.concurrent.Futures;
2521 import com.google.common.util.concurrent.ListenableFuture;
2622 import com.google.common.util.concurrent.SettableFuture;
@@ -28,8 +24,11 @@
2824 import org.slf4j.Logger;
2925 import org.slf4j.LoggerFactory;
3026
31-import com.datastax.driver.core.exceptions.ConnectionException;
32-import com.datastax.driver.core.exceptions.DriverInternalError;
27+import java.nio.ByteBuffer;
28+import java.util.*;
29+import java.util.concurrent.ConcurrentLinkedQueue;
30+import java.util.concurrent.ExecutionException;
31+import java.util.concurrent.LinkedBlockingDeque;
3332
3433 /**
3534 * Default implementation of a result set, backed by an ArrayDeque of ArrayList.
@@ -62,27 +61,27 @@
6261 case VOID:
6362 return empty(info);
6463 case ROWS:
65- Responses.Result.Rows r = (Responses.Result.Rows)msg;
64+ Responses.Result.Rows r = (Responses.Result.Rows) msg;
6665
6766 ColumnDefinitions columnDefs;
6867 if (r.metadata.columns == null) {
6968 assert statement instanceof BoundStatement;
70- columnDefs = ((BoundStatement)statement).statement.getPreparedId().resultSetMetadata;
69+ columnDefs = ((BoundStatement) statement).statement.getPreparedId().resultSetMetadata;
7170 assert columnDefs != null;
7271 } else {
7372 columnDefs = r.metadata.columns;
7473 }
7574
7675 Token.Factory tokenFactory = (session == null) ? null
77- : session.getCluster().manager.metadata.tokenFactory();
76+ : session.getCluster().manager.metadata.tokenFactory();
7877
7978 // info can be null only for internal calls, but we don't page those. We assert
8079 // this explicitly because MultiPage implementation don't support info == null.
8180 assert r.metadata.pagingState == null || info != null;
8281
8382 return r.metadata.pagingState == null
84- ? new SinglePage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info)
85- : new MultiPage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info, r.metadata.pagingState, session, statement);
83+ ? new SinglePage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info)
84+ : new MultiPage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info, r.metadata.pagingState, session, statement);
8685
8786 case SET_KEYSPACE:
8887 case SCHEMA_CHANGE:
@@ -107,7 +106,7 @@
107106
108107 private static ArrayBackedResultSet empty(ExecutionInfo info) {
109108 // We could pass the protocol version but we know we won't need it so passing a bogus value (null)
110- return new SinglePage(ColumnDefinitions.EMPTY, null, null, null, EMPTY_QUEUE, info);
109+ return new SinglePage(ColumnDefinitions.EMPTY, null, null, null, EMPTY_QUEUE, info);
111110 }
112111
113112 public ColumnDefinitions getColumnDefinitions() {
@@ -337,10 +336,10 @@
337336 try {
338337 switch (response.type) {
339338 case RESULT:
340- Responses.Result rm = (Responses.Result)response;
339+ Responses.Result rm = (Responses.Result) response;
341340 info = update(info, rm, MultiPage.this.session);
342341 if (rm.kind == Responses.Result.Kind.ROWS) {
343- Responses.Result.Rows rows = (Responses.Result.Rows)rm;
342+ Responses.Result.Rows rows = (Responses.Result.Rows) rm;
344343 if (rows.metadata.pagingState != null)
345344 info = info.withPagingState(rows.metadata.pagingState, protocolVersion, codecRegistry).withStatement(statement);
346345 MultiPage.this.nextPages.offer(rows.data);
@@ -360,7 +359,7 @@
360359 future.set(MultiPage.this);
361360 break;
362361 case ERROR:
363- future.setException(((Responses.Error)response).asException(connection.address));
362+ future.setException(((Responses.Error) response).asException(connection.address));
364363 break;
365364 default:
366365 // 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,12 +15,12 @@
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 import java.util.regex.Pattern;
2123
22-import com.datastax.driver.core.exceptions.DriverInternalError;
23-
2424 /**
2525 * Implementation of a Row backed by an ArrayList.
2626 */
modified driver-core/src/main/java/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.java +2 −2
@@ -20,11 +20,11 @@
2020 /**
2121 * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing atomic counter
2222 * to generate the sub-millisecond part.
23- * <p>
23+ * <p/>
2424 * This implementation guarantees incrementing timestamps among all client threads, provided that no more than
2525 * 1000 are requested for a given clock tick (the exact granularity of of {@link System#currentTimeMillis()}
2626 * depends on the operating system).
27- * <p>
27+ * <p/>
2828 * If that rate is exceeded, a warning is logged and the timestamps don't increment anymore until the next clock
2929 * tick. If you consistently exceed that rate, consider using {@link ThreadLocalMonotonicTimestampGenerator}.
3030 */
modified driver-core/src/main/java/com/datastax/driver/core/AuthProvider.java +6 −6
@@ -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,20 +30,20 @@
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, String authenticator) {
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
4343 /**
4444 * The {@code Authenticator} to use when connecting to {@code host}
4545 *
46- * @param host the Cassandra host to connect to.
46+ * @param host the Cassandra host to connect to.
4747 * @param authenticator the configured authenticator on the host.
4848 * @return The authentication implementation to use.
4949 */
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 +21 −23
@@ -15,24 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-
18+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
2119 import com.google.common.collect.ImmutableList;
2220
23-import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
21+import java.nio.ByteBuffer;
22+import java.util.*;
2423
2524 /**
2625 * A statement that groups a number of {@link Statement} so they get executed as
2726 * a batch.
28- * <p>
27+ * <p/>
2928 * Note: BatchStatement is not supported with the native protocol version 1: you
3029 * will get an {@link UnsupportedFeatureException} when submitting one if
3130 * version 1 of the protocol is in use (i.e. if you've force version 1 through
3231 * {@link Cluster.Builder#withProtocolVersion} or you use Cassandra 1.2). Note
3332 * however that you can still use <a href="http://cassandra.apache.org/doc/cql3/CQL.html#batchStmt">CQL Batch statements</a>
3433 * even with the protocol version 1.
35- * <p>
34+ * <p/>
3635 * Setting a BatchStatement's serial consistency level is only supported with the
3736 * native protocol version 3 or higher (see {@link #setSerialConsistencyLevel(ConsistencyLevel)}).
3837 */
@@ -60,7 +59,9 @@
6059 * operations and it can only contain these.
6160 */
6261 COUNTER
63- };
62+ }
63+
64+ ;
6465
6566 final Type batchType;
6667 private final List<Statement> statements = new ArrayList<Statement>();
@@ -84,10 +85,10 @@
8485 IdAndValues getIdAndValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
8586 IdAndValues idAndVals = new IdAndValues(statements.size());
8687 for (Statement statement : statements) {
87- if(statement instanceof StatementWrapper)
88+ if (statement instanceof StatementWrapper)
8889 statement = ((StatementWrapper) statement).getWrappedStatement();
8990 if (statement instanceof RegularStatement) {
90- RegularStatement st = (RegularStatement)statement;
91+ RegularStatement st = (RegularStatement) statement;
9192 ByteBuffer[] vals = st.getValues(protocolVersion, codecRegistry);
9293 String query = st.getQueryString();
9394 idAndVals.ids.add(query);
@@ -95,7 +96,7 @@
9596 } else {
9697 // We handle BatchStatement in add() so ...
9798 assert statement instanceof BoundStatement;
98- BoundStatement st = (BoundStatement)statement;
99+ BoundStatement st = (BoundStatement) statement;
99100 idAndVals.ids.add(st.statement.getPreparedId().id);
100101 idAndVals.values.add(Arrays.asList(st.wrapper.values));
101102 }
@@ -105,18 +106,18 @@
105106
106107 /**
107108 * Adds a new statement to this batch.
108- * <p>
109+ * <p/>
109110 * Note that {@code statement} can be any {@code Statement}. It is allowed to mix
110111 * {@code RegularStatement} and {@code BoundStatement} in the same
111112 * {@code BatchStatement} in particular. Adding another {@code BatchStatement}
112113 * is also allowed for convenience and is equivalent to adding all the {@code Statement}
113114 * contained in that other {@code BatchStatement}.
114- * <p>
115+ * <p/>
115116 * When adding a {@code BoundStatement}, all of its values must be set, otherwise an
116117 * {@code IllegalStateException} will be thrown when submitting the batch statement.
117118 * See {@link BoundStatement} for more details, in particular how to handle {@code null}
118119 * values.
119- * <p>
120+ * <p/>
120121 * Please note that the options of the added Statement (all those defined directly by the
121122 * {@link Statement} class: consistency level, fetch size, tracing, ...) will be ignored
122123 * for the purpose of the execution of the Batch. Instead, the options used are the one
@@ -124,10 +125,9 @@
124125 *
125126 * @param statement the new statement to add.
126127 * @return this batch statement.
127- *
128128 * @throws IllegalStateException if adding the new statement means that this
129- * {@code BatchStatement} has more than 65536 statements (since this is the maximum number
130- * of statements for a BatchStatement allowed by the underlying protocol).
129+ * {@code BatchStatement} has more than 65536 statements (since this is the maximum number
130+ * of statements for a BatchStatement allowed by the underlying protocol).
131131 */
132132 public BatchStatement add(Statement statement) {
133133
@@ -135,7 +135,7 @@
135135 // easier to avoid endless loops if the user mistakenly passes a batch that depends on this
136136 // object (or this directly).
137137 if (statement instanceof BatchStatement) {
138- for (Statement subStatements : ((BatchStatement)statement).statements) {
138+ for (Statement subStatements : ((BatchStatement) statement).statements) {
139139 add(subStatements);
140140 }
141141 } else {
@@ -148,7 +148,7 @@
148148
149149 /**
150150 * Adds multiple statements to this batch.
151- * <p>
151+ * <p/>
152152 * This is a shortcut method that calls {@link #add} on all the statements
153153 * from {@code statements}.
154154 *
@@ -192,7 +192,7 @@
192192
193193 /**
194194 * Sets the serial consistency level for the query.
195- * <p>
195+ * <p/>
196196 * This is only supported with version 3 or higher of the native protocol. If you call
197197 * this method when version 2 is in use, you will get an {@link UnsupportedFeatureException}
198198 * when submitting the statement. With version 2, protocol batches with conditions
@@ -201,10 +201,8 @@
201201 *
202202 * @param serialConsistency the serial consistency level to set.
203203 * @return this {@code Statement} object.
204- *
205204 * @throws IllegalArgumentException if {@code serialConsistency} is not one of
206- * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
207- *
205+ * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
208206 * @see Statement#setSerialConsistencyLevel(ConsistencyLevel)
209207 */
210208 @Override
@@ -215,7 +213,7 @@
215213 @Override
216214 public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
217215 for (Statement statement : statements) {
218- if(statement instanceof StatementWrapper)
216+ if (statement instanceof StatementWrapper)
219217 statement = ((StatementWrapper) statement).getWrappedStatement();
220218 ByteBuffer rk = statement.getRoutingKey(protocolVersion, codecRegistry);
221219 if (rk != null)
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +54 −66
@@ -15,34 +15,33 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.google.common.reflect.TypeToken;
20+
1821 import java.math.BigDecimal;
1922 import java.math.BigInteger;
2023 import java.net.InetAddress;
2124 import java.nio.ByteBuffer;
2225 import java.util.*;
2326
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-
2827 /**
2928 * A prepared statement with values bound to the bind variables.
30- * <p>
29+ * <p/>
3130 * Once values has been provided for the variables of the {@link PreparedStatement}
3231 * it has been created from, such BoundStatement can be executed (through
3332 * {@link Session#execute(Statement)}).
34- * <p>
33+ * <p/>
3534 * The values of a BoundStatement can be set by either index or name. When
3635 * setting them by name, names follow the case insensitivity rules explained in
3736 * {@link ColumnDefinitions} but with the difference that if multiple bind
3837 * variables have the same name, setting that name will set <b>all</b> the
3938 * variables for that name.
40- * <p>
39+ * <p/>
4140 * With native protocol V3 or below, all variables of the statement must be bound.
4241 * If you don't explicitly set a value for a variable, an {@code IllegalStateException}
4342 * will be thrown when submitting the statement. If you want to set a variable to
4443 * {@code null}, use {@link #setToNull(int) setToNull}.
45- * <p>
44+ * <p/>
4645 * With native protocol V4 or above, variables can be left unset, in which case they
4746 * will be ignored server side (no tombstones will be generated). If you're reusing
4847 * a bound statement, you can {@link #unset(int) unset} variables that were previously
@@ -64,6 +63,7 @@
6463 /**
6564 * Creates a new {@code BoundStatement} from the provided prepared
6665 * statement.
66+ *
6767 * @param statement the prepared statement from which to create a {@code BoundStatement}.
6868 */
6969 public BoundStatement(PreparedStatement statement) {
@@ -106,7 +106,6 @@
106106 *
107107 * @param i the index of the variable to check.
108108 * @return whether the {@code i}th variable has been bound.
109- *
110109 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
111110 */
112111 public boolean isSet(int i) {
@@ -120,9 +119,8 @@
120119 * @param name the name of the variable to check.
121120 * @return whether the first occurrence of variable {@code name} has been
122121 * bound to a non-null value.
123- *
124122 * @throws IllegalArgumentException if {@code name} is not a prepared
125- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
123+ * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
126124 */
127125 public boolean isSet(String name) {
128126 return wrapper.getValue(wrapper.getIndexOf(name)) != UNSET;
@@ -131,12 +129,11 @@
131129 /**
132130 * Unsets the {@code i}th variable. This will leave the statement in the same state as if no setter was
133131 * ever called for this variable.
134- * <p>
132+ * <p/>
135133 * The treatment of unset variables depends on the native protocol version, see {@link BoundStatement}
136134 * for explanations.
137135 *
138136 * @param i the index of the variable.
139- *
140137 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
141138 */
142139 public void unset(int i) {
@@ -146,14 +143,13 @@
146143 /**
147144 * Unsets all occurrences of variable {@code name}. This will leave the statement in the same state
148145 * as if no setter was ever called for this variable.
149- * <p>
146+ * <p/>
150147 * The treatment of unset variables depends on the native protocol version, see {@link BoundStatement}
151148 * for explanations.
152149 *
153150 * @param name the name of the variable.
154- *
155151 * @throws IllegalArgumentException if {@code name} is not a prepared
156- * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
152+ * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
157153 */
158154 public void unset(String name) {
159155 for (int i : wrapper.getAllIndexesOf(name)) {
@@ -163,25 +159,24 @@
163159
164160 /**
165161 * Bound values to the variables of this statement.
166- *
162+ * <p/>
167163 * This is a convenience method to bind all the variables of the
168164 * {@code BoundStatement} in one call.
169165 *
170166 * @param values the values to bind to the variables of the newly created
171- * BoundStatement. The first element of {@code values} will be bound to the
172- * first bind variable, etc. It is legal to provide fewer values than the
173- * statement has bound variables. In that case, the remaining variable need
174- * to be bound before execution. If more values than variables are provided
175- * however, an IllegalArgumentException wil be raised.
167+ * BoundStatement. The first element of {@code values} will be bound to the
168+ * first bind variable, etc. It is legal to provide fewer values than the
169+ * statement has bound variables. In that case, the remaining variable need
170+ * to be bound before execution. If more values than variables are provided
171+ * however, an IllegalArgumentException wil be raised.
176172 * @return this bound statement.
177- *
178173 * @throws IllegalArgumentException if more {@code values} are provided
179- * than there is of bound variables in this statement.
180- * @throws InvalidTypeException if any of the provided value is not of
181- * correct type to be bound to the corresponding bind variable.
182- * @throws NullPointerException if one of {@code values} is a collection
183- * (List, Set or Map) containing a null value. Nulls are not supported in
184- * collections by CQL.
174+ * than there is of bound variables in this statement.
175+ * @throws InvalidTypeException if any of the provided value is not of
176+ * correct type to be bound to the corresponding bind variable.
177+ * @throws NullPointerException if one of {@code values} is a collection
178+ * (List, Set or Map) containing a null value. Nulls are not supported in
179+ * collections by CQL.
185180 */
186181 public BoundStatement bind(Object... values) {
187182
@@ -196,7 +191,7 @@
196191 ProtocolVersion protocolVersion = statement.getPreparedId().protocolVersion;
197192 if (value instanceof Token)
198193 // bypass CodecRegistry for token values
199- wrapper.values[i] = ((Token)value).serialize(protocolVersion);
194+ wrapper.values[i] = ((Token) value).serialize(protocolVersion);
200195 else
201196 wrapper.values[i] = wrapper.codecFor(i, value).serialize(value, protocolVersion);
202197 }
@@ -206,7 +201,7 @@
206201
207202 /**
208203 * The routing key for this bound query.
209- * <p>
204+ * <p/>
210205 * This method will return a non-{@code null} value if either of the following occur:
211206 * <ul>
212207 * <li>The routing key has been set directly through {@link BoundStatement#setRoutingKey}.</li>
@@ -216,15 +211,14 @@
216211 * key will then be built using the values provided for these partition key columns.</li>
217212 * </ul>
218213 * Otherwise, {@code null} is returned.
219- * <p>
220- *
214+ * <p/>
215+ * <p/>
221216 * Note that if the routing key has been set through {@link BoundStatement#setRoutingKey}, then that takes
222217 * precedence. If the routing key has been set through {@link PreparedStatement#setRoutingKey} then that is used
223218 * next. If neither of those are set then it is computed.
224219 *
225220 * @param protocolVersion unused by this implementation (no internal serialization is required to compute the key).
226- * @param codecRegistry unused by this implementation (no internal serialization is required to compute the key).
227- *
221+ * @param codecRegistry unused by this implementation (no internal serialization is required to compute the key).
228222 * @return the routing key for this statement or {@code null}.
229223 */
230224 @Override
@@ -257,14 +251,13 @@
257251
258252 /**
259253 * Sets the routing key for this bound statement.
260- * <p>
254+ * <p/>
261255 * This is useful when the routing key can neither be set on the {@code PreparedStatement} this bound statement
262256 * was built from, nor automatically computed from bound variables. In particular, this is the case if the
263257 * partition key is composite and only some of its components are bound.
264258 *
265259 * @param routingKey the raw (binary) value to use as routing key.
266260 * @return this {@code BoundStatement} object.
267- *
268261 * @see BoundStatement#getRoutingKey
269262 */
270263 public BoundStatement setRoutingKey(ByteBuffer routingKey) {
@@ -366,9 +359,8 @@
366359 * @param i the index of the variable to set.
367360 * @param v the value to set.
368361 * @return this BoundStatement.
369- *
370362 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
371- * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
363+ * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
372364 * @deprecated deprecated in favor of {@link #setTimestamp(int, Date)}
373365 */
374366 @Deprecated
@@ -381,14 +373,13 @@
381373 * provided date.
382374 *
383375 * @param name the name of the variable to set; if multiple variables
384- * {@code name} are prepared, all of them are set.
385- * @param v the value to set.
376+ * {@code name} are prepared, all of them are set.
377+ * @param v the value to set.
386378 * @return this BoundStatement.
387- *
388379 * @throws IllegalArgumentException if {@code name} is not a prepared
389- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
390- * @throws InvalidTypeException if (any occurrence of) {@code name} is
391- * not of type TIMESTAMP.
380+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
381+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
382+ * not of type TIMESTAMP.
392383 * @deprecated deprecated in favor of {@link #setTimestamp(String, Date)}
393384 */
394385 @Deprecated
@@ -590,16 +581,15 @@
590581
591582 /**
592583 * Sets the {@code i}th value to the provided {@link Token}.
593- * <p>
584+ * <p/>
594585 * {@link #setPartitionKeyToken(Token)} should generally be preferred if you
595586 * have a single token variable.
596587 *
597588 * @param i the index of the variable to set.
598589 * @param v the value to set.
599590 * @return this BoundStatement.
600- *
601591 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
602- * @throws InvalidTypeException if column {@code i} is not of the type of the token's value.
592+ * @throws InvalidTypeException if column {@code i} is not of the type of the token's value.
603593 */
604594 public BoundStatement setToken(int i, Token v) {
605595 return wrapper.setToken(i, v);
@@ -608,10 +598,10 @@
608598 /**
609599 * Sets the value for (all occurrences of) variable {@code name} to the
610600 * provided token.
611- * <p>
601+ * <p/>
612602 * {@link #setPartitionKeyToken(Token)} should generally be preferred if you
613603 * have a single token variable.
614- * <p>
604+ * <p/>
615605 * If you have multiple token variables, use positional binding ({@link #setToken(int, Token)},
616606 * or named bind markers:
617607 * <pre>
@@ -622,14 +612,13 @@
622612 * </pre>
623613 *
624614 * @param name the name of the variable to set; if multiple variables
625- * {@code name} are prepared, all of them are set.
626- * @param v the value to set.
615+ * {@code name} are prepared, all of them are set.
616+ * @param v the value to set.
627617 * @return this BoundStatement.
628- *
629618 * @throws IllegalArgumentException if {@code name} is not a prepared
630- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
631- * @throws InvalidTypeException if (any occurrence of) {@code name} is
632- * not of the type of the token's value.
619+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
620+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
621+ * not of the type of the token's value.
633622 */
634623 public BoundStatement setToken(String name, Token v) {
635624 return wrapper.setToken(name, v);
@@ -639,7 +628,7 @@
639628 * Sets the value for (all occurrences of) variable "{@code partition key token}"
640629 * to the provided token (this is the name generated by Cassandra for markers
641630 * corresponding to a {@code token(...)} call).
642- * <p>
631+ * <p/>
643632 * This method is a shorthand for statements with a single token variable:
644633 * <pre>
645634 * {@code
@@ -659,11 +648,10 @@
659648 *
660649 * @param v the value to set.
661650 * @return this BoundStatement.
662- *
663651 * @throws IllegalArgumentException if {@code name} is not a prepared
664- * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
665- * @throws InvalidTypeException if (any occurrence of) {@code name} is
666- * not of the type of the token's value.
652+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
653+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
654+ * not of the type of the token's value.
667655 */
668656 public BoundStatement setPartitionKeyToken(Token v) {
669657 return setToken("partition key token", v);
@@ -730,7 +718,7 @@
730718 */
731719 @Override
732720 public <K, V> BoundStatement setMap(int i, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass) {
733- return wrapper.setMap(i,v, keysClass, valuesClass);
721+ return wrapper.setMap(i, v, keysClass, valuesClass);
734722 }
735723
736724 /**
@@ -812,7 +800,7 @@
812800 public <E> BoundStatement setSet(String name, Set<E> v, TypeToken<E> elementsType) {
813801 return wrapper.setSet(name, v, elementsType);
814802 }
815-
803+
816804 /**
817805 * {@inheritDoc}
818806 */
@@ -1393,10 +1381,10 @@
13931381 void ensureAllSet() {
13941382 int index = 0;
13951383 for (ByteBuffer value : wrapper.values) {
1396- if (value == BoundStatement.UNSET)
1384+ if (value == BoundStatement.UNSET)
13971385 throw new IllegalStateException("Unset value at index " + index + ". "
1398- + "If you want this value to be null, please set it to null explicitly.");
1399- index += 1;
1386+ + "If you want this value to be null, please set it to null explicitly.");
1387+ index += 1;
14001388 }
14011389 }
14021390
modified driver-core/src/main/java/com/datastax/driver/core/CBUtil.java +7 −7
@@ -15,6 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.google.common.collect.ImmutableMap;
20+import io.netty.buffer.ByteBuf;
21+import io.netty.util.CharsetUtil;
22+
1823 import java.net.InetAddress;
1924 import java.net.InetSocketAddress;
2025 import java.net.UnknownHostException;
@@ -22,18 +27,13 @@
2227 import java.nio.charset.CharacterCodingException;
2328 import java.util.*;
2429
25-import com.google.common.collect.ImmutableMap;
26-import io.netty.buffer.ByteBuf;
27-import io.netty.util.CharsetUtil;
28-
29-import com.datastax.driver.core.exceptions.DriverInternalError;
30-
3130 /**
3231 * ByteBuf utility methods.
3332 */
3433 abstract class CBUtil { // TODO rename
3534
36- private CBUtil() {}
35+ private CBUtil() {
36+ }
3737
3838 private static String readString(ByteBuf cb, int length) {
3939 try {
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 +214 −233
@@ -15,16 +15,9 @@
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.*;
19+import com.datastax.driver.core.policies.*;
20+import com.datastax.driver.core.utils.MoreFutures;
2821 import com.google.common.annotations.VisibleForTesting;
2922 import com.google.common.base.Functions;
3023 import com.google.common.base.Predicates;
@@ -34,15 +27,21 @@
3427 import org.slf4j.Logger;
3528 import org.slf4j.LoggerFactory;
3629
37-import com.datastax.driver.core.exceptions.*;
38-import com.datastax.driver.core.policies.*;
39-import com.datastax.driver.core.utils.MoreFutures;
30+import java.io.Closeable;
31+import java.net.InetAddress;
32+import java.net.InetSocketAddress;
33+import java.net.UnknownHostException;
34+import java.util.*;
35+import java.util.Map.Entry;
36+import java.util.concurrent.*;
37+import java.util.concurrent.atomic.AtomicInteger;
38+import java.util.concurrent.atomic.AtomicReference;
4039
4140 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
4241
4342 /**
4443 * Information and known state of a Cassandra cluster.
45- * <p>
44+ * <p/>
4645 * This is the main entry point of the driver. A simple example of access to a
4746 * Cassandra cluster would be:
4847 * <pre>
@@ -52,7 +51,7 @@
5251 * for (Row row : session.execute("SELECT * FROM table1"))
5352 * // do something ...
5453 * </pre>
55- * <p>
54+ * <p/>
5655 * A cluster object maintains a permanent connection to one of the cluster nodes
5756 * which it uses solely to maintain information on the state and current
5857 * topology of the cluster. Using the connection, the driver will discover all
@@ -71,7 +70,7 @@
7170 @VisibleForTesting
7271 static final int NEW_NODE_DELAY_SECONDS = SystemProperties.getInt("com.datastax.driver.NEW_NODE_DELAY_SECONDS", 1);
7372 private static final int NON_BLOCKING_EXECUTOR_SIZE = SystemProperties.getInt("com.datastax.driver.NON_BLOCKING_EXECUTOR_SIZE",
74- Runtime.getRuntime().availableProcessors());
73+ Runtime.getRuntime().availableProcessors());
7574
7675 private static final ResourceBundle driverProperties = ResourceBundle.getBundle("com.datastax.driver.core.Driver");
7776
@@ -87,13 +86,13 @@
8786
8887 /**
8988 * Constructs a new Cluster instance.
90- * <p>
89+ * <p/>
9190 * This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking
9291 * easier or to "intercept" its method call. Most users shouldn't extend this class however and
9392 * should prefer either using the {@link #builder} or calling {@link #buildFrom} with a custom
9493 * Initializer.
9594 *
96- * @param name the name to use for the cluster (this is not the Cassandra cluster name, see {@link #getClusterName}).
95+ * @param name the name to use for the cluster (this is not the Cassandra cluster name, see {@link #getClusterName}).
9796 * @param contactPoints the list of contact points to use for the new cluster.
9897 * @param configuration the configuration for the new cluster.
9998 */
@@ -103,7 +102,7 @@
103102
104103 /**
105104 * Constructs a new Cluster instance.
106- * <p>
105+ * <p/>
107106 * This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking
108107 * easier or to "intercept" its method call. Most users shouldn't extend this class however and
109108 * should prefer using the {@link #builder}.
@@ -113,9 +112,9 @@
113112 */
114113 protected Cluster(Initializer initializer) {
115114 this(initializer.getClusterName(),
116- checkNotEmpty(initializer.getContactPoints()),
117- initializer.getConfiguration(),
118- initializer.getInitialListeners());
115+ checkNotEmpty(initializer.getContactPoints()),
116+ initializer.getConfiguration(),
117+ initializer.getInitialListeners());
119118 }
120119
121120 private static List<InetSocketAddress> checkNotEmpty(List<InetSocketAddress> contactPoints) {
@@ -130,35 +129,34 @@
130129
131130 /**
132131 * Initialize this Cluster instance.
133- *
132+ * <p/>
134133 * This method creates an initial connection to one of the contact points
135134 * used to construct the {@code Cluster} instance. That connection is then
136135 * used to populate the cluster {@link Metadata}.
137- * <p>
136+ * <p/>
138137 * Calling this method is optional in the sense that any call to one of the
139138 * {@code connect} methods of this object will automatically trigger a call
140139 * to this method beforehand. It is thus only useful to call this method if
141140 * for some reason you want to populate the metadata (or test that at least
142141 * one contact point can be reached) without creating a first {@code
143142 * Session}.
144- * <p>
143+ * <p/>
145144 * Please note that this method only creates one control connection for
146145 * gathering cluster metadata. In particular, it doesn't create any connection pools.
147146 * Those are created when a new {@code Session} is created through
148147 * {@code connect}.
149- * <p>
148+ * <p/>
150149 * This method has no effect if the cluster is already initialized.
151150 *
152151 * @return this {@code Cluster} object.
153- *
154152 * @throws NoHostAvailableException if no host amongst the contact points
155- * can be reached.
156- * @throws AuthenticationException if an authentication error occurs
157- * while contacting the initial contact points.
158- * @throws IllegalStateException if the Cluster was closed prior to calling
159- * this method. This can occur either directly (through {@link #close()} or
160- * {@link #closeAsync()}), or as a result of an error while initializing the
161- * Cluster.
153+ * can be reached.
154+ * @throws AuthenticationException if an authentication error occurs
155+ * while contacting the initial contact points.
156+ * @throws IllegalStateException if the Cluster was closed prior to calling
157+ * this method. This can occur either directly (through {@link #close()} or
158+ * {@link #closeAsync()}), or as a result of an error while initializing the
159+ * Cluster.
162160 */
163161 public Cluster init() {
164162 this.manager.init();
@@ -167,18 +165,17 @@
167165
168166 /**
169167 * Build a new cluster based on the provided initializer.
170- * <p>
168+ * <p/>
171169 * Note that for building a cluster pragmatically, Cluster.Builder
172170 * provides a slightly less verbose shortcut with {@link Builder#build}.
173- * <p>
171+ * <p/>
174172 * Also note that that all the contact points provided by {@code
175173 * initializer} must share the same port.
176174 *
177175 * @param initializer the Cluster.Initializer to use
178176 * @return the newly created Cluster instance
179- *
180177 * @throws IllegalArgumentException if the list of contact points provided
181- * by {@code initializer} is empty or if not all those contact points have the same port.
178+ * by {@code initializer} is empty or if not all those contact points have the same port.
182179 */
183180 public static Cluster buildFrom(Initializer initializer) {
184181 return new Cluster(initializer);
@@ -186,7 +183,7 @@
186183
187184 /**
188185 * Creates a new {@link Cluster.Builder} instance.
189- * <p>
186+ * <p/>
190187 * This is a convenience method for {@code new Cluster.Builder()}.
191188 *
192189 * @return the new cluster builder.
@@ -197,7 +194,7 @@
197194
198195 /**
199196 * Returns the current version of the driver.
200- * <p>
197+ * <p/>
201198 * This is intended for products that wrap or extend the driver, as a way to check
202199 * compatibility if end-users override the driver version in their application.
203200 *
@@ -209,16 +206,16 @@
209206
210207 /**
211208 * Creates a new session on this cluster but does not initialize it.
212- * <p>
209+ * <p/>
213210 * Because this method does not perform any initialization, it cannot fail.
214211 * The initialization of the session (the connection of the Session to the
215212 * Cassandra nodes) will occur if either the {@link Session#init} method is
216213 * called explicitly, or whenever the returned session object is used.
217- * <p>
214+ * <p/>
218215 * Once a session returned by this method gets initialized (see above), it
219216 * will be set to no keyspace. If you want to set such session to a
220217 * keyspace, you will have to explicitly execute a 'USE mykeyspace' query.
221- * <p>
218+ * <p/>
222219 * Note that if you do not particularly need to defer initialization, it is
223220 * simpler to use one of the {@code connect()} method of this class.
224221 *
@@ -231,23 +228,22 @@
231228
232229 /**
233230 * Creates a new session on this cluster and initialize it.
234- * <p>
231+ * <p/>
235232 * Note that this method will initialize the newly created session, trying
236233 * to connect to the Cassandra nodes before returning. If you only want to
237234 * create a Session object without initializing it right away, see
238235 * {@link #newSession}.
239236 *
240237 * @return a new session on this cluster sets to no keyspace.
241- *
242238 * @throws NoHostAvailableException if the Cluster has not been initialized
243- * yet ({@link #init} has not be called and this is the first connect call)
244- * and no host amongst the contact points can be reached.
245- * @throws AuthenticationException if an authentication error occurs while
246- * contacting the initial contact points.
247- * @throws IllegalStateException if the Cluster was closed prior to calling
248- * this method. This can occur either directly (through {@link #close()} or
249- * {@link #closeAsync()}), or as a result of an error while initializing the
250- * Cluster.
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.
251247 */
252248 public Session connect() {
253249 try {
@@ -260,28 +256,27 @@
260256 /**
261257 * Creates a new session on this cluster, initialize it and sets the
262258 * keyspace to the provided one.
263- * <p>
259+ * <p/>
264260 * Note that this method will initialize the newly created session, trying
265261 * to connect to the Cassandra nodes before returning. If you only want to
266262 * create a Session object without initializing it right away, see
267263 * {@link #newSession}.
268264 *
269265 * @param keyspace The name of the keyspace to use for the created
270- * {@code Session}.
266+ * {@code Session}.
271267 * @return a new session on this cluster sets to keyspace
272268 * {@code keyspaceName}.
273- *
274269 * @throws NoHostAvailableException if the Cluster has not been initialized
275- * yet ({@link #init} has not be called and this is the first connect call)
276- * and no host amongst the contact points can be reached, or if no host can
277- * be contacted to set the {@code keyspace}.
278- * @throws AuthenticationException if an authentication error occurs while
279- * contacting the initial contact points.
280- * @throws InvalidQueryException if the keyspace does not exist.
281- * @throws IllegalStateException if the Cluster was closed prior to calling
282- * this method. This can occur either directly (through {@link #close()} or
283- * {@link #closeAsync()}), or as a result of an error while initializing the
284- * Cluster.
270+ * yet ({@link #init} has not be called and this is the first connect call)
271+ * and no host amongst the contact points can be reached, or if no host can
272+ * be contacted to set the {@code keyspace}.
273+ * @throws AuthenticationException if an authentication error occurs while
274+ * contacting the initial contact points.
275+ * @throws InvalidQueryException if the keyspace does not exist.
276+ * @throws IllegalStateException if the Cluster was closed prior to calling
277+ * this method. This can occur either directly (through {@link #close()} or
278+ * {@link #closeAsync()}), or as a result of an error while initializing the
279+ * Cluster.
285280 */
286281 public Session connect(String keyspace) {
287282 try {
@@ -293,23 +288,20 @@
293288
294289 /**
295290 * Creates a new session on this cluster and initializes it asynchronously.
296- *
291+ * <p/>
297292 * This will also initialize the {@code Cluster} if needed; note that cluster
298293 * initialization happens synchronously on the thread that called this method.
299294 * Therefore it is recommended to initialize the cluster at application
300295 * startup, and not rely on this method to do it.
301296 *
302297 * @return a future that will complete when the session is fully initialized.
303- *
304298 * @throws NoHostAvailableException if the Cluster has not been initialized
305- * yet ({@link #init} has not been called and this is the first connect call)
306- * and no host amongst the contact points can be reached.
307- *
308- * @throws IllegalStateException if the Cluster was closed prior to calling
309- * this method. This can occur either directly (through {@link #close()} or
310- * {@link #closeAsync()}), or as a result of an error while initializing the
311- * Cluster.
312- *
299+ * yet ({@link #init} has not been called and this is the first connect call)
300+ * and no host amongst the contact points can be reached.
301+ * @throws IllegalStateException if the Cluster was closed prior to calling
302+ * this method. This can occur either directly (through {@link #close()} or
303+ * {@link #closeAsync()}), or as a result of an error while initializing the
304+ * Cluster.
313305 * @see #connect()
314306 */
315307 public ListenableFuture<Session> connectAsync() {
@@ -319,24 +311,22 @@
319311 /**
320312 * Creates a new session on this cluster, and initializes it to the given
321313 * keyspace asynchronously.
322- *
314+ * <p/>
323315 * This will also initialize the {@code Cluster} if needed; note that cluster
324316 * initialization happens synchronously on the thread that called this method.
325317 * Therefore it is recommended to initialize the cluster at application
326318 * startup, and not rely on this method to do it.
327319 *
328320 * @param keyspace The name of the keyspace to use for the created
329- * {@code Session}.
321+ * {@code Session}.
330322 * @return a future that will complete when the session is fully initialized.
331- *
332323 * @throws NoHostAvailableException if the Cluster has not been initialized
333- * yet ({@link #init} has not been called and this is the first connect call)
334- * and no host amongst the contact points can be reached.
335- *
336- * @throws IllegalStateException if the Cluster was closed prior to calling
337- * this method. This can occur either directly (through {@link #close()} or
338- * {@link #closeAsync()}), or as a result of an error while initializing the
339- * Cluster.
324+ * yet ({@link #init} has not been called and this is the first connect call)
325+ * and no host amongst the contact points can be reached.
326+ * @throws IllegalStateException if the Cluster was closed prior to calling
327+ * this method. This can occur either directly (through {@link #close()} or
328+ * {@link #closeAsync()}), or as a result of an error while initializing the
329+ * Cluster.
340330 */
341331 public ListenableFuture<Session> connectAsync(final String keyspace) {
342332 checkNotClosed(manager);
@@ -364,7 +354,7 @@
364354
365355 /**
366356 * The name of this cluster object.
367- * <p>
357+ * <p/>
368358 * Note that this is not the Cassandra cluster name, but rather a name
369359 * assigned to this Cluster object. Currently, that name is only used
370360 * for one purpose: to distinguish exposed JMX metrics when multiple
@@ -382,7 +372,7 @@
382372
383373 /**
384374 * Returns read-only metadata on the connected cluster.
385- * <p>
375+ * <p/>
386376 * This includes the known nodes with their status as seen by the driver,
387377 * as well as the schema definitions. Since this return metadata on the
388378 * connected cluster, this method may trigger the creation of a connection
@@ -390,15 +380,14 @@
390380 * has been called yet).
391381 *
392382 * @return the cluster metadata.
393- *
394383 * @throws NoHostAvailableException if the Cluster has not been initialized yet
395- * and no host amongst the contact points can be reached.
396- * @throws AuthenticationException if an authentication error occurs
397- * while contacting the initial contact points.
398- * @throws IllegalStateException if the Cluster was closed prior to calling
399- * this method. This can occur either directly (through {@link #close()} or
400- * {@link #closeAsync()}), or as a result of an error while initializing the
401- * Cluster.
384+ * and no host amongst the contact points can be reached.
385+ * @throws AuthenticationException if an authentication error occurs
386+ * while contacting the initial contact points.
387+ * @throws IllegalStateException if the Cluster was closed prior to calling
388+ * this method. This can occur either directly (through {@link #close()} or
389+ * {@link #closeAsync()}), or as a result of an error while initializing the
390+ * Cluster.
402391 */
403392 public Metadata getMetadata() {
404393 manager.init();
@@ -429,9 +418,9 @@
429418 /**
430419 * Registers the provided listener to be notified on hosts
431420 * up/down/added/removed events.
432- * <p>
421+ * <p/>
433422 * Registering the same listener multiple times is a no-op.
434- * <p>
423+ * <p/>
435424 * This method should be used to register additional listeners
436425 * on an already-initialized cluster.
437426 * To add listeners to a cluster object prior to its initialization,
@@ -453,7 +442,7 @@
453442
454443 /**
455444 * Unregisters the provided listener from being notified on hosts events.
456- * <p>
445+ * <p/>
457446 * This method is a no-op if {@code listener} hasn't previously been
458447 * registered against this Cluster.
459448 *
@@ -470,15 +459,15 @@
470459 /**
471460 * Registers the provided tracker to be updated with hosts read
472461 * latencies.
473- * <p>
462+ * <p/>
474463 * Registering the same listener multiple times is a no-op.
475- * <p>
464+ * <p/>
476465 * Beware that the registered tracker's
477466 * {@link LatencyTracker#update(Host, Statement, Exception, long) update}
478467 * method will be called
479468 * very frequently (at the end of every query to a Cassandra host) and
480469 * should thus not be costly.
481- * <p>
470+ * <p/>
482471 * The main use case for a {@link LatencyTracker} is to allow
483472 * load balancing policies to implement latency awareness.
484473 * For example, {@link LatencyAwarePolicy} registers it's own internal
@@ -498,7 +487,7 @@
498487 /**
499488 * Unregisters the provided latency tracking from being updated
500489 * with host read latencies.
501- * <p>
490+ * <p/>
502491 * This method is a no-op if {@code tracker} hasn't previously been
503492 * registered against this Cluster.
504493 *
@@ -514,7 +503,7 @@
514503
515504 /**
516505 * Registers the provided listener to be updated with schema change events.
517- * <p>
506+ * <p/>
518507 * Registering the same listener multiple times is a no-op.
519508 *
520509 * @param listener the new {@link SchemaChangeListener} to register.
@@ -530,7 +519,7 @@
530519 /**
531520 * Unregisters the provided schema change listener from being updated
532521 * with schema change events.
533- * <p>
522+ * <p/>
534523 * This method is a no-op if {@code listener} hasn't previously been
535524 * registered against this Cluster.
536525 *
@@ -546,17 +535,17 @@
546535
547536 /**
548537 * Initiates a shutdown of this cluster instance.
549- * <p>
538+ * <p/>
550539 * This method is asynchronous and return a future on the completion
551540 * of the shutdown process. As soon a the cluster is shutdown, no
552541 * new request will be accepted, but already submitted queries are
553542 * allowed to complete. This method closes all connections from all
554543 * sessions and reclaims all resources used by this Cluster
555544 * instance.
556- * <p>
545+ * <p/>
557546 * If for some reason you wish to expedite this process, the
558547 * {@link CloseFuture#force} can be called on the result future.
559- * <p>
548+ * <p/>
560549 * This method has no particular effect if the cluster was already closed
561550 * (in which case the returned future will return immediately).
562551 *
@@ -569,7 +558,7 @@
569558 /**
570559 * Initiates a shutdown of this cluster instance and blocks until
571560 * that shutdown completes.
572- * <p>
561+ * <p/>
573562 * This method is a shortcut for {@code closeAsync().get()}.
574563 */
575564 public void close() {
@@ -584,7 +573,7 @@
584573
585574 /**
586575 * Whether this Cluster instance has been closed.
587- * <p>
576+ * <p/>
588577 * Note that this method returns true as soon as one of the close methods
589578 * ({@link #closeAsync} or {@link #close}) has been called, it does not guarantee
590579 * that the closing is done. If you want to guarantee that the closing is done,
@@ -605,11 +594,11 @@
605594
606595 /**
607596 * Initializer for {@link Cluster} instances.
608- * <p>
597+ * <p/>
609598 * If you want to create a new {@code Cluster} instance programmatically,
610599 * then it is advised to use {@link Cluster.Builder} which can be obtained from the
611600 * {@link Cluster#builder} method.
612- * <p>
601+ * <p/>
613602 * But it is also possible to implement a custom {@code Initializer} that
614603 * retrieves initialization from a web-service or from a configuration file.
615604 */
@@ -617,7 +606,7 @@
617606
618607 /**
619608 * An optional name for the created cluster.
620- * <p>
609+ * <p/>
621610 * Such name is optional (a default name will be created otherwise) and is currently
622611 * only use for JMX reporting of metrics. See {@link Cluster#getClusterName} for more
623612 * information.
@@ -637,15 +626,15 @@
637626
638627 /**
639628 * The configuration to use for the new cluster.
640- * <p>
629+ * <p/>
641630 * Note that some configuration can be modified after the cluster
642631 * initialization but some others cannot. In particular, the ones that
643632 * cannot be changed afterwards includes:
644633 * <ul>
645- * <li>the port use to connect to Cassandra nodes (see {@link ProtocolOptions}).</li>
646- * <li>the policies used (see {@link Policies}).</li>
647- * <li>the authentication info provided (see {@link Configuration}).</li>
648- * <li>whether metrics are enabled (see {@link Configuration}).</li>
634+ * <li>the port use to connect to Cassandra nodes (see {@link ProtocolOptions}).</li>
635+ * <li>the policies used (see {@link Policies}).</li>
636+ * <li>the authentication info provided (see {@link Configuration}).</li>
637+ * <li>whether metrics are enabled (see {@link Configuration}).</li>
649638 * </ul>
650639 *
651640 * @return the configuration to use for the new cluster.
@@ -654,7 +643,7 @@
654643
655644 /**
656645 * Optional listeners to register against the newly created cluster.
657- * <p>
646+ * <p/>
658647 * Note that contrary to listeners registered post Cluster creation,
659648 * the listeners returned by this method will see {@link Host.StateListener#onAdd}
660649 * events for the initial contact points.
@@ -706,11 +695,11 @@
706695
707696 /**
708697 * An optional name for the create cluster.
709- * <p>
698+ * <p/>
710699 * Note: this is not related to the Cassandra cluster name (though you
711700 * are free to provide the same name). See {@link Cluster#getClusterName} for
712701 * details.
713- * <p>
702+ * <p/>
714703 * If you use this method and create more than one Cluster instance in the
715704 * same JVM (which should be avoided unless you need to connect to multiple
716705 * Cassandra clusters), you should make sure each Cluster instance get a
@@ -726,7 +715,7 @@
726715
727716 /**
728717 * The port to use to connect to the Cassandra host.
729- * <p>
718+ * <p/>
730719 * If not set through this method, the default port (9042) will be used
731720 * instead.
732721 *
@@ -740,12 +729,11 @@
740729
741730 /**
742731 * Sets the maximum time to wait for schema agreement before returning from a DDL query.
743- * <p>
732+ * <p/>
744733 * If not set through this method, the default value (10 seconds) will be used.
745734 *
746735 * @param maxSchemaAgreementWaitSeconds the new value to set.
747736 * @return this Builder.
748- *
749737 * @throws IllegalStateException if the provided value is zero or less.
750738 */
751739 public Builder withMaxSchemaAgreementWaitSeconds(int maxSchemaAgreementWaitSeconds) {
@@ -758,19 +746,19 @@
758746
759747 /**
760748 * The native protocol version to use.
761- * <p>
749+ * <p/>
762750 * The driver supports versions 1 to 3 of the native protocol. Higher versions
763751 * of the protocol have more features and should be preferred, but this also depends
764752 * on the Cassandra version:
765- *
753+ * <p/>
766754 * <table>
767- * <caption>Native protocol version to Cassandra version correspondence</caption>
768- * <tr><th>Protocol version</th><th>Minimum Cassandra version</th></tr>
769- * <tr><td>1</td><td>1.2</td></tr>
770- * <tr><td>2</td><td>2.0</td></tr>
771- * <tr><td>3</td><td>2.1</td></tr>
755+ * <caption>Native protocol version to Cassandra version correspondence</caption>
756+ * <tr><th>Protocol version</th><th>Minimum Cassandra version</th></tr>
757+ * <tr><td>1</td><td>1.2</td></tr>
758+ * <tr><td>2</td><td>2.0</td></tr>
759+ * <tr><td>3</td><td>2.1</td></tr>
772760 * </table>
773- * <p>
761+ * <p/>
774762 * By default, the driver will "auto-detect" which protocol version it can use
775763 * when connecting to the first node. More precisely, it will try first with
776764 * {@link ProtocolVersion#NEWEST_SUPPORTED}, and if not supported fallback to
@@ -779,7 +767,7 @@
779767 * the driver connects to is a Cassandra 1.2 node and auto-detection is used
780768 * (the default), then the native protocol version 1 will be use for the lifetime
781769 * of the Cluster instance.
782- * <p>
770+ * <p/>
783771 * This method allows to force the use of a particular protocol version. Forcing
784772 * version 1 is always fine since all Cassandra version (at least all those
785773 * supporting the native protocol in the first place) so far support it. However,
@@ -790,17 +778,17 @@
790778 * an UnsupportedFeatureException). Using the protocol version 1 should thus
791779 * only be considered when using Cassandra 1.2, until nodes have been upgraded
792780 * to Cassandra 2.0.
793- * <p>
781+ * <p/>
794782 * If version 2 of the protocol is used, then Cassandra 1.2 nodes will be ignored
795783 * (the driver won't connect to them).
796- * <p>
784+ * <p/>
797785 * The default behavior (auto-detection) is fine in almost all case, but you may
798786 * want to force a particular version if you have a Cassandra cluster with mixed
799787 * 1.2/2.0 nodes (i.e. during a Cassandra upgrade).
800788 *
801789 * @param version the native protocol version to use. {@code null} is also supported
802- * to trigger auto-detection (see above) but this is the default (so you don't have
803- * to call this method for that behavior).
790+ * to trigger auto-detection (see above) but this is the default (so you don't have
791+ * to call this method for that behavior).
804792 * @return this Builder.
805793 */
806794 public Builder withProtocolVersion(ProtocolVersion version) {
@@ -811,32 +799,31 @@
811799 /**
812800 * Adds a contact point - or many if it host resolves to multiple
813801 * <code>InetAddress</code>s (A records).
814- * <p>
802+ * <p/>
815803 * Contact points are addresses of Cassandra nodes that the driver uses
816804 * to discover the cluster topology. Only one contact point is required
817805 * (the driver will retrieve the address of the other nodes
818806 * automatically), but it is usually a good idea to provide more than
819807 * one contact point, because if that single contact point is unavailable,
820808 * the driver cannot initialize itself correctly.
821- * <p>
809+ * <p/>
822810 * Note that by default (that is, unless you use the {@link #withLoadBalancingPolicy})
823811 * method of this builder), the first succesfully contacted host will be used
824812 * to define the local data-center for the client. If follows that if you are
825813 * running Cassandra in a multiple data-center setting, it is a good idea to
826814 * only provide contact points that are in the same datacenter than the client,
827815 * or to provide manually the load balancing policy that suits your need.
828- * <p>
816+ * <p/>
829817 * If the host name points to a DNS record with multiple a-records, all InetAddresses
830818 * returned will be used. Make sure that all resulting <code>InetAddress</code>s returned
831819 * point to the same cluster and datacenter.
832-
820+ *
833821 * @param address the address of the node(s) to connect to
834822 * @return this Builder.
835- *
836823 * @throws IllegalArgumentException if no IP address for {@code address}
837- * could be found
838- * @throws SecurityException if a security manager is present and
839- * permission to resolve the host name is denied.
824+ * could be found
825+ * @throws SecurityException if a security manager is present and
826+ * permission to resolve the host name is denied.
840827 */
841828 public Builder addContactPoint(String address) {
842829 // We explicitely check for nulls because InetAdress.getByName() will happily
@@ -855,18 +842,16 @@
855842
856843 /**
857844 * Adds contact points.
858- * <p>
845+ * <p/>
859846 * See {@link Builder#addContactPoint} for more details on contact
860847 * points.
861848 *
862849 * @param addresses addresses of the nodes to add as contact point.
863850 * @return this Builder.
864- *
865851 * @throws IllegalArgumentException if no IP address for at least one
866- * of {@code addresses} could be found
867- * @throws SecurityException if a security manager is present and
868- * permission to resolve the host name is denied.
869- *
852+ * of {@code addresses} could be found
853+ * @throws SecurityException if a security manager is present and
854+ * permission to resolve the host name is denied.
870855 * @see Builder#addContactPoint
871856 */
872857 public Builder addContactPoints(String... addresses) {
@@ -877,13 +862,12 @@
877862
878863 /**
879864 * Adds contact points.
880- * <p>
865+ * <p/>
881866 * See {@link Builder#addContactPoint} for more details on contact
882867 * points.
883868 *
884869 * @param addresses addresses of the nodes to add as contact point.
885870 * @return this Builder.
886- *
887871 * @see Builder#addContactPoint
888872 */
889873 public Builder addContactPoints(InetAddress... addresses) {
@@ -893,13 +877,12 @@
893877
894878 /**
895879 * Adds contact points.
896- *
880+ * <p/>
897881 * See {@link Builder#addContactPoint} for more details on contact
898882 * points.
899883 *
900884 * @param addresses addresses of the nodes to add as contact point
901885 * @return this Builder
902- *
903886 * @see Builder#addContactPoint
904887 */
905888 public Builder addContactPoints(Collection<InetAddress> addresses) {
@@ -909,7 +892,7 @@
909892
910893 /**
911894 * Adds contact points.
912- * <p>
895+ * <p/>
913896 * See {@link Builder#addContactPoint} for more details on contact
914897 * points. Contrarily to other {@code addContactPoints} methods, this method
915898 * allow to provide a different port for each contact points. Since Cassandra
@@ -926,7 +909,6 @@
926909 *
927910 * @param addresses addresses of the nodes to add as contact point
928911 * @return this Builder
929- *
930912 * @see Builder#addContactPoint
931913 */
932914 public Builder addContactPointsWithPorts(Collection<InetSocketAddress> addresses) {
@@ -936,7 +918,7 @@
936918
937919 /**
938920 * Configures the load balancing policy to use for the new cluster.
939- * <p>
921+ * <p/>
940922 * If no load balancing policy is set through this method,
941923 * {@link Policies#defaultLoadBalancingPolicy} will be used instead.
942924 *
@@ -950,7 +932,7 @@
950932
951933 /**
952934 * Configures the reconnection policy to use for the new cluster.
953- * <p>
935+ * <p/>
954936 * If no reconnection policy is set through this method,
955937 * {@link Policies#DEFAULT_RECONNECTION_POLICY} will be used instead.
956938 *
@@ -964,7 +946,7 @@
964946
965947 /**
966948 * Configures the retry policy to use for the new cluster.
967- * <p>
949+ * <p/>
968950 * If no retry policy is set through this method,
969951 * {@link Policies#DEFAULT_RETRY_POLICY} will be used instead.
970952 *
@@ -978,7 +960,7 @@
978960
979961 /**
980962 * Configures the address translator to use for the new cluster.
981- * <p>
963+ * <p/>
982964 * See {@link AddressTranslator} for more detail on address translation,
983965 * but the default translator, {@link IdentityTranslator}, should be
984966 * correct in most cases. If unsure, stick to the default.
@@ -994,12 +976,12 @@
994976 /**
995977 * Configures the generator that will produce the client-side timestamp sent
996978 * with each query.
997- * <p>
979+ * <p/>
998980 * This feature is only available with version {@link ProtocolVersion#V3 V3} or
999981 * above of the native protocol. With earlier versions, timestamps are always
1000982 * generated server-side, and setting a generator through this method will have
1001983 * no effect.
1002- * <p>
984+ * <p/>
1003985 * If no generator is set through this method, the driver will default to the
1004986 * legacy server-side behavior by using {@link ServerSideTimestampGenerator}.
1005987 *
@@ -1013,7 +995,7 @@
1013995
1014996 /**
1015997 * Configures the speculative execution policy to use for the new cluster.
1016- * <p>
998+ * <p/>
1017999 * If no policy is set through this method, {@link Policies#defaultSpeculativeExecutionPolicy()}
10181000 * will be used instead.
10191001 *
@@ -1028,7 +1010,7 @@
10281010
10291011 /**
10301012 * Configures the {@link CodecRegistry} instance to use for the new cluster.
1031- * <p>
1013+ * <p/>
10321014 * If no codec registry is set through this method, {@link CodecRegistry#DEFAULT_INSTANCE}
10331015 * will be used instead.
10341016 * <p>Note that if two or more {@link Cluster} instances are configured to
@@ -1047,7 +1029,7 @@
10471029
10481030 /**
10491031 * Uses the provided credentials when connecting to Cassandra hosts.
1050- * <p>
1032+ * <p/>
10511033 * This should be used if the Cassandra cluster has been configured to
10521034 * use the {@code PasswordAuthenticator}. If the the default {@code
10531035 * AllowAllAuthenticator} is used instead, using this method has no
@@ -1065,14 +1047,14 @@
10651047 /**
10661048 * Use the specified AuthProvider when connecting to Cassandra
10671049 * hosts.
1068- * <p>
1050+ * <p/>
10691051 * Use this method when a custom authentication scheme is in place.
10701052 * You shouldn't call both this method and {@code withCredentials}
10711053 * on the same {@code Builder} instance as one will supersede the
10721054 * other
10731055 *
10741056 * @param authProvider the {@link AuthProvider} to use to login to
1075- * Cassandra hosts.
1057+ * Cassandra hosts.
10761058 * @return this Builder
10771059 */
10781060 public Builder withAuthProvider(AuthProvider authProvider) {
@@ -1085,7 +1067,6 @@
10851067 *
10861068 * @param compression the compression to set.
10871069 * @return this Builder.
1088- *
10891070 * @see ProtocolOptions.Compression
10901071 */
10911072 public Builder withCompression(ProtocolOptions.Compression compression) {
@@ -1106,11 +1087,11 @@
11061087
11071088 /**
11081089 * Enables the use of SSL for the created {@code Cluster}.
1109- * <p>
1090+ * <p/>
11101091 * Calling this method will use the JDK-based implementation with the default options
11111092 * (see {@link JdkSSLOptions.Builder}).
11121093 * This is thus a shortcut for {@code withSSL(JdkSSLOptions.builder().build())}.
1113- * <p>
1094+ * <p/>
11141095 * Note that if SSL is enabled, the driver will not connect to any
11151096 * Cassandra nodes that doesn't have SSL enabled and it is strongly
11161097 * advised to enable SSL on every Cassandra node if you plan on using
@@ -1127,7 +1108,6 @@
11271108 * Enable the use of SSL for the created {@code Cluster} using the provided options.
11281109 *
11291110 * @param sslOptions the SSL options to use.
1130- *
11311111 * @return this builder.
11321112 */
11331113 public Builder withSSL(SSLOptions sslOptions) {
@@ -1137,7 +1117,7 @@
11371117
11381118 /**
11391119 * Register the provided listeners in the newly created cluster.
1140- * <p>
1120+ * <p/>
11411121 * Note: repeated calls to this method will override the previous ones.
11421122 *
11431123 * @param listeners the listeners to register.
@@ -1150,7 +1130,7 @@
11501130
11511131 /**
11521132 * Disables JMX reporting of the metrics.
1153- * <p>
1133+ * <p/>
11541134 * JMX reporting is enabled by default (see {@link Metrics}) but can be
11551135 * disabled using this option. If metrics are disabled, this is a
11561136 * no-op.
@@ -1164,7 +1144,7 @@
11641144
11651145 /**
11661146 * Sets the PoolingOptions to use for the newly created Cluster.
1167- * <p>
1147+ * <p/>
11681148 * If no pooling options are set through this method, default pooling
11691149 * options will be used.
11701150 *
@@ -1178,7 +1158,7 @@
11781158
11791159 /**
11801160 * Sets the SocketOptions to use for the newly created Cluster.
1181- * <p>
1161+ * <p/>
11821162 * If no socket options are set through this method, default socket
11831163 * options will be used.
11841164 *
@@ -1192,7 +1172,7 @@
11921172
11931173 /**
11941174 * Sets the QueryOptions to use for the newly created Cluster.
1195- * <p>
1175+ * <p/>
11961176 * If no query options are set through this method, default query
11971177 * options will be used.
11981178 *
@@ -1206,7 +1186,7 @@
12061186
12071187 /**
12081188 * Set the {@link NettyOptions} to use for the newly created Cluster.
1209- * <p>
1189+ * <p/>
12101190 * If no Netty options are set through this method, {@link NettyOptions#DEFAULT_INSTANCE}
12111191 * will be used as a default value, which means that no customization will be applied.
12121192 *
@@ -1220,7 +1200,7 @@
12201200
12211201 /**
12221202 * The configuration that will be used for the new cluster.
1223- * <p>
1203+ * <p/>
12241204 * You <b>should not</b> modify this object directly because changes made
12251205 * to the returned object may not be used by the cluster build.
12261206 * Instead, you should use the other methods of this {@code Builder}.
@@ -1230,15 +1210,15 @@
12301210 @Override
12311211 public Configuration getConfiguration() {
12321212 ProtocolOptions protocolOptions = new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider)
1233- .setCompression(compression);
1213+ .setCompression(compression);
12341214
12351215 MetricsOptions metricsOptions = new MetricsOptions(metricsEnabled, jmxEnabled);
12361216
12371217 return configurationBuilder
1238- .withProtocolOptions(protocolOptions)
1239- .withMetricsOptions(metricsOptions)
1240- .withPolicies(policiesBuilder.build())
1241- .build();
1218+ .withProtocolOptions(protocolOptions)
1219+ .withMetricsOptions(metricsOptions)
1220+ .withPolicies(policiesBuilder.build())
1221+ .build();
12421222 }
12431223
12441224 @Override
@@ -1249,7 +1229,7 @@
12491229 /**
12501230 * Builds the cluster with the configured set of initial contact points
12511231 * and policies.
1252- * <p>
1232+ * <p/>
12531233 * This is a convenience method for {@code Cluster.buildFrom(this)}.
12541234 *
12551235 * @return the newly built Cluster instance.
@@ -1269,7 +1249,7 @@
12691249
12701250 /**
12711251 * The sessions and hosts managed by this a Cluster instance.
1272- * <p>
1252+ * <p/>
12731253 * Note: the reason we create a Manager object separate from Cluster is
12741254 * that Manager is not publicly visible. For instance, we wouldn't want
12751255 * user to be able to call the {@link #onUp} and {@link #onDown} methods.
@@ -1320,7 +1300,7 @@
13201300
13211301 final Set<Host.StateListener> listeners;
13221302 final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>();
1323- final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
1303+ final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
13241304
13251305 EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer;
13261306 EventDebouncer<NodeRefreshRequest> nodeRefreshRequestDebouncer;
@@ -1364,23 +1344,23 @@
13641344 // create debouncers - at this stage, they are not running yet
13651345 QueryOptions queryOptions = configuration.getQueryOptions();
13661346 this.nodeListRefreshRequestDebouncer = new EventDebouncer<NodeListRefreshRequest>(
1367- "Node list refresh",
1368- scheduledTasksExecutor,
1369- new NodeListRefreshRequestDeliveryCallback(),
1370- queryOptions.getRefreshNodeListIntervalMillis(),
1371- queryOptions.getMaxPendingRefreshNodeListRequests());
1347+ "Node list refresh",
1348+ scheduledTasksExecutor,
1349+ new NodeListRefreshRequestDeliveryCallback(),
1350+ queryOptions.getRefreshNodeListIntervalMillis(),
1351+ queryOptions.getMaxPendingRefreshNodeListRequests());
13721352 this.nodeRefreshRequestDebouncer = new EventDebouncer<NodeRefreshRequest>(
1373- "Node refresh",
1374- scheduledTasksExecutor,
1375- new NodeRefreshRequestDeliveryCallback(),
1376- queryOptions.getRefreshNodeIntervalMillis(),
1377- queryOptions.getMaxPendingRefreshNodeRequests());
1353+ "Node refresh",
1354+ scheduledTasksExecutor,
1355+ new NodeRefreshRequestDeliveryCallback(),
1356+ queryOptions.getRefreshNodeIntervalMillis(),
1357+ queryOptions.getMaxPendingRefreshNodeRequests());
13781358 this.schemaRefreshRequestDebouncer = new EventDebouncer<SchemaRefreshRequest>(
1379- "Schema refresh",
1380- scheduledTasksExecutor,
1381- new SchemaRefreshRequestDeliveryCallback(),
1382- queryOptions.getRefreshSchemaIntervalMillis(),
1383- queryOptions.getMaxPendingRefreshSchemaRequests());
1359+ "Schema refresh",
1360+ scheduledTasksExecutor,
1361+ new SchemaRefreshRequestDeliveryCallback(),
1362+ queryOptions.getRefreshSchemaIntervalMillis(),
1363+ queryOptions.getMaxPendingRefreshSchemaRequests());
13841364
13851365 this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
13861366
@@ -1390,9 +1370,9 @@
13901370 // create the Host object so we can initialize the control connection.
13911371 metadata.add(address);
13921372 }
1393-
1373+
13941374 Collection<Host> allHosts = metadata.allHosts();
1395-
1375+
13961376 // At this stage, metadata.allHosts() only contains the contact points, that's what we want to pass to LBP.init().
13971377 // But the control connection will initialize first and discover more hosts, so make a copy.
13981378 Set<Host> contactPointHosts = Sets.newHashSet(allHosts);
@@ -1466,7 +1446,7 @@
14661446 logUnsupportedVersionProtocol(host, connectionFactory.protocolVersion);
14671447 continue;
14681448 }
1469-
1449+
14701450 if (!contactPointHosts.contains(host))
14711451 loadBalancingPolicy().onAdd(host);
14721452
@@ -1498,11 +1478,11 @@
14981478
14991479 private ListeningExecutorService makeExecutor(int threads, String name, LinkedBlockingQueue<Runnable> workQueue) {
15001480 ThreadPoolExecutor executor = new ThreadPoolExecutor(threads,
1501- threads,
1502- DEFAULT_THREAD_KEEP_ALIVE,
1503- TimeUnit.SECONDS,
1504- workQueue,
1505- threadFactory(name));
1481+ threads,
1482+ DEFAULT_THREAD_KEEP_ALIVE,
1483+ TimeUnit.SECONDS,
1484+ workQueue,
1485+ threadFactory(name));
15061486
15071487 executor.allowCoreThreadTimeOut(true);
15081488 return MoreExecutors.listeningDecorator(executor);
@@ -1602,8 +1582,8 @@
16021582 }
16031583
16041584 return closeFuture.compareAndSet(null, future)
1605- ? future
1606- : closeFuture.get(); // We raced, it's ok, return the future that was actually set
1585+ ? future
1586+ : closeFuture.get(); // We raced, it's ok, return the future that was actually set
16071587 }
16081588
16091589 private void shutdownNow(ExecutorService executor) {
@@ -1611,20 +1591,20 @@
16111591 // If some tasks were submitted to this executor but not yet commenced, make sure the corresponding futures complete
16121592 for (Runnable pendingTask : pendingTasks) {
16131593 if (pendingTask instanceof FutureTask<?>)
1614- ((FutureTask<?>)pendingTask).cancel(false);
1594+ ((FutureTask<?>) pendingTask).cancel(false);
16151595 }
16161596 }
16171597
16181598 void logUnsupportedVersionProtocol(Host host, ProtocolVersion version) {
16191599 logger.warn("Detected added or restarted Cassandra host {} but ignoring it since it does not support the version {} of the native "
1620- + "protocol which is currently in use. If you want to force the use of a particular version of the native protocol, use "
1621- + "Cluster.Builder#usingProtocolVersion() when creating the Cluster instance.", host, version);
1600+ + "protocol which is currently in use. If you want to force the use of a particular version of the native protocol, use "
1601+ + "Cluster.Builder#usingProtocolVersion() when creating the Cluster instance.", host, version);
16221602 }
16231603
16241604 void logClusterNameMismatch(Host host, String expectedClusterName, String actualClusterName) {
16251605 logger.warn("Detected added or restarted Cassandra host {} but ignoring it since its cluster name '{}' does not match the one "
1626- + "currently known ({})",
1627- host, actualClusterName, expectedClusterName);
1606+ + "currently known ({})",
1607+ host, actualClusterName, expectedClusterName);
16281608 }
16291609
16301610 public ListenableFuture<?> triggerOnUp(final Host host) {
@@ -1658,7 +1638,7 @@
16581638 return;
16591639 }
16601640 try {
1661-
1641+
16621642 // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
16631643 if (host.state == Host.State.UP)
16641644 return;
@@ -1747,7 +1727,7 @@
17471727 }
17481728
17491729 public ListenableFuture<?> triggerOnDown(final Host host, final boolean isHostAddition, final boolean startReconnection) {
1750- if(!isClosed()) {
1730+ if (!isClosed()) {
17511731 return executor.submit(new ExceptionCatchingRunnable() {
17521732 @Override
17531733 public void runMayThrow() throws InterruptedException, ExecutionException {
@@ -2102,7 +2082,7 @@
21022082 PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().id, stmt);
21032083 if (previous != null) {
21042084 logger.warn("Re-preparing already prepared query {}. Please note that preparing the same query more than once is "
2105- + "generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.", stmt.getQueryString());
2085+ + "generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.", stmt.getQueryString());
21062086
21072087 // The one object in the cache will get GCed once it's not referenced by the client anymore since we use a weak reference.
21082088 // So we need to make sure that the instance we do return to the user is the one that is in the cache.
@@ -2115,7 +2095,7 @@
21152095 * @param reusedConnection an existing connection (from a reconnection attempt) that we want to
21162096 * reuse to prepare the statements (might be null).
21172097 * @return a connection that the rest of the initialization process can use (it will be made part
2118- * of a connection pool). Can be reusedConnection, or one that was open in the method.
2098+ * of a connection pool). Can be reusedConnection, or one that was open in the method.
21192099 */
21202100 private Connection prepareAllQueries(Host host, Connection reusedConnection) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
21212101 if (preparedQueries.isEmpty())
@@ -2125,8 +2105,8 @@
21252105 Connection connection = null;
21262106 try {
21272107 connection = (reusedConnection == null)
2128- ? connectionFactory.open(host)
2129- : reusedConnection;
2108+ ? connectionFactory.open(host)
2109+ : reusedConnection;
21302110
21312111 try {
21322112 controlConnection.waitForSchemaAgreement();
@@ -2214,8 +2194,8 @@
22142194 public void refreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final SchemaElement targetType, final String targetKeyspace, final String targetName, final List<String> targetSignature) {
22152195 if (logger.isDebugEnabled())
22162196 logger.debug("Refreshing schema for {}{}",
2217- targetType == null ? "everything" : targetKeyspace,
2218- (targetType == KEYSPACE) ? "" : "." + targetName + " (" + targetType + ")");
2197+ targetType == null ? "everything" : targetKeyspace,
2198+ (targetType == KEYSPACE) ? "" : "." + targetName + " (" + targetType + ")");
22192199
22202200 maybeRefreshSchemaAndSignal(connection, future, rs, targetType, targetKeyspace, targetName, targetSignature);
22212201 }
@@ -2268,13 +2248,13 @@
22682248 return;
22692249 }
22702250
2271- final ProtocolEvent event = ((Responses.Event)response).event;
2251+ final ProtocolEvent event = ((Responses.Event) response).event;
22722252
22732253 logger.debug("Received event {}, scheduling delivery", response);
22742254
22752255 switch (event.type) {
22762256 case TOPOLOGY_CHANGE:
2277- ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange)event;
2257+ ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange) event;
22782258 InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress());
22792259 Host.statesLogger.debug("[{}] received event {}", tpAddr, tpc.change);
22802260 switch (tpc.change) {
@@ -2290,7 +2270,7 @@
22902270 }
22912271 break;
22922272 case STATUS_CHANGE:
2293- ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange)event;
2273+ ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange) event;
22942274 InetSocketAddress stAddr = translateAddress(stc.node.getAddress());
22952275 Host.statesLogger.debug("[{}] received event {}", stAddr, stc.status);
22962276 switch (stc.status) {
@@ -2306,7 +2286,7 @@
23062286 if (!configuration.getQueryOptions().isMetadataEnabled())
23072287 return;
23082288
2309- ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event;
2289+ ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange) event;
23102290 switch (scc.change) {
23112291 case CREATED:
23122292 case UPDATED:
@@ -2327,7 +2307,7 @@
23272307 KeyspaceMetadata keyspace = manager.metadata.keyspaces.get(scc.targetKeyspace);
23282308 if (keyspace == null) {
23292309 logger.warn("Received a DROPPED notification for {} {}.{}, but this keyspace is unknown in our metadata",
2330- scc.targetType, scc.targetKeyspace, scc.targetName);
2310+ scc.targetType, scc.targetKeyspace, scc.targetName);
23312311 } else {
23322312 switch (scc.targetType) {
23332313 case TABLE:
@@ -2472,7 +2452,8 @@
24722452 }
24732453
24742454 private class CleanupIdleConnectionsTask implements Runnable {
2475- @Override public void run() {
2455+ @Override
2456+ public void run() {
24762457 try {
24772458 long now = System.currentTimeMillis();
24782459 for (SessionManager session : sessions) {
@@ -2604,7 +2585,7 @@
26042585 // If host already existed, retrieve it and check its state, if it's not up schedule a
26052586 // hostUp event.
26062587 Host existingHost = metadata.getHost(address);
2607- if(!existingHost.isUp())
2588+ if (!existingHost.isUp())
26082589 futures.add(schedule(hostUp(existingHost)));
26092590 }
26102591 break;
@@ -2748,7 +2729,7 @@
27482729
27492730 /**
27502731 * Periodically ensures that closed connections are properly terminated once they have no more pending requests.
2751- *
2732+ * <p/>
27522733 * This is normally done when the connection errors out, or when the last request is processed; this class acts as
27532734 * a last-effort protection since unterminated connections can lead to deadlocks. If it terminates a connection,
27542735 * 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/ClusteringOrder.java +1 −1
@@ -17,7 +17,7 @@
1717
1818 /**
1919 * Clustering orders.
20- * <p>
20+ * <p/>
2121 * This is used by metadata classes to indicate the clustering
2222 * order of a clustering column in a table or materialized view.
2323 */
modified driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +133 −137
@@ -15,13 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.lang.reflect.ParameterizedType;
19-import java.lang.reflect.Type;
20-import java.nio.ByteBuffer;
21-import java.util.*;
22-import java.util.concurrent.CopyOnWriteArrayList;
23-import java.util.concurrent.ExecutionException;
24-
18+import com.datastax.driver.core.exceptions.CodecNotFoundException;
2519 import com.google.common.base.Objects;
2620 import com.google.common.cache.*;
2721 import com.google.common.collect.ImmutableSet;
@@ -30,29 +24,33 @@
3024 import org.slf4j.Logger;
3125 import org.slf4j.LoggerFactory;
3226
33-import static com.google.common.base.Preconditions.checkNotNull;
34-
35-import com.datastax.driver.core.exceptions.CodecNotFoundException;
27+import java.lang.reflect.ParameterizedType;
28+import java.lang.reflect.Type;
29+import java.nio.ByteBuffer;
30+import java.util.List;
31+import java.util.Map;
32+import java.util.Set;
33+import java.util.concurrent.CopyOnWriteArrayList;
34+import java.util.concurrent.ExecutionException;
3635
37-import static com.datastax.driver.core.DataType.Name.LIST;
38-import static com.datastax.driver.core.DataType.Name.MAP;
39-import static com.datastax.driver.core.DataType.Name.SET;
36+import static com.datastax.driver.core.DataType.Name.*;
37+import static com.google.common.base.Preconditions.checkNotNull;
4038
4139 /**
4240 * A registry for {@link TypeCodec}s. When the driver needs to serialize or deserialize a Java type to/from CQL,
4341 * it will lookup in the registry for a suitable codec. The registry is initialized with default codecs that handle
4442 * basic conversions (e.g. CQL {@code text} to {@code java.lang.String}), and users can add their own. Complex
4543 * codecs can also be generated on-the-fly from simpler ones (more details below).
46- *
44+ * <p/>
4745 * <h3>Creating a registry</h3>
48- *
49- * <p>
46+ * <p/>
47+ * <p/>
5048 * By default, the driver uses {@link CodecRegistry#DEFAULT_INSTANCE}, a shareable, JVM-wide instance initialized with
5149 * built-in codecs for all the base CQL types.
5250 * The only reason to create your own instances is if you have multiple {@code Cluster} objects that use different
5351 * sets of codecs. In that case, use {@link com.datastax.driver.core.Cluster.Builder#withCodecRegistry(CodecRegistry)}
5452 * to associate the registry with the cluster:
55- *
53+ * <p/>
5654 * <pre>
5755 * {@code
5856 * CodecRegistry myCodecRegistry = new CodecRegistry();
@@ -65,7 +63,7 @@
6563 *
6664 * {@code CodecRegistry} instances are thread-safe.
6765 *
68- * <p>
66+ *
6967 * It is possible to turn on log messages by setting the {@code com.datastax.driver.core.CodecRegistry} logger
7068 * level to {@code TRACE}. Beware that the registry can be very verbose at this log level.
7169 *
@@ -85,11 +83,11 @@
8583 *
8684 * The conversion will be available to:
8785 * <ul>
88- * <li>all driver types that implement {@link GettableByIndexData}, {@link GettableByNameData},
89- * {@link SettableByIndexData} and/or {@link SettableByNameData}. Namely: {@link Row},
90- * {@link BoundStatement}, {@link UDTValue} and {@link TupleValue};</li>
91- * <li>{@link SimpleStatement(String, Object...) simple statements};</li>
92- * <li>statements created with the {@link com.datastax.driver.core.querybuilder.QueryBuilder Query builder}.</li>
86+ * <li>all driver types that implement {@link GettableByIndexData}, {@link GettableByNameData},
87+ * {@link SettableByIndexData} and/or {@link SettableByNameData}. Namely: {@link Row},
88+ * {@link BoundStatement}, {@link UDTValue} and {@link TupleValue};</li>
89+ * <li>{@link SimpleStatement(String, Object...) simple statements};</li>
90+ * <li>statements created with the {@link com.datastax.driver.core.querybuilder.QueryBuilder Query builder}.</li>
9391 * </ul>
9492 *
9593 * Example:
@@ -107,16 +105,16 @@
107105 * It can manage:
108106 *
109107 * <ul>
110- * <li>collections (lists, sets and maps) of known types. For example,
111- * if you registered a codec for JDK8's {@code java.time.LocalDate} like in the example above, you get
112- * {@code List<LocalDate>>} and {@code Set<LocalDate>>} handled for free,
113- * as well as all {@code Map} types whose keys and/or values are {@code java.time.LocalDate}.
114- * This works recursively for nested collections;</li>
115- * <li>{@link UserType user types}, mapped to {@link UDTValue} objects. Custom codecs are available recursively
116- * to the UDT's fields, so if one of your fields is a {@code timestamp} you can use your {@code LocaDateCodec} to retrieve
117- * it as a {@code java.time.LocalDate};</li>
118- * <li>{@link TupleType tuple types}, mapped to {@link TupleValue} (with the same rules for nested fields);</li>
119- * <li>{@link com.datastax.driver.core.DataType.CustomType custom types}, mapped to {@code ByteBuffer}.</li>
108+ * <li>collections (lists, sets and maps) of known types. For example,
109+ * if you registered a codec for JDK8's {@code java.time.LocalDate} like in the example above, you get
110+ * {@code List<LocalDate>>} and {@code Set<LocalDate>>} handled for free,
111+ * as well as all {@code Map} types whose keys and/or values are {@code java.time.LocalDate}.
112+ * This works recursively for nested collections;</li>
113+ * <li>{@link UserType user types}, mapped to {@link UDTValue} objects. Custom codecs are available recursively
114+ * to the UDT's fields, so if one of your fields is a {@code timestamp} you can use your {@code LocaDateCodec} to retrieve
115+ * it as a {@code java.time.LocalDate};</li>
116+ * <li>{@link TupleType tuple types}, mapped to {@link TupleValue} (with the same rules for nested fields);</li>
117+ * <li>{@link com.datastax.driver.core.DataType.CustomType custom types}, mapped to {@code ByteBuffer}.</li>
120118 * </ul>
121119 *
122120 * If the codec registry encounters a mapping that it can't handle automatically, a {@link CodecNotFoundException} is thrown;
@@ -128,9 +126,9 @@
128126 * codec. For example, if you registered {@code LocalDateCodec} and ask the registry for a codec to convert a CQL
129127 * {@code list<timestamp>} to a Java {@code List<LocalDate>}:
130128 * <ol>
131- * <li>the first lookup will generate a {@code TypeCodec<List<LocalDate>>} from {@code LocalDateCodec}, and put it in
132- * the cache;</li>
133- * <li>the second lookup will hit the cache directly, and reuse the previously generated instance.</li>
129+ * <li>the first lookup will generate a {@code TypeCodec<List<LocalDate>>} from {@code LocalDateCodec}, and put it in
130+ * the cache;</li>
131+ * <li>the second lookup will hit the cache directly, and reuse the previously generated instance.</li>
134132 * </ol>
135133 *
136134 * The javadoc for each {@link #codecFor(DataType) codecFor} variant specifies whether the result can be cached or not.
@@ -140,11 +138,11 @@
140138 * When the registry looks up a codec, the rules of precedence are:
141139 *
142140 * <ul>
143- * <li>if a result was previously cached for that mapping, it is returned;</li>
144- * <li>otherwise, the registry checks the list of "basic" codecs: the default ones, and the ones that were explicitly
145- * registered (in the order that they were registered). It calls each codec's {@code accepts} methods to determine if
146- * it can handle the mapping, and if so returns it;</li>
147- * <li>otherwise, the registry tries to generate a codec, according to the rules outlined above.</li>
141+ * <li>if a result was previously cached for that mapping, it is returned;</li>
142+ * <li>otherwise, the registry checks the list of "basic" codecs: the default ones, and the ones that were explicitly
143+ * registered (in the order that they were registered). It calls each codec's {@code accepts} methods to determine if
144+ * it can handle the mapping, and if so returns it;</li>
145+ * <li>otherwise, the registry tries to generate a codec, according to the rules outlined above.</li>
148146 * </ul>
149147 *
150148 * It is currently impossible to override an existing codec. If you try to do so, {@link #register(TypeCodec)} will log a
@@ -156,30 +154,30 @@
156154
157155 @SuppressWarnings("unchecked")
158156 private static final ImmutableSet<TypeCodec<?>> PRIMITIVE_CODECS = ImmutableSet.of(
159- TypeCodec.blob(),
160- TypeCodec.cboolean(),
161- TypeCodec.smallInt(),
162- TypeCodec.tinyInt(),
163- TypeCodec.cint(),
164- TypeCodec.bigint(),
165- TypeCodec.counter(),
166- TypeCodec.cdouble(),
167- TypeCodec.cfloat(),
168- TypeCodec.varint(),
169- TypeCodec.decimal(),
170- TypeCodec.varchar(), // must be declared before AsciiCodec so it gets chosen when CQL type not available
171- TypeCodec.ascii(),
172- TypeCodec.timestamp(),
173- TypeCodec.date(),
174- TypeCodec.time(),
175- TypeCodec.uuid(), // must be declared before TimeUUIDCodec so it gets chosen when CQL type not available
176- TypeCodec.timeUUID(),
177- TypeCodec.inet()
157+ TypeCodec.blob(),
158+ TypeCodec.cboolean(),
159+ TypeCodec.smallInt(),
160+ TypeCodec.tinyInt(),
161+ TypeCodec.cint(),
162+ TypeCodec.bigint(),
163+ TypeCodec.counter(),
164+ TypeCodec.cdouble(),
165+ TypeCodec.cfloat(),
166+ TypeCodec.varint(),
167+ TypeCodec.decimal(),
168+ TypeCodec.varchar(), // must be declared before AsciiCodec so it gets chosen when CQL type not available
169+ TypeCodec.ascii(),
170+ TypeCodec.timestamp(),
171+ TypeCodec.date(),
172+ TypeCodec.time(),
173+ TypeCodec.uuid(), // must be declared before TimeUUIDCodec so it gets chosen when CQL type not available
174+ TypeCodec.timeUUID(),
175+ TypeCodec.inet()
178176 );
179177
180178 /**
181179 * The default {@code CodecRegistry} instance.
182- *
180+ * <p/>
183181 * It will be shared among all {@link Cluster} instances that were not explicitly built with a different instance.
184182 */
185183 public static final CodecRegistry DEFAULT_INSTANCE = new CodecRegistry();
@@ -204,7 +202,7 @@
204202 return true;
205203 if (o == null || getClass() != o.getClass())
206204 return false;
207- CacheKey cacheKey = (CacheKey)o;
205+ CacheKey cacheKey = (CacheKey) o;
208206 return Objects.equal(cqlType, cacheKey.cqlType) && Objects.equal(javaType, cacheKey.javaType);
209207 }
210208
@@ -258,14 +256,14 @@
258256 }
259257 case UDT: {
260258 int weight = level;
261- for (UserType.Field field : ((UserType)cqlType)) {
259+ for (UserType.Field field : ((UserType) cqlType)) {
262260 weight += weigh(field.getType(), level + 1);
263261 }
264262 return weight == 0 ? 1 : weight;
265263 }
266264 case TUPLE: {
267265 int weight = level;
268- for (DataType componentType : ((TupleType)cqlType).getComponentTypes()) {
266+ for (DataType componentType : ((TupleType) cqlType).getComponentTypes()) {
269267 weight += weigh(componentType, level + 1);
270268 }
271269 return weight == 0 ? 1 : weight;
@@ -312,11 +310,11 @@
312310
313311 private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() {
314312 CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder()
315- // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs,
316- // so let's start with roughly 1/4 of that
317- .initialCapacity(100)
318- .maximumWeight(1000)
319- .weigher(new TypeCodecWeigher());
313+ // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs,
314+ // so let's start with roughly 1/4 of that
315+ .initialCapacity(100)
316+ .maximumWeight(1000)
317+ .weigher(new TypeCodecWeigher());
320318 if (logger.isTraceEnabled())
321319 // do not bother adding a listener if it will be ineffective
322320 builder = builder.removalListener(new TypeCodecRemovalListener());
@@ -325,7 +323,7 @@
325323
326324 /**
327325 * Register the given codec with this registry.
328- * <p>
326+ * <p/>
329327 * This method will log a warning and ignore the codec if it collides with a previously registered one.
330328 * Note that this check is not done in a completely thread-safe manner; codecs should typically be registered
331329 * at application startup, not in a highly concurrent context (if a race condition occurs, the worst possible
@@ -358,7 +356,6 @@
358356 *
359357 * @param codecs The codecs to add to the registry.
360358 * @return this CodecRegistry (for method chaining).
361- *
362359 * @see #register(TypeCodec)
363360 */
364361 public CodecRegistry register(TypeCodec<?>... codecs) {
@@ -372,7 +369,6 @@
372369 *
373370 * @param codecs The codecs to add to the registry.
374371 * @return this CodecRegistry (for method chaining).
375- *
376372 * @see #register(TypeCodec)
377373 */
378374 public CodecRegistry register(Iterable<? extends TypeCodec<?>> codecs) {
@@ -383,19 +379,19 @@
383379
384380 /**
385381 * Returns a {@link TypeCodec codec} that accepts the given value.
386- * <p>
382+ * <p/>
387383 * This method takes an arbitrary Java object and tries to locate a suitable codec for it.
388384 * Codecs must perform a {@link TypeCodec#accepts(Object) runtime inspection} of the object to determine
389385 * if they can accept it or not, which, depending on the implementations, can be expensive; besides, the
390386 * resulting codec cannot be cached.
391387 * Therefore there might be a performance penalty when using this method.
392- * <p>
388+ * <p/>
393389 * Furthermore, this method returns the first matching codec, regardless of its accepted CQL type.
394390 * It should be reserved for situations where the target CQL type is not available or unknown.
395391 * In the Java driver, this happens mainly when serializing a value in a
396392 * {@link SimpleStatement(String, Object...) SimpleStatement} or in the
397393 * {@link com.datastax.driver.core.querybuilder.QueryBuilder}, where no CQL type information is available.
398- * <p>
394+ * <p/>
399395 * Codecs returned by this method are <em>NOT</em> cached (see the {@link CodecRegistry top-level documentation}
400396 * of this class for more explanations about caching).
401397 *
@@ -409,12 +405,12 @@
409405
410406 /**
411407 * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type}.
412- * <p>
408+ * <p/>
413409 * This method returns the first matching codec, regardless of its accepted Java type.
414410 * It should be reserved for situations where the Java type is not available or unknown.
415411 * In the Java driver, this happens mainly when deserializing a value using the
416412 * {@link GettableByIndexData#getObject(int) getObject} method.
417- * <p>
413+ * <p/>
418414 * Codecs returned by this method are cached (see the {@link CodecRegistry top-level documentation}
419415 * of this class for more explanations about caching).
420416 *
@@ -429,14 +425,14 @@
429425 /**
430426 * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type}
431427 * and the given Java class.
432- * <p>
428+ * <p/>
433429 * This method can only handle raw (non-parameterized) Java types.
434430 * For parameterized types, use {@link #codecFor(DataType, TypeToken)} instead.
435- * <p>
431+ * <p/>
436432 * Codecs returned by this method are cached (see the {@link CodecRegistry top-level documentation}
437433 * of this class for more explanations about caching).
438434 *
439- * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
435+ * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
440436 * @param javaType The Java type the codec should accept; can be {@code null}.
441437 * @return A suitable codec.
442438 * @throws CodecNotFoundException if a suitable codec cannot be found.
@@ -448,13 +444,13 @@
448444 /**
449445 * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type}
450446 * and the given Java type.
451- * <p>
447+ * <p/>
452448 * This method handles parameterized types thanks to Guava's {@link TypeToken} API.
453- * <p>
449+ * <p/>
454450 * Codecs returned by this method are cached (see the {@link CodecRegistry top-level documentation}
455451 * of this class for more explanations about caching).
456452 *
457- * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
453+ * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
458454 * @param javaType The {@link TypeToken Java type} the codec should accept; can be {@code null}.
459455 * @return A suitable codec.
460456 * @throws CodecNotFoundException if a suitable codec cannot be found.
@@ -466,18 +462,18 @@
466462 /**
467463 * Returns a {@link TypeCodec codec} that accepts the given {@link DataType CQL type}
468464 * and the given value.
469- * <p>
465+ * <p/>
470466 * This method takes an arbitrary Java object and tries to locate a suitable codec for it.
471467 * Codecs must perform a {@link TypeCodec#accepts(Object) runtime inspection} of the object to determine
472468 * if they can accept it or not, which, depending on the implementations, can be expensive; besides, the
473469 * resulting codec cannot be cached.
474470 * Therefore there might be a performance penalty when using this method.
475- * <p>
471+ * <p/>
476472 * Codecs returned by this method are <em>NOT</em> cached (see the {@link CodecRegistry top-level documentation}
477473 * of this class for more explanations about caching).
478474 *
479475 * @param cqlType The {@link DataType CQL type} the codec should accept; can be {@code null}.
480- * @param value The value the codec should accept; must not be {@code null}.
476+ * @param value The value the codec should accept; must not be {@code null}.
481477 * @return A suitable codec.
482478 * @throws CodecNotFoundException if a suitable codec cannot be found.
483479 */
@@ -493,9 +489,9 @@
493489 try {
494490 TypeCodec<?> codec = cache.get(cacheKey);
495491 logger.trace("Returning cached codec {}", codec);
496- return (TypeCodec<T>)codec;
492+ return (TypeCodec<T>) codec;
497493 } catch (UncheckedExecutionException e) {
498- if(e.getCause() instanceof CodecNotFoundException) {
494+ if (e.getCause() instanceof CodecNotFoundException) {
499495 throw (CodecNotFoundException) e.getCause();
500496 }
501497 throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
@@ -513,7 +509,7 @@
513509 for (TypeCodec<?> codec : codecs) {
514510 if (codec.accepts(cqlType) && (javaType == null || codec.accepts(javaType))) {
515511 logger.trace("Codec found: {}", codec);
516- return (TypeCodec<T>)codec;
512+ return (TypeCodec<T>) codec;
517513 }
518514 }
519515 return createCodec(cqlType, javaType);
@@ -526,7 +522,7 @@
526522 for (TypeCodec<?> codec : codecs) {
527523 if ((cqlType == null || codec.accepts(cqlType)) && codec.accepts(value)) {
528524 logger.trace("Codec found: {}", codec);
529- return (TypeCodec<T>)codec;
525+ return (TypeCodec<T>) codec;
530526 }
531527 }
532528 return createCodec(cqlType, value);
@@ -548,10 +544,10 @@
548544
549545 private <T> TypeCodec<T> createCodec(DataType cqlType, T value) {
550546 TypeCodec<T> codec = maybeCreateCodec(cqlType, value);
551- if(codec == null)
547+ if (codec == null)
552548 throw notFound(cqlType, TypeToken.of(value.getClass()));
553549 // double-check that the created codec satisfies the initial request
554- if((cqlType != null && !codec.accepts(cqlType)) || !codec.accepts(value))
550+ if ((cqlType != null && !codec.accepts(cqlType)) || !codec.accepts(value))
555551 throw notFound(cqlType, TypeToken.of(value.getClass()));
556552 logger.trace("Codec created: {}", codec);
557553 return codec;
@@ -564,46 +560,46 @@
564560 if (cqlType.getName() == LIST && (javaType == null || List.class.isAssignableFrom(javaType.getRawType()))) {
565561 TypeToken<?> elementType = null;
566562 if (javaType != null && javaType.getType() instanceof ParameterizedType) {
567- Type[] typeArguments = ((ParameterizedType)javaType.getType()).getActualTypeArguments();
563+ Type[] typeArguments = ((ParameterizedType) javaType.getType()).getActualTypeArguments();
568564 elementType = TypeToken.of(typeArguments[0]);
569565 }
570566 TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType);
571- return (TypeCodec<T>)TypeCodec.list(eltCodec);
567+ return (TypeCodec<T>) TypeCodec.list(eltCodec);
572568 }
573569
574570 if (cqlType.getName() == SET && (javaType == null || Set.class.isAssignableFrom(javaType.getRawType()))) {
575571 TypeToken<?> elementType = null;
576572 if (javaType != null && javaType.getType() instanceof ParameterizedType) {
577- Type[] typeArguments = ((ParameterizedType)javaType.getType()).getActualTypeArguments();
573+ Type[] typeArguments = ((ParameterizedType) javaType.getType()).getActualTypeArguments();
578574 elementType = TypeToken.of(typeArguments[0]);
579575 }
580576 TypeCodec<?> eltCodec = findCodec(cqlType.getTypeArguments().get(0), elementType);
581- return (TypeCodec<T>)TypeCodec.set(eltCodec);
577+ return (TypeCodec<T>) TypeCodec.set(eltCodec);
582578 }
583579
584580 if (cqlType.getName() == MAP && (javaType == null || Map.class.isAssignableFrom(javaType.getRawType()))) {
585581 TypeToken<?> keyType = null;
586582 TypeToken<?> valueType = null;
587583 if (javaType != null && javaType.getType() instanceof ParameterizedType) {
588- Type[] typeArguments = ((ParameterizedType)javaType.getType()).getActualTypeArguments();
584+ Type[] typeArguments = ((ParameterizedType) javaType.getType()).getActualTypeArguments();
589585 keyType = TypeToken.of(typeArguments[0]);
590586 valueType = TypeToken.of(typeArguments[1]);
591587 }
592588 TypeCodec<?> keyCodec = findCodec(cqlType.getTypeArguments().get(0), keyType);
593589 TypeCodec<?> valueCodec = findCodec(cqlType.getTypeArguments().get(1), valueType);
594- return (TypeCodec<T>)TypeCodec.map(keyCodec, valueCodec);
590+ return (TypeCodec<T>) TypeCodec.map(keyCodec, valueCodec);
595591 }
596592
597593 if (cqlType instanceof TupleType && (javaType == null || TupleValue.class.isAssignableFrom(javaType.getRawType()))) {
598- return (TypeCodec<T>)TypeCodec.tuple((TupleType)cqlType);
594+ return (TypeCodec<T>) TypeCodec.tuple((TupleType) cqlType);
599595 }
600596
601597 if (cqlType instanceof UserType && (javaType == null || UDTValue.class.isAssignableFrom(javaType.getRawType()))) {
602- return (TypeCodec<T>)TypeCodec.userType((UserType)cqlType);
598+ return (TypeCodec<T>) TypeCodec.userType((UserType) cqlType);
603599 }
604600
605- if(cqlType instanceof DataType.CustomType && (javaType == null || ByteBuffer.class.isAssignableFrom(javaType.getRawType()))) {
606- return (TypeCodec<T>)TypeCodec.custom((DataType.CustomType)cqlType);
601+ if (cqlType instanceof DataType.CustomType && (javaType == null || ByteBuffer.class.isAssignableFrom(javaType.getRawType()))) {
602+ return (TypeCodec<T>) TypeCodec.custom((DataType.CustomType) cqlType);
607603 }
608604
609605 return null;
@@ -614,71 +610,71 @@
614610 checkNotNull(value);
615611
616612 if ((cqlType == null || cqlType.getName() == LIST) && value instanceof List) {
617- List list = (List)value;
613+ List list = (List) value;
618614 if (list.isEmpty()) {
619615 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
620- ? DataType.blob()
621- : cqlType.getTypeArguments().get(0);
622- return TypeCodec.list(findCodec(elementType, (TypeToken)null));
616+ ? DataType.blob()
617+ : cqlType.getTypeArguments().get(0);
618+ return TypeCodec.list(findCodec(elementType, (TypeToken) null));
623619 } else {
624620 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
625- ? null
626- : cqlType.getTypeArguments().get(0);
627- return (TypeCodec<T>)TypeCodec.list(findCodec(elementType, list.iterator().next()));
621+ ? null
622+ : cqlType.getTypeArguments().get(0);
623+ return (TypeCodec<T>) TypeCodec.list(findCodec(elementType, list.iterator().next()));
628624 }
629625 }
630626
631627 if ((cqlType == null || cqlType.getName() == SET) && value instanceof Set) {
632- Set set = (Set)value;
628+ Set set = (Set) value;
633629 if (set.isEmpty()) {
634630 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
635- ? DataType.blob()
636- : cqlType.getTypeArguments().get(0);
637- return TypeCodec.set(findCodec(elementType, (TypeToken)null));
631+ ? DataType.blob()
632+ : cqlType.getTypeArguments().get(0);
633+ return TypeCodec.set(findCodec(elementType, (TypeToken) null));
638634 } else {
639635 DataType elementType = (cqlType == null || cqlType.getTypeArguments().isEmpty())
640- ? null
641- : cqlType.getTypeArguments().get(0);
642- return (TypeCodec<T>)TypeCodec.set(findCodec(elementType, set.iterator().next()));
636+ ? null
637+ : cqlType.getTypeArguments().get(0);
638+ return (TypeCodec<T>) TypeCodec.set(findCodec(elementType, set.iterator().next()));
643639 }
644640 }
645641
646642 if ((cqlType == null || cqlType.getName() == MAP) && value instanceof Map) {
647- Map map = (Map)value;
643+ Map map = (Map) value;
648644 if (map.isEmpty()) {
649645 DataType keyType = (cqlType == null || cqlType.getTypeArguments().size() < 1)
650- ? DataType.blob()
651- : cqlType.getTypeArguments().get(0);
646+ ? DataType.blob()
647+ : cqlType.getTypeArguments().get(0);
652648 DataType valueType = (cqlType == null || cqlType.getTypeArguments().size() < 2)
653- ? DataType.blob() :
654- cqlType.getTypeArguments().get(1);
649+ ? DataType.blob() :
650+ cqlType.getTypeArguments().get(1);
655651 return TypeCodec.map(
656- findCodec(keyType, (TypeToken)null),
657- findCodec(valueType, (TypeToken)null));
652+ findCodec(keyType, (TypeToken) null),
653+ findCodec(valueType, (TypeToken) null));
658654 } else {
659655 DataType keyType = (cqlType == null || cqlType.getTypeArguments().size() < 1)
660- ? null
661- : cqlType.getTypeArguments().get(0);
656+ ? null
657+ : cqlType.getTypeArguments().get(0);
662658 DataType valueType = (cqlType == null || cqlType.getTypeArguments().size() < 2)
663- ? null
664- : cqlType.getTypeArguments().get(1);
665- Map.Entry entry = (Map.Entry)map.entrySet().iterator().next();
666- return (TypeCodec<T>)TypeCodec.map(
667- findCodec(keyType, entry.getKey()),
668- findCodec(valueType, entry.getValue()));
659+ ? null
660+ : cqlType.getTypeArguments().get(1);
661+ Map.Entry entry = (Map.Entry) map.entrySet().iterator().next();
662+ return (TypeCodec<T>) TypeCodec.map(
663+ findCodec(keyType, entry.getKey()),
664+ findCodec(valueType, entry.getValue()));
669665 }
670666 }
671667
672668 if ((cqlType == null || cqlType.getName() == DataType.Name.TUPLE) && value instanceof TupleValue) {
673- return (TypeCodec<T>)TypeCodec.tuple(cqlType == null ? ((TupleValue)value).getType() : (TupleType)cqlType);
669+ return (TypeCodec<T>) TypeCodec.tuple(cqlType == null ? ((TupleValue) value).getType() : (TupleType) cqlType);
674670 }
675671
676672 if ((cqlType == null || cqlType.getName() == DataType.Name.UDT) && value instanceof UDTValue) {
677- return (TypeCodec<T>)TypeCodec.userType(cqlType == null ? ((UDTValue)value).getType() : (UserType)cqlType);
673+ return (TypeCodec<T>) TypeCodec.userType(cqlType == null ? ((UDTValue) value).getType() : (UserType) cqlType);
678674 }
679675
680- if((cqlType != null && cqlType instanceof DataType.CustomType) && value instanceof ByteBuffer) {
681- return (TypeCodec<T>)TypeCodec.custom((DataType.CustomType)cqlType);
676+ if ((cqlType != null && cqlType instanceof DataType.CustomType) && value instanceof ByteBuffer) {
677+ return (TypeCodec<T>) TypeCodec.custom((DataType.CustomType) cqlType);
682678 }
683679
684680 return null;
@@ -686,8 +682,8 @@
686682
687683 private static CodecNotFoundException notFound(DataType cqlType, TypeToken<?> javaType) {
688684 String msg = String.format("Codec not found for requested operation: [%s <-> %s]",
689- cqlType == null ? "ANY" : cqlType,
690- javaType == null ? "ANY" : javaType);
685+ cqlType == null ? "ANY" : cqlType,
686+ javaType == null ? "ANY" : javaType);
691687 return new CodecNotFoundException(msg, cqlType, javaType);
692688 }
693689
modified driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java +21 −27
@@ -16,14 +16,6 @@
1616 package com.datastax.driver.core;
1717
1818 import java.nio.ByteBuffer;
19-import java.util.List;
20-import java.util.Map;
21-import java.util.Set;
22-
23-import com.google.common.reflect.TypeParameter;
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
2719
2820 /**
2921 * A set of utility methods to deal with type conversion and serialization.
@@ -34,16 +26,17 @@
3426
3527 private static final long EPOCH_AS_CQL_LONG = (1L << 31);
3628
37- private CodecUtils(){}
29+ private CodecUtils() {
30+ }
3831
3932 /**
4033 * Utility method that "packs" together a list of {@link ByteBuffer}s containing
4134 * serialized collection elements.
4235 * Mainly intended for use with collection codecs when serializing collections.
4336 *
44- * @param buffers the collection elements
37+ * @param buffers the collection elements
4538 * @param elements the total number of elements
46- * @param version the protocol version to use
39+ * @param version the protocol version to use
4740 * @return The serialized collection
4841 */
4942 public static ByteBuffer pack(ByteBuffer[] buffers, int elements, ProtocolVersion version) {
@@ -56,13 +49,14 @@
5649 writeSize(result, elements, version);
5750 for (ByteBuffer bb : buffers)
5851 writeValue(result, bb, version);
59- return (ByteBuffer)result.flip();
52+ return (ByteBuffer) result.flip();
6053 }
6154
6255 /**
6356 * Utility method that reads a size value.
6457 * Mainly intended for collection codecs when deserializing CQL collections.
65- * @param input The ByteBuffer to read from.
58+ *
59+ * @param input The ByteBuffer to read from.
6660 * @param version The protocol version to use.
6761 * @return The size value.
6862 */
@@ -83,8 +77,8 @@
8377 * Utility method that writes a size value.
8478 * Mainly intended for collection codecs when serializing CQL collections.
8579 *
86- * @param output The ByteBuffer to write to.
87- * @param size The collection size.
80+ * @param output The ByteBuffer to write to.
81+ * @param size The collection size.
8882 * @param version The protocol version to use.
8983 */
9084 public static void writeSize(ByteBuffer output, int size, ProtocolVersion version) {
@@ -93,7 +87,7 @@
9387 case V2:
9488 if (size > 65535)
9589 throw new IllegalArgumentException(String.format("Native protocol version %d supports up to 65535 elements in any collection - but collection contains %d elements", version.toInt(), size));
96- output.putShort((short)size);
90+ output.putShort((short) size);
9791 break;
9892 case V3:
9993 case V4:
@@ -108,7 +102,7 @@
108102 * Utility method that reads a value.
109103 * Mainly intended for collection codecs when deserializing CQL collections.
110104 *
111- * @param input The ByteBuffer to read from.
105+ * @param input The ByteBuffer to read from.
112106 * @param version The protocol version to use.
113107 * @return The collection element.
114108 */
@@ -120,9 +114,9 @@
120114 /**
121115 * Utility method that writes a value.
122116 * Mainly intended for collection codecs when deserializing CQL collections.
123-
124- * @param output The ByteBuffer to write to.
125- * @param value The value to write.
117+ *
118+ * @param output The ByteBuffer to write to.
119+ * @param value The value to write.
126120 * @param version The protocol version to use.
127121 */
128122 public static void writeValue(ByteBuffer output, ByteBuffer value, ProtocolVersion version) {
@@ -130,7 +124,7 @@
130124 case V1:
131125 case V2:
132126 assert value != null;
133- output.putShort((short)value.remaining());
127+ output.putShort((short) value.remaining());
134128 output.put(value.duplicate());
135129 break;
136130 case V3:
@@ -150,7 +144,7 @@
150144 /**
151145 * Read {@code length} bytes from {@code bb} into a new ByteBuffer.
152146 *
153- * @param bb The ByteBuffer to read.
147+ * @param bb The ByteBuffer to read.
154148 * @param length The number of bytes to read.
155149 * @return The read bytes.
156150 */
@@ -163,7 +157,7 @@
163157
164158 /**
165159 * Converts an "unsigned" int read from a DATE value into a signed int.
166- * <p>
160+ * <p/>
167161 * The protocol encodes DATE values as <em>unsigned</em> ints with the Epoch in the middle of the range (2^31).
168162 * This method handles the conversion from an "unsigned" to a signed int.
169163 */
@@ -173,7 +167,7 @@
173167
174168 /**
175169 * Converts an int into an "unsigned" int suitable to be written as a DATE value.
176- * <p>
170+ * <p/>
177171 * The protocol encodes DATE values as <em>unsigned</em> ints with the Epoch in the middle of the range (2^31).
178172 * This method handles the conversion from a signed to an "unsigned" int.
179173 */
@@ -195,13 +189,13 @@
195189 public static int fromCqlDateToDaysSinceEpoch(long raw) {
196190 if (raw < 0 || raw > MAX_CQL_LONG_VALUE)
197191 throw new IllegalArgumentException(String.format("Numeric literals for DATE must be between 0 and %d (got %d)", MAX_CQL_LONG_VALUE, raw));
198- return (int)(raw - EPOCH_AS_CQL_LONG);
192+ return (int) (raw - EPOCH_AS_CQL_LONG);
199193 }
200194
201195 /**
202196 * Convert the number of days since the Epoch into
203197 * a raw CQL long representing a numeric DATE literal.
204- *
198+ * <p/>
205199 * In CQL, numeric DATE literals are longs (unsigned integers actually)
206200 * between 0 and 2^32 - 1, with the epoch in the middle;
207201 * this method re-centers the epoch at 2^31.
@@ -210,7 +204,7 @@
210204 * @return The CQL date value corresponding to the given value.
211205 */
212206 public static long fromDaysSinceEpochToCqlDate(int days) {
213- return ((long)days + EPOCH_AS_CQL_LONG);
207+ return ((long) days + EPOCH_AS_CQL_LONG);
214208 }
215209
216210 private static int sizeOfCollectionSize(ProtocolVersion version) {
modified driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java +21 −28
@@ -20,15 +20,15 @@
2020 /**
2121 * Metadata describing the columns returned in a {@link ResultSet} or a
2222 * {@link PreparedStatement}.
23- * <p>
23+ * <p/>
2424 * A {@code columnDefinitions}} instance is mainly a list of
2525 * {@code ColumnsDefinitions.Definition}. The definitions or metadata for a column
2626 * can be accessed either by:
2727 * <ul>
28- * <li>index (indexed from 0)</li>
29- * <li>name</li>
28+ * <li>index (indexed from 0)</li>
29+ * <li>name</li>
3030 * </ul>
31- * <p>
31+ * <p/>
3232 * When accessed by name, column selection is case insensitive. In case multiple
3333 * columns only differ by the case of their name, then the column returned with
3434 * be the first column that has been defined in CQL without forcing case sensitivity
@@ -36,17 +36,17 @@
3636 * If none of the columns have been defined in this manner, the first column matching
3737 * (with case insensitivity) is returned. You can force the case of a selection
3838 * by double quoting the name.
39- * <p>
39+ * <p/>
4040 * For example:
4141 * <ul>
42- * <li>If {@code cd} contains column {@code fOO}, then {@code cd.contains("foo")},
43- * {@code cd.contains("fOO")} and {@code cd.contains("Foo")} will return {@code true}.</li>
44- * <li>If {@code cd} contains both {@code foo} and {@code FOO} then:
45- * <ul>
46- * <li>{@code cd.getType("foo")}, {@code cd.getType("fOO")} and {@code cd.getType("FOO")}
47- * will all match column {@code foo}.</li>
48- * <li>{@code cd.getType("\"FOO\"")} will match column {@code FOO}</li>
49- * </ul>
42+ * <li>If {@code cd} contains column {@code fOO}, then {@code cd.contains("foo")},
43+ * {@code cd.contains("fOO")} and {@code cd.contains("Foo")} will return {@code true}.</li>
44+ * <li>If {@code cd} contains both {@code foo} and {@code FOO} then:
45+ * <ul>
46+ * <li>{@code cd.getType("foo")}, {@code cd.getType("fOO")} and {@code cd.getType("FOO")}
47+ * will all match column {@code foo}.</li>
48+ * <li>{@code cd.getType("\"FOO\"")} will match column {@code FOO}</li>
49+ * </ul>
5050 * </ul>
5151 * Note that the preceding rules mean that if a {@code ColumnDefinitions} object
5252 * 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) {
@@ -334,19 +327,19 @@
334327
335328 @Override
336329 public final int hashCode() {
337- return Arrays.hashCode(new Object[]{ keyspace, table, name, type});
330+ return Arrays.hashCode(new Object[]{keyspace, table, name, type});
338331 }
339332
340333 @Override
341334 public final boolean equals(Object o) {
342- if(!(o instanceof Definition))
335+ if (!(o instanceof Definition))
343336 return false;
344337
345- Definition other = (Definition)o;
338+ Definition other = (Definition) o;
346339 return keyspace.equals(other.keyspace)
347- && table.equals(other.table)
348- && name.equals(other.name)
349- && type.equals(other.type);
340+ && table.equals(other.table)
341+ && name.equals(other.name)
342+ && type.equals(other.type);
350343 }
351344 }
352345 }
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +17 −17
@@ -15,12 +15,12 @@
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.HashMap;
2022 import java.util.Map;
2123
22-import com.google.common.base.Objects;
23-
2424 /**
2525 * Describes a Column.
2626 */
@@ -108,10 +108,10 @@
108108 if (!(other instanceof ColumnMetadata))
109109 return false;
110110
111- ColumnMetadata that = (ColumnMetadata)other;
111+ ColumnMetadata that = (ColumnMetadata) other;
112112 return this.name.equals(that.name) &&
113- this.isStatic == that.isStatic &&
114- this.type.equals(that.type);
113+ this.isStatic == that.isStatic &&
114+ this.type.equals(that.type);
115115 }
116116
117117 @Override
@@ -131,11 +131,11 @@
131131
132132 public enum Kind {
133133
134- PARTITION_KEY ("PARTITION_KEY" , "PARTITION_KEY"),
135- CLUSTERING_COLUMN ("CLUSTERING_KEY", "CLUSTERING" ),
136- REGULAR ("REGULAR" , "REGULAR" ),
137- COMPACT_VALUE ("COMPACT_VALUE" , "" ), // v2 only
138- STATIC ("STATIC" , "STATIC" );
134+ PARTITION_KEY("PARTITION_KEY", "PARTITION_KEY"),
135+ CLUSTERING_COLUMN("CLUSTERING_KEY", "CLUSTERING"),
136+ REGULAR("REGULAR", "REGULAR"),
137+ COMPACT_VALUE("COMPACT_VALUE", ""), // v2 only
138+ STATIC("STATIC", "STATIC");
139139
140140 final String v2;
141141 final String v3;
@@ -147,7 +147,7 @@
147147
148148 static Kind fromStringV2(String s) {
149149 for (Kind kind : Kind.values()) {
150- if(kind.v2.equalsIgnoreCase(s))
150+ if (kind.v2.equalsIgnoreCase(s))
151151 return kind;
152152 }
153153 throw new IllegalArgumentException(s);
@@ -155,7 +155,7 @@
155155
156156 static Kind fromStringV3(String s) {
157157 for (Kind kind : Kind.values()) {
158- if(kind.v3.equalsIgnoreCase(s))
158+ if (kind.v3.equalsIgnoreCase(s))
159159 return kind;
160160 }
161161 throw new IllegalArgumentException(s);
@@ -182,7 +182,7 @@
182182 String name = row.getString(COLUMN_NAME);
183183
184184 Kind kind;
185- if(version.getMajor() < 2) {
185+ if (version.getMajor() < 2) {
186186 kind = Kind.REGULAR;
187187 } else if (version.getMajor() < 3) {
188188 kind = row.isNull(KIND_V2) ? Kind.REGULAR : Kind.fromStringV2(row.getString(KIND_V2));
@@ -191,16 +191,16 @@
191191 }
192192
193193 int position;
194- if(version.getMajor() >= 3) {
194+ if (version.getMajor() >= 3) {
195195 position = row.getInt(POSITION); // cannot be null, -1 is used as a special value instead of null to avoid tombstones
196- if(position == -1) position = 0;
196+ if (position == -1) position = 0;
197197 } else {
198198 position = row.isNull(COMPONENT_INDEX) ? 0 : row.getInt(COMPONENT_INDEX);
199199 }
200200
201201 String dataType;
202202 boolean reversed;
203- if(version.getMajor() >= 3) {
203+ if (version.getMajor() >= 3) {
204204 dataType = row.getString(TYPE);
205205 String clusteringOrderStr = row.getString(CLUSTERING_ORDER);
206206 reversed = clusteringOrderStr.equals(DESC);
@@ -213,7 +213,7 @@
213213
214214 // secondary indexes (C* < 3.0.0)
215215 // from C* 3.0 onwards 2i are defined in a separate table
216- if(version.getMajor() < 3) {
216+ if (version.getMajor() < 3) {
217217 for (String str : Arrays.asList(INDEX_TYPE, INDEX_NAME, INDEX_OPTIONS))
218218 if (row.getColumnDefinitions().contains(str) && !row.isNull(str))
219219 c.indexColumns.put(str, row.getString(str));
modified driver-core/src/main/java/com/datastax/driver/core/Configuration.java +37 −29
@@ -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).
@@ -35,7 +35,7 @@
3535
3636 /**
3737 * Returns a builder to create a new {@code Configuration} object.
38- * <p>
38+ * <p/>
3939 * You only need this if you are building the configuration yourself. If you
4040 * use {@link Cluster#builder()}, it will be done under the hood for you.
4141 *
@@ -55,13 +55,13 @@
5555 private final CodecRegistry codecRegistry;
5656
5757 private Configuration(Policies policies,
58- ProtocolOptions protocolOptions,
59- PoolingOptions poolingOptions,
60- SocketOptions socketOptions,
61- MetricsOptions metricsOptions,
62- QueryOptions queryOptions,
63- NettyOptions nettyOptions,
64- CodecRegistry codecRegistry) {
58+ ProtocolOptions protocolOptions,
59+ PoolingOptions poolingOptions,
60+ SocketOptions socketOptions,
61+ MetricsOptions metricsOptions,
62+ QueryOptions queryOptions,
63+ NettyOptions nettyOptions,
64+ CodecRegistry codecRegistry) {
6565 this.policies = policies;
6666 this.protocolOptions = protocolOptions;
6767 this.poolingOptions = poolingOptions;
@@ -116,7 +116,7 @@
116116
117117 /**
118118 * Returns the metrics configuration, if metrics are enabled.
119- * <p>
119+ * <p/>
120120 * Metrics collection is enabled by default but can be disabled at cluster
121121 * construction time through {@link Cluster.Builder#withoutMetrics}.
122122 *
@@ -137,6 +137,7 @@
137137
138138 /**
139139 * Returns the {@link NettyOptions} instance for this configuration.
140+ *
140141 * @return the {@link NettyOptions} instance for this configuration.
141142 */
142143 public NettyOptions getNettyOptions() {
@@ -145,7 +146,7 @@
145146
146147 /**
147148 * Returns the {@link CodecRegistry} instance for this configuration.
148- * <p>
149+ * <p/>
149150 * Note that this method could return {@link CodecRegistry#DEFAULT_INSTANCE}
150151 * if no specific codec registry has been set on the {@link Cluster}.
151152 * In this case, care should be taken when registering new codecs as they would be
@@ -172,6 +173,7 @@
172173
173174 /**
174175 * Sets the policies for this cluster.
176+ *
175177 * @param policies the policies.
176178 * @return this builder.
177179 */
@@ -182,6 +184,7 @@
182184
183185 /**
184186 * Sets the protocol options for this cluster.
187+ *
185188 * @param protocolOptions the protocol options.
186189 * @return this builder.
187190 */
@@ -192,6 +195,7 @@
192195
193196 /**
194197 * Sets the pooling options for this cluster.
198+ *
195199 * @param poolingOptions the pooling options.
196200 * @return this builder.
197201 */
@@ -202,6 +206,7 @@
202206
203207 /**
204208 * Sets the socket options for this cluster.
209+ *
205210 * @param socketOptions the socket options.
206211 * @return this builder.
207212 */
@@ -209,10 +214,10 @@
209214 this.socketOptions = socketOptions;
210215 return this;
211216 }
212-
217+
213218 /**
214219 * Sets the metrics options for this cluster.
215- * <p>
220+ * <p/>
216221 * If this method doesn't get called, the configuration will use the
217222 * defaults: metrics enabled with JMX reporting enabled.
218223 * To disable metrics, call this method with an instance where
@@ -225,9 +230,10 @@
225230 this.metricsOptions = metricsOptions;
226231 return this;
227232 }
228-
233+
229234 /**
230235 * Sets the query options for this cluster.
236+ *
231237 * @param queryOptions the query options.
232238 * @return this builder.
233239 */
@@ -235,9 +241,10 @@
235241 this.queryOptions = queryOptions;
236242 return this;
237243 }
238-
244+
239245 /**
240246 * Sets the Netty options for this cluster.
247+ *
241248 * @param nettyOptions the Netty options.
242249 * @return this builder.
243250 */
@@ -248,6 +255,7 @@
248255
249256 /**
250257 * Sets the codec registry for this cluster.
258+ *
251259 * @param codecRegistry the codec registry.
252260 * @return this builder.
253261 */
@@ -258,21 +266,21 @@
258266
259267 /**
260268 * Builds the final object from this builder.
261- * <p>
269+ * <p/>
262270 * Any field that hasn't been set explicitly will get its default value.
263271 *
264272 * @return the object.
265273 */
266274 public Configuration build() {
267275 return new Configuration(
268- policies != null ? policies : Policies.builder().build(),
269- protocolOptions != null ? protocolOptions : new ProtocolOptions(),
270- poolingOptions != null ? poolingOptions : new PoolingOptions(),
271- socketOptions != null ? socketOptions : new SocketOptions(),
272- metricsOptions != null ? metricsOptions : new MetricsOptions(),
273- queryOptions != null ? queryOptions : new QueryOptions(),
274- nettyOptions != null ? nettyOptions : NettyOptions.DEFAULT_INSTANCE,
275- codecRegistry != null ? codecRegistry : CodecRegistry.DEFAULT_INSTANCE);
276+ policies != null ? policies : Policies.builder().build(),
277+ protocolOptions != null ? protocolOptions : new ProtocolOptions(),
278+ poolingOptions != null ? poolingOptions : new PoolingOptions(),
279+ socketOptions != null ? socketOptions : new SocketOptions(),
280+ metricsOptions != null ? metricsOptions : new MetricsOptions(),
281+ queryOptions != null ? queryOptions : new QueryOptions(),
282+ nettyOptions != null ? nettyOptions : NettyOptions.DEFAULT_INSTANCE,
283+ codecRegistry != null ? codecRegistry : CodecRegistry.DEFAULT_INSTANCE);
276284 }
277285 }
278286 }
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +91 −90
@@ -15,17 +15,9 @@
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.*;
20+import com.datastax.driver.core.utils.MoreFutures;
2921 import com.google.common.annotations.VisibleForTesting;
3022 import com.google.common.collect.Lists;
3123 import com.google.common.collect.MapMaker;
@@ -44,13 +36,19 @@
4436 import org.slf4j.Logger;
4537 import org.slf4j.LoggerFactory;
4638
47-import static io.netty.handler.timeout.IdleState.ALL_IDLE;
48-
49-import com.datastax.driver.core.Responses.Result.SetKeyspace;
50-import com.datastax.driver.core.exceptions.*;
51-import com.datastax.driver.core.utils.MoreFutures;
39+import java.lang.ref.WeakReference;
40+import java.net.InetSocketAddress;
41+import java.util.HashSet;
42+import java.util.Iterator;
43+import java.util.List;
44+import java.util.Queue;
45+import java.util.concurrent.*;
46+import java.util.concurrent.atomic.AtomicBoolean;
47+import java.util.concurrent.atomic.AtomicInteger;
48+import java.util.concurrent.atomic.AtomicReference;
5249
5350 import static com.datastax.driver.core.Message.Response.Type.ERROR;
51+import static io.netty.handler.timeout.IdleState.ALL_IDLE;
5452
5553 // For LoggingHandler
5654 //import org.jboss.netty.handler.logging.LoggingHandler;
@@ -66,7 +64,7 @@
6664
6765 private static final boolean DISABLE_COALESCING = SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false);
6866
69- enum State {OPEN, TRASHED, RESURRECTING, GONE }
67+ enum State {OPEN, TRASHED, RESURRECTING, GONE}
7068
7169 final AtomicReference<State> state = new AtomicReference<State>(State.OPEN);
7270
@@ -96,14 +94,14 @@
9694 private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>();
9795
9896 /**
99- /**
97+ * /**
10098 * Create a new connection to a Cassandra node and associate it with the given pool.
10199 *
102- * @param name the connection name
100+ * @param name the connection name
103101 * @param address the remote address
104102 * @param factory the connection factory to use
105- * @param owner the component owning this connection (may be null).
106- * Note that an existing connection can also be associated to an owner later with {@link #setOwner(Owner)}.
103+ * @param owner the component owning this connection (may be null).
104+ * Note that an existing connection can also be associated to an owner later with {@link #setOwner(Owner)}.
107105 */
108106 protected Connection(String name, InetSocketAddress address, Factory factory, Owner owner) {
109107 this.address = address;
@@ -131,10 +129,10 @@
131129 Bootstrap bootstrap = factory.newBootstrap();
132130 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
133131 bootstrap.handler(
134- new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(),
135- factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
136- factory.configuration.getNettyOptions(),
137- factory.configuration.getCodecRegistry()));
132+ new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(),
133+ factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
134+ factory.configuration.getNettyOptions(),
135+ factory.configuration.getCodecRegistry()));
138136
139137 ChannelFuture future = bootstrap.connect(address);
140138
@@ -173,7 +171,7 @@
173171 Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor();
174172
175173 ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture,
176- onChannelReady(protocolVersion, initExecutor), initExecutor);
174+ onChannelReady(protocolVersion, initExecutor), initExecutor);
177175
178176 // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
179177 ListenableFuture<Void> initFuture = Futures.withFallback(initializeTransportFuture, new FutureFallback<Void>() {
@@ -188,10 +186,10 @@
188186 } else {
189187 // Defunct to ensure that the error will be signaled (marking the host down)
190188 Exception e = (t instanceof ConnectionException || t instanceof DriverException || t instanceof InterruptedException)
191- ? (Exception)t
192- : new ConnectionException(Connection.this.address,
193- String.format("Unexpected error during transport initialization (%s)", t),
194- t);
189+ ? (Exception) t
190+ : new ConnectionException(Connection.this.address,
191+ String.format("Unexpected error during transport initialization (%s)", t),
192+ t);
195193 future.setException(defunct(e));
196194 }
197195 return future;
@@ -215,8 +213,8 @@
215213 if (t == null)
216214 return "";
217215 String msg = t.getMessage() == null || t.getMessage().isEmpty()
218- ? t.toString()
219- : t.getMessage();
216+ ? t.toString()
217+ : t.getMessage();
220218 return " (" + msg + ')';
221219 }
222220
@@ -227,7 +225,7 @@
227225 ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
228226 Future startupResponseFuture = write(new Requests.Startup(compression));
229227 return Futures.transform(startupResponseFuture,
230- onStartupResponse(protocolVersion, initExecutor), initExecutor);
228+ onStartupResponse(protocolVersion, initExecutor), initExecutor);
231229 }
232230 };
233231 }
@@ -240,15 +238,15 @@
240238 case READY:
241239 return checkClusterName(protocolVersion, initExecutor);
242240 case ERROR:
243- Responses.Error error = (Responses.Error)response;
241+ Responses.Error error = (Responses.Error) response;
244242 // Testing for a specific string is a tad fragile but well, we don't have much choice
245243 // C* 2.1 reports a server error instead of protocol error, see CASSANDRA-9451
246244 if ((error.code == ExceptionCode.PROTOCOL_ERROR || error.code == ExceptionCode.SERVER_ERROR) &&
247- error.message.contains("Invalid or unsupported protocol version"))
245+ error.message.contains("Invalid or unsupported protocol version"))
248246 throw unsupportedProtocolVersionException(protocolVersion, error.serverProtocolVersion);
249247 throw new TransportException(address, String.format("Error initializing connection: %s", error.message));
250248 case AUTHENTICATE:
251- Responses.Authenticate authenticate = (Responses.Authenticate)response;
249+ Responses.Authenticate authenticate = (Responses.Authenticate) response;
252250 Authenticator authenticator = factory.authProvider.newAuthenticator(address, authenticate.authenticator);
253251 switch (protocolVersion) {
254252 case V1:
@@ -287,17 +285,17 @@
287285 try {
288286 write(clusterNameFuture);
289287 return Futures.transform(clusterNameFuture,
290- new AsyncFunction<ResultSet, Void>() {
291- @Override
292- public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
293- Row row = rs.one();
294- String actual = row.getString("cluster_name");
295- if (!expected.equals(actual))
296- throw new ClusterNameMismatchException(address, actual, expected);
297- markInitialized();
298- return MoreFutures.VOID_SUCCESS;
299- }
300- }, executor);
288+ new AsyncFunction<ResultSet, Void>() {
289+ @Override
290+ public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
291+ Row row = rs.one();
292+ String actual = row.getString("cluster_name");
293+ if (!expected.equals(actual))
294+ throw new ClusterNameMismatchException(address, actual, expected);
295+ markInitialized();
296+ return MoreFutures.VOID_SUCCESS;
297+ }
298+ }, executor);
301299 } catch (Exception e) {
302300 return Futures.immediateFailedFuture(e);
303301 }
@@ -309,23 +307,23 @@
309307 }
310308
311309 private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final ProtocolVersion protocolVersion, final Executor executor) {
312- Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials());
310+ Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator) authenticator).getCredentials());
313311 try {
314312 Future authResponseFuture = write(creds);
315313 return Futures.transform(authResponseFuture,
316- new AsyncFunction<Message.Response, Void>() {
317- @Override
318- public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
319- switch (authResponse.type) {
320- case READY:
321- return checkClusterName(protocolVersion, executor);
322- case ERROR:
323- throw new AuthenticationException(address, ((Responses.Error)authResponse).message);
324- default:
325- throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
314+ new AsyncFunction<Message.Response, Void>() {
315+ @Override
316+ public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
317+ switch (authResponse.type) {
318+ case READY:
319+ return checkClusterName(protocolVersion, executor);
320+ case ERROR:
321+ throw new AuthenticationException(address, ((Responses.Error) authResponse).message);
322+ default:
323+ throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
324+ }
326325 }
327- }
328- }, executor);
326+ }, executor);
329327 } catch (Exception e) {
330328 return Futures.immediateFailedFuture(e);
331329 }
@@ -351,10 +349,10 @@
351349 switch (authResponse.type) {
352350 case AUTH_SUCCESS:
353351 logger.trace("{} Authentication complete", this);
354- authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token);
352+ authenticator.onAuthenticationSuccess(((Responses.AuthSuccess) authResponse).token);
355353 return checkClusterName(protocolVersion, executor);
356354 case AUTH_CHALLENGE:
357- byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token);
355+ byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge) authResponse).token);
358356 if (responseToServer == null) {
359357 // If we generate a null response, then authentication has completed, proceed without
360358 // sending a further response back to the server.
@@ -371,10 +369,10 @@
371369 // attempted v2 auth against a server which only supports v1
372370 // The AIOOBE indicates that the server didn't recognise the
373371 // initial AuthResponse message
374- String message = ((Responses.Error)authResponse).message;
372+ String message = ((Responses.Error) authResponse).message;
375373 if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
376374 message = String.format("Cannot use authenticator %s with protocol version 1, "
377- + "only plain text authentication is supported with this protocol version", authenticator);
375+ + "only plain text authentication is supported with this protocol version", authenticator);
378376 throw new AuthenticationException(address, message);
379377 default:
380378 throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type));
@@ -439,14 +437,14 @@
439437 throw defunct(e);
440438 } catch (BusyConnectionException e) {
441439 logger.warn("Tried to set the keyspace on busy {}. "
442- + "This should not happen but is not critical (it will be retried)", this);
440+ + "This should not happen but is not critical (it will be retried)", this);
443441 throw new ConnectionException(address, "Tried to set the keyspace on busy connection");
444442 } catch (ExecutionException e) {
445443 Throwable cause = e.getCause();
446444 if (cause instanceof OperationTimedOutException) {
447445 // Rethrow so that the caller doesn't try to use the connection, but do not defunct as we don't want to mark down
448446 logger.warn("Timeout while setting keyspace on {}. "
449- + "This should not happen but is not critical (it will be retried)", this);
447+ + "This should not happen but is not critical (it will be retried)", this);
450448 throw new ConnectionException(address, "Timeout while setting keyspace on connection");
451449 } else {
452450 throw defunct(new ConnectionException(address, "Error while setting keyspace", cause));
@@ -462,11 +460,11 @@
462460 @Override
463461 public ListenableFuture<Void> apply(Message.Response response) throws Exception {
464462 if (response instanceof SetKeyspace) {
465- Connection.this.keyspace = ((SetKeyspace)response).keyspace;
463+ Connection.this.keyspace = ((SetKeyspace) response).keyspace;
466464 return MoreFutures.VOID_SUCCESS;
467465 } else if (response.type == ERROR) {
468466 closeAsync().force();
469- Responses.Error error = (Responses.Error)response;
467+ Responses.Error error = (Responses.Error) response;
470468 throw error.asException(address);
471469 } else {
472470 closeAsync().force();
@@ -481,9 +479,8 @@
481479 *
482480 * @param request the request to send
483481 * @return a future on the server response
484- *
485482 * @throws ConnectionException if the connection is closed
486- * @throws TransportException if an I/O error while sending the request
483+ * @throws TransportException if an I/O error while sending the request
487484 */
488485 public Future write(Message.Request request) throws ConnectionException, BusyConnectionException {
489486 Future future = new Future(request);
@@ -577,7 +574,9 @@
577574 return this.ownerRef.get() != null;
578575 }
579576
580- /** @return whether the connection was already associated with an owner */
577+ /**
578+ * @return whether the connection was already associated with an owner
579+ */
581580 boolean setOwner(Owner owner) {
582581 return ownerRef.compareAndSet(null, owner);
583582 }
@@ -589,7 +588,7 @@
589588 void release() {
590589 Owner owner = ownerRef.get();
591590 if (owner instanceof HostConnectionPool)
592- ((HostConnectionPool)owner).returnConnection(this);
591+ ((HostConnectionPool) owner).returnConnection(this);
593592 }
594593
595594 public boolean isClosed() {
@@ -598,13 +597,12 @@
598597
599598 /**
600599 * Closes the connection: no new writes will be accepted after this method has returned.
601- *
600+ * <p/>
602601 * However, a closed connection might still have ongoing queries awaiting for their result.
603602 * When all these ongoing queries have completed, the underlying channel will be closed; we
604603 * refer to this final state as "terminated".
605604 *
606605 * @return a future that will complete once the connection has terminated.
607- *
608606 * @see #tryTerminate(boolean)
609607 */
610608 public CloseFuture closeAsync() {
@@ -644,12 +642,11 @@
644642
645643 /**
646644 * Tries to terminate a closed connection, i.e. release system resources.
647- *
645+ * <p/>
648646 * This is called both by "normal" code and by {@link Cluster.ConnectionReaper}.
649647 *
650648 * @param force whether to proceed if there are still outstanding requests.
651649 * @return whether the connection has actually terminated.
652- *
653650 * @see #closeAsync()
654651 */
655652 boolean tryTerminate(boolean force) {
@@ -719,7 +716,6 @@
719716 * Opens a new connection to the node this factory points to.
720717 *
721718 * @return the newly created (and initialized) connection.
722- *
723719 * @throws ConnectionException if connection attempt fails.
724720 */
725721 public Connection open(Host host) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
@@ -771,15 +767,15 @@
771767 static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
772768 Throwable t = e.getCause();
773769 if (t instanceof ConnectionException)
774- throw (ConnectionException)t;
770+ throw (ConnectionException) t;
775771 if (t instanceof InterruptedException)
776- throw (InterruptedException)t;
772+ throw (InterruptedException) t;
777773 if (t instanceof UnsupportedProtocolVersionException)
778- throw (UnsupportedProtocolVersionException)t;
774+ throw (UnsupportedProtocolVersionException) t;
779775 if (t instanceof ClusterNameMismatchException)
780- throw (ClusterNameMismatchException)t;
776+ throw (ClusterNameMismatchException) t;
781777 if (t instanceof DriverException)
782- throw (DriverException)t;
778+ throw (DriverException) t;
783779
784780 return new RuntimeException("Unexpected exception during connection initialization", t);
785781 }
@@ -802,7 +798,7 @@
802798 private Bootstrap newBootstrap() {
803799 Bootstrap b = new Bootstrap();
804800 b.group(eventLoopGroup)
805- .channel(channelClass);
801+ .channel(channelClass);
806802
807803 SocketOptions options = configuration.getSocketOptions();
808804
@@ -900,7 +896,7 @@
900896 }
901897
902898 private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new MapMaker()
903- .concurrencyLevel(16)
899+ .concurrencyLevel(16)
904900 .weakKeys()
905901 .makeMap();
906902
@@ -979,7 +975,7 @@
979975 protected void channelRead0(ChannelHandlerContext ctx, Message.Response response) throws Exception {
980976 int streamId = response.getStreamId();
981977
982- if(logger.isTraceEnabled())
978+ if (logger.isTraceEnabled())
983979 logger.trace("{}, stream {}, received: {}", Connection.this, streamId, asDebugString(response));
984980
985981 if (streamId < 0) {
@@ -1002,7 +998,7 @@
1002998 streamIdHandler.unmark(streamId);
1003999 if (logger.isDebugEnabled())
10041000 logger.debug("{} Response received on stream {} but no handler set anymore (either the request has "
1005- + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
1001+ + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
10061002 return;
10071003 }
10081004 handler.cancelTimeout();
@@ -1016,7 +1012,7 @@
10161012
10171013 @Override
10181014 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
1019- if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) {
1015+ if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == ALL_IDLE) {
10201016 logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
10211017 write(HEARTBEAT_CALLBACK);
10221018 }
@@ -1048,8 +1044,7 @@
10481044
10491045 public void errorOutAllHandler(ConnectionException ce) {
10501046 Iterator<ResponseHandler> iter = pending.values().iterator();
1051- while (iter.hasNext())
1052- {
1047+ while (iter.hasNext()) {
10531048 ResponseHandler handler = iter.next();
10541049 handler.cancelTimeout();
10551050 handler.callback.onException(Connection.this, ce, System.nanoTime() - handler.startTime, handler.retryCount);
@@ -1202,9 +1197,13 @@
12021197
12031198 interface ResponseCallback {
12041199 public Message.Request request();
1200+
12051201 public int retryCount();
1202+
12061203 public void onSet(Connection connection, Message.Response response, long latency, int retryCount);
1204+
12071205 public void onException(Connection connection, Exception exception, long latency, int retryCount);
1206+
12081207 public boolean onTimeout(Connection connection, long latency, int retryCount);
12091208 }
12101209
@@ -1343,7 +1342,9 @@
13431342 }
13441343 }
13451344
1346- /** A component that "owns" a connection, and should be notified when it dies. */
1345+ /**
1346+ * A component that "owns" a connection, and should be notified when it dies.
1347+ */
13471348 interface Owner {
13481349 void onConnectionDefunct(Connection connection);
13491350 }
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 +25 −25
@@ -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.*;
2519 import com.google.common.annotations.VisibleForTesting;
2620 import com.google.common.base.Objects;
2721 import com.google.common.util.concurrent.ListenableFuture;
2822 import org.slf4j.Logger;
2923 import org.slf4j.LoggerFactory;
3024
31-import com.datastax.driver.core.exceptions.*;
25+import java.net.InetAddress;
26+import java.net.InetSocketAddress;
27+import java.net.UnknownHostException;
28+import java.util.*;
29+import java.util.concurrent.ExecutionException;
30+import java.util.concurrent.TimeUnit;
31+import java.util.concurrent.atomic.AtomicReference;
3232
33-import static com.datastax.driver.core.SchemaElement.*;
33+import static com.datastax.driver.core.SchemaElement.KEYSPACE;
3434
3535 class ControlConnection implements Connection.Owner {
3636
@@ -94,8 +94,8 @@
9494 Host connectedHost() {
9595 Connection current = connectionRef.get();
9696 return (current == null)
97- ? null
98- : cluster.metadata.getHost(current.address);
97+ ? null
98+ : cluster.metadata.getHost(current.address);
9999 }
100100
101101 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
@@ -296,8 +296,8 @@
296296
297297 public void refreshSchema(SchemaElement targetType, String targetKeyspace, String targetName, List<String> signature) throws InterruptedException {
298298 logger.debug("[Control connection] Refreshing schema for {}{}",
299- targetType == null ? "everything" : targetKeyspace,
300- (targetType == KEYSPACE) ? "" : "." + targetName + " (" + targetType + ")");
299+ targetType == null ? "everything" : targetKeyspace,
300+ (targetType == KEYSPACE) ? "" : "." + targetName + " (" + targetType + ")");
301301 try {
302302 Connection c = connectionRef.get();
303303 // At startup, when we add the initial nodes, this will be null, which is ok
@@ -332,15 +332,15 @@
332332 if (host == null || host.getCassandraVersion() == null) {
333333 cassandraVersion = cluster.protocolVersion().minCassandraVersion();
334334 logger.warn("Cannot find Cassandra version for host {} to parse the schema, using {} based on protocol version in use. "
335- + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
335+ + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
336336 } else {
337337 cassandraVersion = host.getCassandraVersion();
338338 }
339339
340340 SchemaParser.forVersion(cassandraVersion)
341- .refresh(cluster.getCluster(),
342- targetType, targetKeyspace, targetName, targetSignature,
343- connection, cassandraVersion);
341+ .refresh(cluster.getCluster(),
342+ targetType, targetKeyspace, targetName, targetSignature,
343+ connection, cassandraVersion);
344344 }
345345
346346 void refreshNodeListAndTokenMap() {
@@ -392,8 +392,8 @@
392392 boolean isConnectedHost = c.address.equals(host.getSocketAddress());
393393 if (isConnectedHost || host.listenAddress != null) {
394394 DefaultResultSetFuture future = isConnectedHost
395- ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_LOCAL))
396- : new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS + " WHERE peer='" + host.listenAddress.getHostAddress() + '\''));
395+ ? new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_LOCAL))
396+ : new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS + " WHERE peer='" + host.listenAddress.getHostAddress() + '\''));
397397 c.write(future);
398398 return future.get().one();
399399 }
@@ -474,8 +474,8 @@
474474 String version = row.getString("release_version");
475475 // We don't know if it's a 'local' or a 'peers' row, and only 'peers' rows have the 'peer' field.
476476 InetAddress listenAddress = row.getColumnDefinitions().contains("peer")
477- ? row.getInet("peer")
478- : null;
477+ ? row.getInet("peer")
478+ : null;
479479
480480 host.setVersionAndListenAdress(version, listenAddress);
481481 }
@@ -664,7 +664,7 @@
664664
665665 if (current != null && current.address.equals(host.getSocketAddress())) {
666666 logger.debug("[Control connection] {} is down/removed and it was the control host, triggering reconnect",
667- current.address);
667+ current.address);
668668 if (!current.isClosed())
669669 current.closeAsync();
670670 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 +65 −67
@@ -15,8 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
2019 import com.google.common.base.Objects;
2120 import com.google.common.base.Predicate;
2221 import com.google.common.collect.ImmutableList;
@@ -24,7 +23,7 @@
2423 import com.google.common.collect.Sets;
2524 import io.netty.buffer.ByteBuf;
2625
27-import com.datastax.driver.core.exceptions.DriverInternalError;
26+import java.util.*;
2827
2928 /**
3029 * Data types supported by cassandra.
@@ -36,49 +35,49 @@
3635 */
3736 public enum Name {
3837
39- ASCII (1),
40- BIGINT (2),
41- BLOB (3),
42- BOOLEAN (4),
43- COUNTER (5),
44- DECIMAL (6),
45- DOUBLE (7),
46- FLOAT (8),
47- INET (16),
48- INT (9),
49- TEXT (10){
38+ ASCII(1),
39+ BIGINT(2),
40+ BLOB(3),
41+ BOOLEAN(4),
42+ COUNTER(5),
43+ DECIMAL(6),
44+ DOUBLE(7),
45+ FLOAT(8),
46+ INET(16),
47+ INT(9),
48+ TEXT(10) {
5049 @Override
5150 public boolean isCompatibleWith(Name that) {
5251 return this == that || that == VARCHAR;
5352 }
5453 },
55- TIMESTAMP (11),
56- UUID (12),
57- VARCHAR (13){
54+ TIMESTAMP(11),
55+ UUID(12),
56+ VARCHAR(13) {
5857 @Override
5958 public boolean isCompatibleWith(Name that) {
6059 return this == that || that == TEXT;
6160 }
6261 },
63- VARINT (14),
64- TIMEUUID (15),
65- LIST (32),
66- SET (34),
67- MAP (33),
68- CUSTOM (0),
69- UDT (48, ProtocolVersion.V3),
70- TUPLE (49, ProtocolVersion.V3),
71- SMALLINT (19, ProtocolVersion.V4),
72- TINYINT (20, ProtocolVersion.V4),
73- DATE (17, ProtocolVersion.V4),
74- TIME (18, ProtocolVersion.V4)
75- ;
62+ VARINT(14),
63+ TIMEUUID(15),
64+ LIST(32),
65+ SET(34),
66+ MAP(33),
67+ CUSTOM(0),
68+ UDT(48, ProtocolVersion.V3),
69+ TUPLE(49, ProtocolVersion.V3),
70+ SMALLINT(19, ProtocolVersion.V4),
71+ TINYINT(20, ProtocolVersion.V4),
72+ DATE(17, ProtocolVersion.V4),
73+ TIME(18, ProtocolVersion.V4);
7674
7775 final int protocolId;
7876
7977 final ProtocolVersion minProtocolVersion;
8078
8179 private static final Name[] nameToIds;
80+
8281 static {
8382 int maxCode = -1;
8483 for (Name name : Name.values())
@@ -126,6 +125,7 @@
126125 }
127126
128127 private static final Map<Name, DataType> primitiveTypeMap = new EnumMap<Name, DataType>(Name.class);
128+
129129 static {
130130 primitiveTypeMap.put(Name.ASCII, new DataType.NativeType(Name.ASCII));
131131 primitiveTypeMap.put(Name.BIGINT, new DataType.NativeType(Name.BIGINT));
@@ -163,8 +163,8 @@
163163 case CUSTOM:
164164 String className = CBUtil.readString(buffer);
165165 return DataTypeClassNameParser.isUserType(className) || DataTypeClassNameParser.isTupleType(className)
166- ? DataTypeClassNameParser.parseOne(className, protocolVersion, codecRegistry)
167- : custom(className);
166+ ? DataTypeClassNameParser.parseOne(className, protocolVersion, codecRegistry)
167+ : custom(className);
168168 case LIST:
169169 return list(decode(buffer, protocolVersion, codecRegistry));
170170 case SET:
@@ -380,7 +380,7 @@
380380 * Returns the type of lists of {@code elementType} elements.
381381 *
382382 * @param elementType the type of the list elements.
383- * @param frozen whether the list is frozen.
383+ * @param frozen whether the list is frozen.
384384 * @return the type of lists of {@code elementType} elements.
385385 */
386386 public static CollectionType list(DataType elementType, boolean frozen) {
@@ -389,7 +389,7 @@
389389
390390 /**
391391 * Returns the type of "not frozen" lists of {@code elementType} elements.
392- * <p>
392+ * <p/>
393393 * This is a shorthand for {@code list(elementType, false);}.
394394 *
395395 * @param elementType the type of the list elements.
@@ -401,7 +401,7 @@
401401
402402 /**
403403 * Returns the type of frozen lists of {@code elementType} elements.
404- * <p>
404+ * <p/>
405405 * This is a shorthand for {@code list(elementType, true);}.
406406 *
407407 * @param elementType the type of the list elements.
@@ -415,7 +415,7 @@
415415 * Returns the type of sets of {@code elementType} elements.
416416 *
417417 * @param elementType the type of the set elements.
418- * @param frozen whether the set is frozen.
418+ * @param frozen whether the set is frozen.
419419 * @return the type of sets of {@code elementType} elements.
420420 */
421421 public static CollectionType set(DataType elementType, boolean frozen) {
@@ -424,7 +424,7 @@
424424
425425 /**
426426 * Returns the type of "not frozen" sets of {@code elementType} elements.
427- * <p>
427+ * <p/>
428428 * This is a shorthand for {@code set(elementType, false);}.
429429 *
430430 * @param elementType the type of the set elements.
@@ -436,7 +436,7 @@
436436
437437 /**
438438 * Returns the type of frozen sets of {@code elementType} elements.
439- * <p>
439+ * <p/>
440440 * This is a shorthand for {@code set(elementType, true);}.
441441 *
442442 * @param elementType the type of the set elements.
@@ -449,9 +449,9 @@
449449 /**
450450 * Returns the type of maps of {@code keyType} to {@code valueType} elements.
451451 *
452- * @param keyType the type of the map keys.
452+ * @param keyType the type of the map keys.
453453 * @param valueType the type of the map values.
454- * @param frozen whether the map is frozen.
454+ * @param frozen whether the map is frozen.
455455 * @return the type of maps of {@code keyType} to {@code valueType} elements.
456456 */
457457 public static CollectionType map(DataType keyType, DataType valueType, boolean frozen) {
@@ -460,10 +460,10 @@
460460
461461 /**
462462 * Returns the type of "not frozen" maps of {@code keyType} to {@code valueType} elements.
463- * <p>
463+ * <p/>
464464 * This is a shorthand for {@code map(keyType, valueType, false);}.
465465 *
466- * @param keyType the type of the map keys.
466+ * @param keyType the type of the map keys.
467467 * @param valueType the type of the map values.
468468 * @return the type of "not frozen" maps of {@code keyType} to {@code valueType} elements.
469469 */
@@ -473,10 +473,10 @@
473473
474474 /**
475475 * Returns the type of frozen maps of {@code keyType} to {@code valueType} elements.
476- * <p>
476+ * <p/>
477477 * This is a shorthand for {@code map(keyType, valueType, true);}.
478478 *
479- * @param keyType the type of the map keys.
479+ * @param keyType the type of the map keys.
480480 * @param valueType the type of the map values.
481481 * @return the type of frozen maps of {@code keyType} to {@code valueType} elements.
482482 */
@@ -486,11 +486,11 @@
486486
487487 /**
488488 * Returns a Custom type.
489- * <p>
489+ * <p/>
490490 * A custom type is defined by the name of the class used on the Cassandra
491491 * side to implement it. Note that the support for custom type by the
492492 * driver is limited.
493- * <p>
493+ * <p/>
494494 * The use of custom types is rarely useful and is thus not encouraged.
495495 *
496496 * @param typeClassName the server-side fully qualified class name for the type.
@@ -513,7 +513,7 @@
513513
514514 /**
515515 * Returns whether this data type is frozen.
516- * <p>
516+ * <p/>
517517 * This applies to User Defined Types, tuples and nested collections. Frozen types are serialized as a single value in
518518 * Cassandra's storage engine, whereas non-frozen types are stored in a form that allows updates to individual subfields.
519519 *
@@ -533,17 +533,17 @@
533533
534534 /**
535535 * Returns the type arguments of this type.
536- * <p>
536+ * <p/>
537537 * Note that only the collection types (LIST, MAP, SET) have type
538538 * arguments. For the other types, this will return an empty list.
539- * <p>
539+ * <p/>
540540 * For the collection types:
541541 * <ul>
542- * <li>For lists and sets, this method returns one argument, the type of
543- * the elements.</li>
544- * <li>For maps, this method returns two arguments, the first one is the
545- * type of the map keys, the second one is the type of the map
546- * values.</li>
542+ * <li>For lists and sets, this method returns one argument, the type of
543+ * the elements.</li>
544+ * <li>For maps, this method returns two arguments, the first one is the
545+ * type of the map keys, the second one is the type of the map
546+ * values.</li>
547547 * </ul>
548548 *
549549 * @return an immutable list containing the type arguments of this type.
@@ -587,7 +587,7 @@
587587 * Returns a String representation of this data type
588588 * suitable for inclusion as a parameter type
589589 * in a function or aggregate signature.
590- * <p>
590+ * <p/>
591591 * In such places, the String representation might vary
592592 * from the canonical one as returned by {@link #toString()};
593593 * e.g. the {@code frozen} keyword is not accepted.
@@ -614,16 +614,16 @@
614614 @Override
615615 public final int hashCode() {
616616 return (name == Name.TEXT)
617- ? Name.VARCHAR.hashCode()
618- : name.hashCode();
617+ ? Name.VARCHAR.hashCode()
618+ : name.hashCode();
619619 }
620620
621621 @Override
622622 public final boolean equals(Object o) {
623- if(!(o instanceof DataType.NativeType))
623+ if (!(o instanceof DataType.NativeType))
624624 return false;
625625
626- NativeType that = (DataType.NativeType)o;
626+ NativeType that = (DataType.NativeType) o;
627627 return this.name.isCompatibleWith(that.name);
628628 }
629629
@@ -661,10 +661,10 @@
661661
662662 @Override
663663 public final boolean equals(Object o) {
664- if(!(o instanceof DataType.CollectionType))
664+ if (!(o instanceof DataType.CollectionType))
665665 return false;
666666
667- DataType.CollectionType d = (DataType.CollectionType)o;
667+ DataType.CollectionType d = (DataType.CollectionType) o;
668668 return name == d.name && typeArguments.equals(d.typeArguments);
669669 }
670670
@@ -673,8 +673,7 @@
673673 if (name == Name.MAP) {
674674 String template = frozen ? "frozen<%s<%s, %s>>" : "%s<%s, %s>";
675675 return String.format(template, name, typeArguments.get(0), typeArguments.get(1));
676- }
677- else {
676+ } else {
678677 String template = frozen ? "frozen<%s<%s>>" : "%s<%s>";
679678 return String.format(template, name, typeArguments.get(0));
680679 }
@@ -685,8 +684,7 @@
685684 if (name == Name.MAP) {
686685 String template = "%s<%s, %s>";
687686 return String.format(template, name, typeArguments.get(0), typeArguments.get(1));
688- }
689- else {
687+ } else {
690688 String template = "%s<%s>";
691689 return String.format(template, name, typeArguments.get(0));
692690 }
@@ -718,10 +716,10 @@
718716
719717 @Override
720718 public final boolean equals(Object o) {
721- if(!(o instanceof DataType.CustomType))
719+ if (!(o instanceof DataType.CustomType))
722720 return false;
723721
724- DataType.CustomType d = (DataType.CustomType)o;
722+ DataType.CustomType d = (DataType.CustomType) o;
725723 return name == d.name && Objects.equal(customClassName, d.customClassName);
726724 }
727725
modified driver-core/src/main/java/com/datastax/driver/core/DataTypeClassNameParser.java +29 −30
@@ -15,14 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.datastax.driver.core.utils.Bytes;
2020 import com.google.common.collect.ImmutableMap;
2121 import org.slf4j.Logger;
2222 import org.slf4j.LoggerFactory;
2323
24-import com.datastax.driver.core.exceptions.DriverInternalError;
25-import com.datastax.driver.core.utils.Bytes;
24+import java.util.*;
2625
2726 /*
2827 * Parse data types from schema tables, for Cassandra 3.0 and above.
@@ -51,27 +50,27 @@
5150 private static final String TUPLE_TYPE = "org.apache.cassandra.db.marshal.TupleType";
5251
5352 private static ImmutableMap<String, DataType> cassTypeToDataType =
54- new ImmutableMap.Builder<String, DataType>()
55- .put("org.apache.cassandra.db.marshal.AsciiType", DataType.ascii())
56- .put("org.apache.cassandra.db.marshal.LongType", DataType.bigint())
57- .put("org.apache.cassandra.db.marshal.BytesType", DataType.blob())
58- .put("org.apache.cassandra.db.marshal.BooleanType", DataType.cboolean())
59- .put("org.apache.cassandra.db.marshal.CounterColumnType", DataType.counter())
60- .put("org.apache.cassandra.db.marshal.DecimalType", DataType.decimal())
61- .put("org.apache.cassandra.db.marshal.DoubleType", DataType.cdouble())
62- .put("org.apache.cassandra.db.marshal.FloatType", DataType.cfloat())
63- .put("org.apache.cassandra.db.marshal.InetAddressType", DataType.inet())
64- .put("org.apache.cassandra.db.marshal.Int32Type", DataType.cint())
65- .put("org.apache.cassandra.db.marshal.UTF8Type", DataType.text())
66- .put("org.apache.cassandra.db.marshal.TimestampType", DataType.timestamp())
67- .put("org.apache.cassandra.db.marshal.SimpleDateType", DataType.date())
68- .put("org.apache.cassandra.db.marshal.TimeType", DataType.time())
69- .put("org.apache.cassandra.db.marshal.UUIDType", DataType.uuid())
70- .put("org.apache.cassandra.db.marshal.IntegerType", DataType.varint())
71- .put("org.apache.cassandra.db.marshal.TimeUUIDType", DataType.timeuuid())
72- .put("org.apache.cassandra.db.marshal.ByteType", DataType.tinyint())
73- .put("org.apache.cassandra.db.marshal.ShortType", DataType.smallint())
74- .build();
53+ new ImmutableMap.Builder<String, DataType>()
54+ .put("org.apache.cassandra.db.marshal.AsciiType", DataType.ascii())
55+ .put("org.apache.cassandra.db.marshal.LongType", DataType.bigint())
56+ .put("org.apache.cassandra.db.marshal.BytesType", DataType.blob())
57+ .put("org.apache.cassandra.db.marshal.BooleanType", DataType.cboolean())
58+ .put("org.apache.cassandra.db.marshal.CounterColumnType", DataType.counter())
59+ .put("org.apache.cassandra.db.marshal.DecimalType", DataType.decimal())
60+ .put("org.apache.cassandra.db.marshal.DoubleType", DataType.cdouble())
61+ .put("org.apache.cassandra.db.marshal.FloatType", DataType.cfloat())
62+ .put("org.apache.cassandra.db.marshal.InetAddressType", DataType.inet())
63+ .put("org.apache.cassandra.db.marshal.Int32Type", DataType.cint())
64+ .put("org.apache.cassandra.db.marshal.UTF8Type", DataType.text())
65+ .put("org.apache.cassandra.db.marshal.TimestampType", DataType.timestamp())
66+ .put("org.apache.cassandra.db.marshal.SimpleDateType", DataType.date())
67+ .put("org.apache.cassandra.db.marshal.TimeType", DataType.time())
68+ .put("org.apache.cassandra.db.marshal.UUIDType", DataType.uuid())
69+ .put("org.apache.cassandra.db.marshal.IntegerType", DataType.varint())
70+ .put("org.apache.cassandra.db.marshal.TimeUUIDType", DataType.timeuuid())
71+ .put("org.apache.cassandra.db.marshal.ByteType", DataType.tinyint())
72+ .put("org.apache.cassandra.db.marshal.ShortType", DataType.smallint())
73+ .build();
7574
7675 static DataType parseOne(String className, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
7776 boolean frozen = false;
@@ -99,7 +98,7 @@
9998
10099 if (frozen)
101100 logger.warn("Got o.a.c.db.marshal.FrozenType for something else than a collection, "
102- + "this driver version might be too old for your version of Cassandra");
101+ + "this driver version might be too old for your version of Cassandra");
103102
104103 if (isUserType(next)) {
105104 ++parser.idx; // skipping '('
@@ -200,9 +199,9 @@
200199
201200 private ParseResult(DataType type, boolean reversed) {
202201 this(false,
203- Collections.<DataType>singletonList(type),
204- Collections.<Boolean>singletonList(reversed),
205- Collections.<String, DataType>emptyMap());
202+ Collections.<DataType>singletonList(type),
203+ Collections.<Boolean>singletonList(reversed),
204+ Collections.<String, DataType>emptyMap());
206205 }
207206
208207 private ParseResult(boolean isComposite, List<DataType> types, List<Boolean> reversed, Map<String, DataType> collections) {
@@ -399,7 +398,7 @@
399398
400399 @Override
401400 public String toString() {
402- return str.substring(0, idx) + "[" + (idx == str.length() ? "" : str.charAt(idx)) + "]" + str.substring(idx+1);
401+ return str.substring(0, idx) + "[" + (idx == str.length() ? "" : str.charAt(idx)) + "]" + str.substring(idx + 1);
403402 }
404403 }
405404 }
modified driver-core/src/main/java/com/datastax/driver/core/DataTypeCqlNameParser.java +42 −45
@@ -15,19 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.datastax.driver.core.exceptions.UnresolvedUserTypeException;
20+import com.google.common.collect.ImmutableMap;
21+
1822 import java.util.ArrayList;
1923 import java.util.List;
2024 import java.util.Map;
2125
22-import com.google.common.collect.ImmutableMap;
23-
24-import com.datastax.driver.core.exceptions.DriverInternalError;
25-import com.datastax.driver.core.exceptions.UnresolvedUserTypeException;
26-
2726 import static com.datastax.driver.core.DataType.*;
28-import static com.datastax.driver.core.ParseUtils.isBlank;
29-import static com.datastax.driver.core.ParseUtils.isIdentifierChar;
30-import static com.datastax.driver.core.ParseUtils.skipSpaces;
27+import static com.datastax.driver.core.ParseUtils.*;
3128
3229 /*
3330 * Parse data types from schema tables, for Cassandra 3.0 and above.
@@ -40,46 +37,46 @@
4037 class DataTypeCqlNameParser {
4138
4239 private static final String FROZEN = "frozen";
43- private static final String LIST = "list";
44- private static final String SET = "set";
45- private static final String MAP = "map";
46- private static final String TUPLE = "tuple";
47- private static final String EMPTY = "empty";
40+ private static final String LIST = "list";
41+ private static final String SET = "set";
42+ private static final String MAP = "map";
43+ private static final String TUPLE = "tuple";
44+ private static final String EMPTY = "empty";
4845
4946 private static final ImmutableMap<String, DataType> NATIVE_TYPES_MAP =
50- new ImmutableMap.Builder<String, DataType>()
51- .put("ascii", ascii())
52- .put("bigint", bigint())
53- .put("blob", blob())
54- .put("boolean", cboolean())
55- .put("counter", counter())
56- .put("decimal", decimal())
57- .put("double", cdouble())
58- .put("float", cfloat())
59- .put("inet", inet())
60- .put("int", cint())
61- .put("text", text())
62- .put("varchar", varchar())
63- .put("timestamp", timestamp())
64- .put("date", date())
65- .put("time", time())
66- .put("uuid", uuid())
67- .put("varint", varint())
68- .put("timeuuid", timeuuid())
69- .put("tinyint", tinyint())
70- .put("smallint", smallint())
71- .build();
47+ new ImmutableMap.Builder<String, DataType>()
48+ .put("ascii", ascii())
49+ .put("bigint", bigint())
50+ .put("blob", blob())
51+ .put("boolean", cboolean())
52+ .put("counter", counter())
53+ .put("decimal", decimal())
54+ .put("double", cdouble())
55+ .put("float", cfloat())
56+ .put("inet", inet())
57+ .put("int", cint())
58+ .put("text", text())
59+ .put("varchar", varchar())
60+ .put("timestamp", timestamp())
61+ .put("date", date())
62+ .put("time", time())
63+ .put("uuid", uuid())
64+ .put("varint", varint())
65+ .put("timeuuid", timeuuid())
66+ .put("tinyint", tinyint())
67+ .put("smallint", smallint())
68+ .build();
7269
7370 /**
7471 * @param currentUserTypes if this method gets called as part of a refresh that spans multiple user types, this contains the ones
7572 * that have already been refreshed. If the type we are parsing references a user type, we want to pick its
7673 * definition from this map in priority.
77- * @param oldUserTypes this contains all the keyspace's user types as they were before the refresh started. If we can't find a
78- * definition in {@code currentUserTypes}, we'll check this map as a fallback.
74+ * @param oldUserTypes this contains all the keyspace's user types as they were before the refresh started. If we can't find a
75+ * definition in {@code currentUserTypes}, we'll check this map as a fallback.
7976 */
8077 static DataType parse(String toParse, Cluster cluster, String currentKeyspaceName, Map<String, UserType> currentUserTypes, Map<String, UserType> oldUserTypes, boolean frozen, boolean shallowUserTypes) {
8178
82- if(toParse.startsWith("'"))
79+ if (toParse.startsWith("'"))
8380 return custom(toParse.substring(1, toParse.length() - 1));
8481
8582 Parser parser = new Parser(toParse, 0);
@@ -132,7 +129,7 @@
132129
133130 // return a custom type for the special empty type
134131 // so that it gets detected later on, see TableMetadata
135- if(type.equalsIgnoreCase(EMPTY))
132+ if (type.equalsIgnoreCase(EMPTY))
136133 return custom(type);
137134
138135 // We need to remove escaped double quotes within the type name as it is stored unescaped.
@@ -204,16 +201,16 @@
204201 private String readNextIdentifier() {
205202 int startIdx = idx;
206203 // if first character is a quote, this is a quoted identifier.
207- if(str.charAt(startIdx) == '"') {
204+ if (str.charAt(startIdx) == '"') {
208205 ++idx;
209206 // read until closing quote.
210- while(!isEOS()) {
207+ while (!isEOS()) {
211208 boolean atQuote = str.charAt(idx) == '"';
212209 ++idx;
213210 if (atQuote) {
214211 // if the next character is also a quote, this is an escaped
215212 // quote, continue reading, otherwise stop.
216- if(!isEOS() && str.charAt(idx) == '"')
213+ if (!isEOS() && str.charAt(idx) == '"')
217214 ++idx;
218215 else
219216 break;
@@ -251,7 +248,7 @@
251248 // Only parse for '<' and '>' characters if not within a quoted identifier.
252249 // Note we don't need to handle escaped quotes ("") in type names here, because they just cause inQuotes to flip
253250 // to false and immediately back to true
254- if(!inQuotes) {
251+ if (!inQuotes) {
255252 if (str.charAt(idx) == '"') {
256253 inQuotes = true;
257254 } else if (str.charAt(idx) == '<') {
@@ -259,7 +256,7 @@
259256 } else if (str.charAt(idx) == '>') {
260257 open--;
261258 }
262- } else if(str.charAt(idx) == '"') {
259+ } else if (str.charAt(idx) == '"') {
263260 inQuotes = false;
264261 }
265262 }
@@ -292,7 +289,7 @@
292289
293290 @Override
294291 public String toString() {
295- return str.substring(0, idx) + "[" + (idx == str.length() ? "" : str.charAt(idx)) + "]" + str.substring(idx+1);
292+ return str.substring(0, idx) + "[" + (idx == str.length() ? "" : str.charAt(idx)) + "]" + str.substring(idx + 1);
296293 }
297294 }
298295 }
modified driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +5 −6
@@ -15,14 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.policies.RetryPolicy;
19+import com.google.common.collect.ImmutableMap;
20+
1821 import java.nio.ByteBuffer;
1922 import java.util.List;
2023 import java.util.Map;
2124
22-import com.google.common.collect.ImmutableMap;
23-
24-import com.datastax.driver.core.policies.RetryPolicy;
25-
2625 import static com.datastax.driver.core.ProtocolVersion.V4;
2726
2827 public class DefaultPreparedStatement implements PreparedStatement {
@@ -63,8 +62,8 @@
6362 }
6463
6564 int[] pkIndices = (protocolVersion.compareTo(V4) >= 0)
66- ? msg.metadata.pkIndices
67- : computePkIndices(cluster.getMetadata(), defs);
65+ ? msg.metadata.pkIndices
66+ : computePkIndices(cluster.getMetadata(), defs);
6867
6968 PreparedId prepId = new PreparedId(msg.statementId, defs, msg.resultMetadata.columns, pkIndices, protocolVersion);
7069
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +36 −37
@@ -15,16 +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-
18+import com.datastax.driver.core.exceptions.*;
2219 import com.google.common.util.concurrent.AbstractFuture;
2320 import com.google.common.util.concurrent.Uninterruptibles;
2421 import org.slf4j.Logger;
2522 import org.slf4j.LoggerFactory;
2623
27-import com.datastax.driver.core.exceptions.*;
24+import java.util.concurrent.ExecutionException;
25+import java.util.concurrent.TimeUnit;
26+import java.util.concurrent.TimeoutException;
2827
2928 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
3029
@@ -61,11 +60,11 @@
6160 try {
6261 switch (response.type) {
6362 case RESULT:
64- Responses.Result rm = (Responses.Result)response;
63+ Responses.Result rm = (Responses.Result) response;
6564 switch (rm.kind) {
6665 case SET_KEYSPACE:
6766 // propagate the keyspace change to other connections
68- session.poolsState.setKeyspace(((Responses.Result.SetKeyspace)rm).keyspace);
67+ session.poolsState.setKeyspace(((Responses.Result.SetKeyspace) rm).keyspace);
6968 set(ArrayBackedResultSet.fromMessage(rm, session, protocolVersion, info, statement));
7069 break;
7170 case SCHEMA_CHANGE:
@@ -74,7 +73,7 @@
7473 if (!cluster.configuration.getQueryOptions().isMetadataEnabled()) {
7574 cluster.waitForSchemaAgreementAndSignal(connection, this, rs);
7675 } else {
77- Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm;
76+ Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange) rm;
7877 switch (scc.change) {
7978 case CREATED:
8079 case UPDATED:
@@ -100,7 +99,7 @@
10099 KeyspaceMetadata keyspace = session.cluster.manager.metadata.keyspaces.get(scc.targetKeyspace);
101100 if (keyspace == null) {
102101 logger.warn("Received a DROPPED notification for {} {}.{}, but this keyspace is unknown in our metadata",
103- scc.targetType, scc.targetKeyspace, scc.targetName);
102+ scc.targetType, scc.targetKeyspace, scc.targetName);
104103 } else {
105104 switch (scc.targetType) {
106105 case TABLE:
@@ -177,7 +176,7 @@
177176 }
178177 break;
179178 case ERROR:
180- setException(((Responses.Error)response).asException(connection.address));
179+ setException(((Responses.Error) response).asException(connection.address));
181180 break;
182181 default:
183182 // This mean we have probably have a bad node, so defunct the connection
@@ -220,23 +219,23 @@
220219
221220 /**
222221 * Waits for the query to return and return its result.
223- *
222+ * <p/>
224223 * This method is usually more convenient than {@link #get} because it:
225224 * <ul>
226- * <li>Waits for the result uninterruptibly, and so doesn't throw
227- * {@link InterruptedException}.</li>
228- * <li>Returns meaningful exceptions, instead of having to deal
229- * with ExecutionException.</li>
225+ * <li>Waits for the result uninterruptibly, and so doesn't throw
226+ * {@link InterruptedException}.</li>
227+ * <li>Returns meaningful exceptions, instead of having to deal
228+ * with ExecutionException.</li>
230229 * </ul>
231230 * As such, it is the preferred way to get the future result.
232231 *
233232 * @throws NoHostAvailableException if no host in the cluster can be
234- * contacted successfully to execute this query.
235- * @throws QueryExecutionException if the query triggered an execution
236- * exception, that is an exception thrown by Cassandra when it cannot execute
237- * the query with the requested consistency level successfully.
233+ * contacted successfully to execute this query.
234+ * @throws QueryExecutionException if the query triggered an execution
235+ * exception, that is an exception thrown by Cassandra when it cannot execute
236+ * the query with the requested consistency level successfully.
238237 * @throws QueryValidationException if the query is invalid (syntax error,
239- * unauthorized or any other validation problem).
238+ * unauthorized or any other validation problem).
240239 */
241240 public ResultSet getUninterruptibly() {
242241 try {
@@ -249,26 +248,26 @@
249248 /**
250249 * Waits for the provided time for the query to return and return its
251250 * result if available.
252- *
251+ * <p/>
253252 * This method is usually more convenient than {@link #get} because it:
254253 * <ul>
255- * <li>Waits for the result uninterruptibly, and so doesn't throw
256- * {@link InterruptedException}.</li>
257- * <li>Returns meaningful exceptions, instead of having to deal
258- * with ExecutionException.</li>
254+ * <li>Waits for the result uninterruptibly, and so doesn't throw
255+ * {@link InterruptedException}.</li>
256+ * <li>Returns meaningful exceptions, instead of having to deal
257+ * with ExecutionException.</li>
259258 * </ul>
260259 * As such, it is the preferred way to get the future result.
261260 *
262261 * @throws NoHostAvailableException if no host in the cluster can be
263- * contacted successfully to execute this query.
264- * @throws QueryExecutionException if the query triggered an execution
265- * exception, that is an exception thrown by Cassandra when it cannot execute
266- * the query with the requested consistency level successfully.
262+ * contacted successfully to execute this query.
263+ * @throws QueryExecutionException if the query triggered an execution
264+ * exception, that is an exception thrown by Cassandra when it cannot execute
265+ * the query with the requested consistency level successfully.
267266 * @throws QueryValidationException if the query if invalid (syntax error,
268- * unauthorized or any other validation problem).
269- * @throws TimeoutException if the wait timed out (Note that this is
270- * different from a Cassandra timeout, which is a {@code
271- * QueryExecutionException}).
267+ * unauthorized or any other validation problem).
268+ * @throws TimeoutException if the wait timed out (Note that this is
269+ * different from a Cassandra timeout, which is a {@code
270+ * QueryExecutionException}).
272271 */
273272 public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException {
274273 try {
@@ -281,12 +280,12 @@
281280 /**
282281 * Attempts to cancel the execution of the request corresponding to this
283282 * future. This attempt will fail if the request has already returned.
284- * <p>
283+ * <p/>
285284 * Please note that this only cancels the request driver side, but nothing
286285 * is done to interrupt the execution of the request Cassandra side (and that even
287286 * if {@code mayInterruptIfRunning} is true) since Cassandra does not
288287 * support such interruption.
289- * <p>
288+ * <p/>
290289 * This method can be used to ensure no more work is performed driver side
291290 * (which, while it doesn't include stopping a request already submitted
292291 * to a Cassandra node, may include not retrying another Cassandra host on
@@ -306,7 +305,7 @@
306305 * <pre>
307306 *
308307 * @param mayInterruptIfRunning the value of this parameter is currently
309- * ignored.
308+ * ignored.
310309 * @return {@code false} if the future could not be cancelled (it has already
311310 * completed normally); {@code true} otherwise.
312311 */
@@ -315,7 +314,7 @@
315314 if (!super.cancel(mayInterruptIfRunning))
316315 return false;
317316
318- if(handler != null) {
317+ if (handler != null) {
319318 handler.cancel();
320319 }
321320 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/DirectedGraph.java +8 −5
@@ -15,15 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
2019 import com.google.common.base.Preconditions;
2120 import com.google.common.collect.HashMultimap;
2221 import com.google.common.collect.Lists;
2322 import com.google.common.collect.Maps;
2423 import com.google.common.collect.Multimap;
2524
26-import com.datastax.driver.core.exceptions.DriverInternalError;
25+import java.util.*;
2726
2827 /**
2928 * A basic directed graph implementation to perform topological sorts.
@@ -48,14 +47,18 @@
4847 this(Arrays.asList(vertices));
4948 }
5049
51- /** this assumes that {@code from} and {@code to} were part of the vertices passed to the constructor */
50+ /**
51+ * this assumes that {@code from} and {@code to} were part of the vertices passed to the constructor
52+ */
5253 void addEdge(V from, V to) {
5354 Preconditions.checkArgument(vertices.containsKey(from) && vertices.containsKey(to));
5455 adjacencyList.put(from, to);
5556 vertices.put(to, vertices.get(to) + 1);
5657 }
5758
58- /** one-time use only, calling this multiple times on the same graph won't work */
59+ /**
60+ * one-time use only, calling this multiple times on the same graph won't work
61+ */
5962 List<V> topologicalSort() {
6063 Preconditions.checkState(!wasSorted);
6164 wasSorted = true;
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 +19 −18
@@ -15,42 +15,43 @@
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),
40- READ_FAILURE (0x1300),
37+ TRUNCATE_ERROR(0x1003),
38+ WRITE_TIMEOUT(0x1100),
39+ READ_TIMEOUT(0x1200),
40+ READ_FAILURE(0x1300),
4141 FUNCTION_FAILURE(0x1400),
42- WRITE_FAILURE (0x1500),
42+ WRITE_FAILURE(0x1500),
4343
4444 // 2xx: problem validating the request
45- SYNTAX_ERROR (0x2000),
46- UNAUTHORIZED (0x2100),
47- INVALID (0x2200),
48- CONFIG_ERROR (0x2300),
49- ALREADY_EXISTS (0x2400),
50- UNPREPARED (0x2500);
45+ SYNTAX_ERROR(0x2000),
46+ UNAUTHORIZED(0x2100),
47+ INVALID(0x2200),
48+ CONFIG_ERROR(0x2300),
49+ ALREADY_EXISTS(0x2400),
50+ UNPREPARED(0x2500);
5151
5252 public final int value;
5353 private static final Map<Integer, ExceptionCode> valueToCode = new HashMap<Integer, ExceptionCode>(ExceptionCode.values().length);
54+
5455 static {
5556 for (ExceptionCode code : ExceptionCode.values())
5657 valueToCode.put(code.value, code);
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +18 −21
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.Bytes;
19+import com.google.common.util.concurrent.Futures;
20+import com.google.common.util.concurrent.ListenableFuture;
21+
1822 import java.nio.ByteBuffer;
1923 import java.util.Collections;
2024 import java.util.List;
2125 import java.util.Map;
2226
23-import com.google.common.util.concurrent.Futures;
24-import com.google.common.util.concurrent.ListenableFuture;
25-
26-import com.datastax.driver.core.utils.Bytes;
27-
2827 /**
2928 * Basic information on the execution of a query.
3029 */
@@ -79,7 +78,7 @@
7978
8079 /**
8180 * The list of tried hosts for this query.
82- * <p>
81+ * <p/>
8382 * In general, this will be a singleton list with the host that coordinated
8483 * that query. However:
8584 * <ul>
@@ -91,7 +90,7 @@
9190 * <li>if {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}
9291 * are enabled, other hosts might have been tried speculatively as well.</li>
9392 * </ul>
94- * <p>
93+ * <p/>
9594 * If you are only interested in fetching the final (and often only) node
9695 * coordinating the query, {@link #getQueriedHost} provides a shortcut to
9796 * fetch the last element of the list returned by this method.
@@ -104,7 +103,7 @@
104103
105104 /**
106105 * Return the Cassandra host that coordinated this query.
107- * <p>
106+ * <p/>
108107 * This is a shortcut for {@code getTriedHosts().get(getTriedHosts().size())}.
109108 *
110109 * @return return the Cassandra host that coordinated this query.
@@ -118,7 +117,7 @@
118117 * due to the {@link com.datastax.driver.core.policies.RetryPolicy}, this
119118 * return the biggest consistency level that has been actually achieved by
120119 * the query.
121- * <p>
120+ * <p/>
122121 * Note that the default {@code RetryPolicy}
123122 * ({@link com.datastax.driver.core.policies.DefaultRetryPolicy})
124123 * will never allow a query to be successful without achieving the
@@ -138,7 +137,7 @@
138137
139138 /**
140139 * Return the query trace if tracing was enabled on this query.
141- * <p>
140+ * <p/>
142141 * Note that accessing the fields of the the returned object will trigger a
143142 * <b>blocking</b> background query.
144143 *
@@ -151,7 +150,7 @@
151150
152151 /**
153152 * Placeholder for async query trace retrieval (not implemented yet).
154- * <p>
153+ * <p/>
155154 * Async query trace retrieval will be implemented in a future version. This method
156155 * is added now to avoid breaking binary compatibility later.
157156 * The current implementation merely wraps the result of {@link #getQueryTrace()} in
@@ -166,12 +165,11 @@
166165
167166 /**
168167 * The paging state of the query.
169- *
168+ * <p/>
170169 * This object represents the next page to be fetched if this query is
171170 * multi page. It can be saved and reused later on the same statement.
172171 *
173172 * @return the paging state or null if there is no next page.
174- *
175173 * @see Statement#setPagingState(PagingState)
176174 */
177175 public PagingState getPagingState() {
@@ -182,12 +180,11 @@
182180
183181 /**
184182 * Returns the "raw" paging state of the query.
185- *
183+ * <p/>
186184 * Contrary to {@link #getPagingState()}, there will be no validation when
187185 * this is later reinjected into a statement.
188186 *
189187 * @return the paging state or null if there is no next page.
190- *
191188 * @see Statement#setPagingStateUnsafe(byte[])
192189 */
193190 public byte[] getPagingStateUnsafe() {
@@ -198,15 +195,15 @@
198195
199196 /**
200197 * Whether the cluster had reached schema agreement after the execution of this query.
201- *
198+ * <p/>
202199 * After a successful schema-altering query (ex: creating a table), the driver
203200 * will check if the cluster's nodes agree on the new schema version. If not,
204201 * it will keep retrying for a given delay (configurable via
205202 * {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}).
206- * <p>
203+ * <p/>
207204 * If this method returns {@code false}, clients can call {@link Metadata#checkSchemaAgreement()}
208205 * later to perform the check manually.
209- * <p>
206+ * <p/>
210207 * Note that the schema agreement check is only performed for schema-altering queries
211208 * For other query types, this method will always return {@code true}.
212209 *
@@ -223,7 +220,7 @@
223220
224221 /**
225222 * Returns the server-side warnings for this query.
226- * <p>
223+ * <p/>
227224 * This feature is only available with {@link ProtocolVersion#V4} or above; with lower
228225 * versions, the returned list will always be empty.
229226 *
@@ -238,11 +235,11 @@
238235 * Return the incoming payload, that is, the payload that the server
239236 * sent back with its response, if any,
240237 * or {@code null}, if the server did not include any custom payload.
241- * <p>
238+ * <p/>
242239 * This method returns a read-only view of the original map, but
243240 * its values remain inherently mutable.
244241 * Callers should take care not to modify the returned map in any way.
245- * <p>
242+ * <p/>
246243 * This feature is only available with {@link ProtocolVersion#V4} or above; with lower
247244 * versions, this method will always return {@code null}.
248245 *
modified driver-core/src/main/java/com/datastax/driver/core/Frame.java +13 −14
@@ -15,31 +15,30 @@
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 /**
2928 * A frame for the CQL binary protocol.
30- * <p>
29+ * <p/>
3130 * Each frame contains a fixed size header (8 bytes for V1 and V2, 9 bytes for V3 and V4)
3231 * followed by a variable size body. The content of the body depends
3332 * on the header opcode value (the body can in particular be empty for some
3433 * opcode values).
35- * <p>
34+ * <p/>
3635 * The protocol distinguishes 2 types of frames: requests and responses. Requests
3736 * are those frames sent by the clients to the server, response are the ones sent
3837 * by the server. Note however that the protocol supports server pushes (events)
3938 * so responses does not necessarily come right after a client request.
40- * <p>
39+ * <p/>
4140 * Frames for protocol versions 1+2 are defined as:
42- *
41+ * <p/>
4342 * <pre>
4443 * 0 8 16 24 32
4544 * +---------+---------+---------+---------+
@@ -52,10 +51,10 @@
5251 * . .
5352 * . .
5453 * +---------------------------------------- *
55- *</pre>
56- *
54+ * </pre>
55+ * <p/>
5756 * Frames for protocol versions 3+4 are defined as:
58- *
57+ * <p/>
5958 * <pre>
6059 * 0 8 16 24 32 40
6160 * +---------+---------+---------+---------+---------+
@@ -92,7 +91,7 @@
9291 // version first byte is the "direction" of the frame (request or response)
9392 ProtocolVersion version = ProtocolVersion.fromInt(versionBytes & 0x7F);
9493 int hdrLen = Header.lengthFor(version);
95- assert fullFrame.readableBytes() >= (hdrLen-1) : String.format("Frame too short (%d bytes)", fullFrame.readableBytes());
94+ assert fullFrame.readableBytes() >= (hdrLen - 1) : String.format("Frame too short (%d bytes)", fullFrame.readableBytes());
9695
9796 int flags = fullFrame.readByte();
9897 int streamId = readStreamid(fullFrame, version);
@@ -142,6 +141,7 @@
142141
143142 /**
144143 * Return the expected frame header length in bytes according to the protocol version in use.
144+ *
145145 * @param version the protocol version in use
146146 * @return the expected frame header length in bytes
147147 */
@@ -158,8 +158,7 @@
158158 }
159159 }
160160
161- public static enum Flag
162- {
161+ public static enum Flag {
163162 // The order of that enum matters!!
164163 COMPRESSED,
165164 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/FunctionMetadata.java +38 −39
@@ -15,16 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collections;
19-import java.util.Iterator;
20-import java.util.List;
21-import java.util.Map;
22-
2318 import com.google.common.base.Objects;
2419 import com.google.common.collect.ImmutableMap;
2520 import org.slf4j.Logger;
2621 import org.slf4j.LoggerFactory;
2722
23+import java.util.Collections;
24+import java.util.Iterator;
25+import java.util.List;
26+import java.util.Map;
27+
2828 /**
2929 * Describes a CQL function (created with {@code CREATE FUNCTION...}).
3030 */
@@ -94,15 +94,15 @@
9494 if (argumentNames.size() != argumentTypes.size()) {
9595 String fullName = Metadata.fullFunctionName(simpleName, arguments.values());
9696 logger.error(String.format("Error parsing definition of function %1$s.%2$s: the number of argument names and types don't match."
97- + "Cluster.getMetadata().getKeyspace(\"%1$s\").getFunction(\"%2$s\") will be missing.",
98- ksm.getName(), fullName));
97+ + "Cluster.getMetadata().getKeyspace(\"%1$s\").getFunction(\"%2$s\") will be missing.",
98+ ksm.getName(), fullName));
9999 return null;
100100 }
101101 String body = row.getString("body");
102102 boolean calledOnNullInput = row.getBool("called_on_null_input");
103103 String language = row.getString("language");
104104 DataType returnType;
105- if(version.getMajor() >= 3.0) {
105+ if (version.getMajor() >= 3.0) {
106106 returnType = DataTypeCqlNameParser.parse(row.getString("return_type"), cluster, ksm.getName(), ksm.userTypes, null, false, false);
107107 } else {
108108 returnType = DataTypeClassNameParser.parseOne(row.getString("return_type"), protocolVersion, codecRegistry);
@@ -132,7 +132,7 @@
132132
133133 /**
134134 * Returns a CQL query representing this function in human readable form.
135- * <p>
135+ * <p/>
136136 * This method is equivalent to {@link #asCQLQuery} but the output is formatted.
137137 *
138138 * @return the CQL query representing this function.
@@ -143,7 +143,7 @@
143143
144144 /**
145145 * Returns a CQL query representing this function.
146- *
146+ * <p/>
147147 * This method returns a single 'CREATE FUNCTION' query corresponding to
148148 * this function definition.
149149 *
@@ -163,10 +163,10 @@
163163 StringBuilder sb = new StringBuilder("CREATE FUNCTION ");
164164
165165 sb
166- .append(Metadata.escapeId(keyspace.getName()))
167- .append('.')
168- .append(Metadata.escapeId(simpleName))
169- .append('(');
166+ .append(Metadata.escapeId(keyspace.getName()))
167+ .append('.')
168+ .append(Metadata.escapeId(simpleName))
169+ .append('(');
170170
171171 boolean first = true;
172172 for (Map.Entry<String, DataType> entry : arguments.entrySet()) {
@@ -178,28 +178,28 @@
178178 String name = entry.getKey();
179179 DataType type = entry.getValue();
180180 sb
181- .append(TableMetadata.spaces(4, formatted))
182- .append(Metadata.escapeId(name))
183- .append(' ')
184- .append(type.asFunctionParameterString());
181+ .append(TableMetadata.spaces(4, formatted))
182+ .append(Metadata.escapeId(name))
183+ .append(' ')
184+ .append(type.asFunctionParameterString());
185185 }
186186 sb.append(')');
187187
188188 TableMetadata.spaceOrNewLine(sb, formatted)
189- .append(calledOnNullInput ? "CALLED ON NULL INPUT" : "RETURNS NULL ON NULL INPUT");
189+ .append(calledOnNullInput ? "CALLED ON NULL INPUT" : "RETURNS NULL ON NULL INPUT");
190190
191191 TableMetadata.spaceOrNewLine(sb, formatted)
192- .append("RETURNS ")
193- .append(returnType);
192+ .append("RETURNS ")
193+ .append(returnType);
194194
195195 TableMetadata.spaceOrNewLine(sb, formatted)
196- .append("LANGUAGE ")
197- .append(language);
196+ .append("LANGUAGE ")
197+ .append(language);
198198
199199 TableMetadata.spaceOrNewLine(sb, formatted)
200- .append("AS '")
201- .append(body)
202- .append("';");
200+ .append("AS '")
201+ .append(body)
202+ .append("';");
203203
204204 return sb.toString();
205205 }
@@ -215,10 +215,10 @@
215215
216216 /**
217217 * Returns the CQL signature of this function.
218- * <p>
218+ * <p/>
219219 * This is the name of the function, followed by the names of the argument types between parentheses,
220220 * for example {@code sum(int,int)}.
221- * <p>
221+ * <p/>
222222 * Note that the returned signature is not qualified with the keyspace name.
223223 *
224224 * @return the signature of this function.
@@ -226,8 +226,8 @@
226226 public String getSignature() {
227227 StringBuilder sb = new StringBuilder();
228228 sb
229- .append(Metadata.escapeId(simpleName))
230- .append('(');
229+ .append(Metadata.escapeId(simpleName))
230+ .append('(');
231231 boolean first = true;
232232 for (DataType type : arguments.values()) {
233233 if (first)
@@ -242,13 +242,12 @@
242242
243243 /**
244244 * Returns the simple name of this function.
245- * <p>
245+ * <p/>
246246 * This is the name of the function, without arguments. Note that functions can be overloaded with
247247 * different argument lists, therefore the simple name may not be unique. For example,
248248 * {@code sum(int,int)} and {@code sum(int,int,int)} both have the simple name {@code sum}.
249249 *
250250 * @return the simple name of this function.
251- *
252251 * @see #getSignature()
253252 */
254253 public String getSimpleName() {
@@ -275,7 +274,7 @@
275274
276275 /**
277276 * Indicates whether this function's body gets called on null input.
278- * <p>
277+ * <p/>
279278 * This is {@code true} if the function was created with {@code CALLED ON NULL INPUT},
280279 * and {@code false} if it was created with {@code RETURNS NULL ON NULL INPUT}.
281280 *
@@ -309,13 +308,13 @@
309308 return true;
310309
311310 if (other instanceof FunctionMetadata) {
312- FunctionMetadata that = (FunctionMetadata)other;
311+ FunctionMetadata that = (FunctionMetadata) other;
313312 return this.keyspace.getName().equals(that.keyspace.getName()) &&
314- this.arguments.equals(that.arguments) &&
315- this.body.equals(that.body) &&
316- this.calledOnNullInput == that.calledOnNullInput &&
317- this.language.equals(that.language) &&
318- this.returnType.equals(that.returnType);
313+ this.arguments.equals(that.arguments) &&
314+ this.body.equals(that.body) &&
315+ this.calledOnNullInput == that.calledOnNullInput &&
316+ this.language.equals(that.language) &&
317+ this.returnType.equals(that.returnType);
319318 }
320319 return false;
321320 }
modified driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +116 −145
@@ -15,18 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.CodecNotFoundException;
19+import com.datastax.driver.core.exceptions.InvalidTypeException;
20+import com.google.common.reflect.TypeToken;
21+
1822 import java.math.BigDecimal;
1923 import java.math.BigInteger;
2024 import java.net.InetAddress;
2125 import java.nio.ByteBuffer;
2226 import java.util.*;
2327
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.CodecNotFoundException;
27-
28-import com.datastax.driver.core.exceptions.InvalidTypeException;
29-
3028 /**
3129 * Collection of (typed) CQL values that can be retrieved by index (starting at 0).
3230 */
@@ -37,289 +35,271 @@
3735 *
3836 * @param i the index ({@code 0 <= i < size()}) of the value to check.
3937 * @return whether the {@code i}th value is NULL.
40- *
4138 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for
42- * this object.
39+ * this object.
4340 */
4441 public boolean isNull(int i);
4542
4643 /**
4744 * Returns the {@code i}th value as a boolean.
48- * <p>
45+ * <p/>
4946 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code boolean}
5047 * (for CQL type {@code boolean}, this will be the built-in codec).
5148 *
5249 * @param i the index ({@code 0 <= i < size()}) to retrieve.
5350 * @return the boolean value of the {@code i}th element. If the value is NULL, {@code false} is returned.
5451 * If you need to distinguish NULL and false values, check first with {@link #isNull(int)} or use {@code get(i, Boolean.class)}.
55- *
5652 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
57- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
58- * type to a boolean.
53+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
54+ * type to a boolean.
5955 */
6056 public boolean getBool(int i);
6157
6258 /**
6359 * Returns the {@code i}th value as a byte.
64- * <p>
60+ * <p/>
6561 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code byte}
6662 * (for CQL type {@code tinyint}, this will be the built-in codec).
6763 *
6864 * @param i the index ({@code 0 <= i < size()}) to retrieve.
6965 * @return the value of the {@code i}th element as a byte. If the value is NULL, {@code 0} is returned.
7066 * If you need to distinguish NULL and 0, check first with {@link #isNull(int)} or use {@code get(i, Byte.class)}.
71- *
7267 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
73- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
74- * type to a byte.
68+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
69+ * type to a byte.
7570 */
7671 public byte getByte(int i);
7772
7873 /**
7974 * Returns the {@code i}th value as a short.
80- * <p>
75+ * <p/>
8176 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code short}
8277 * (for CQL type {@code smallint}, this will be the built-in codec).
8378 *
8479 * @param i the index ({@code 0 <= i < size()}) to retrieve.
8580 * @return the value of the {@code i}th element as a short. If the value is NULL, {@code 0} is returned.
8681 * If you need to distinguish NULL and 0, check first with {@link #isNull(int)} or use {@code get(i, Short.class)}.
87- *
8882 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
89- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
90- * type to a short.
83+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
84+ * type to a short.
9185 */
9286 public short getShort(int i);
9387
9488 /**
9589 * Returns the {@code i}th value as an integer.
96- * <p>
90+ * <p/>
9791 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code int}
9892 * (for CQL type {@code int}, this will be the built-in codec).
9993 *
10094 * @param i the index ({@code 0 <= i < size()}) to retrieve.
10195 * @return the value of the {@code i}th element as an integer. If the value is NULL, {@code 0} is returned.
10296 * If you need to distinguish NULL and 0, check first with {@link #isNull(int)} or use {@code get(i, Integer.class)}.
103- *
10497 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
105- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
106- * type to an int.
98+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
99+ * type to an int.
107100 */
108101 public int getInt(int i);
109102
110103 /**
111104 * Returns the {@code i}th value as a long.
112- * <p>
105+ * <p/>
113106 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code byte}
114107 * (for CQL types {@code bigint} and {@code counter}, this will be the built-in codec).
115108 *
116109 * @param i the index ({@code 0 <= i < size()}) to retrieve.
117110 * @return the value of the {@code i}th element as a long. If the value is NULL, {@code 0L} is returned.
118111 * If you need to distinguish NULL and 0L, check first with {@link #isNull(int)} or use {@code get(i, Long.class)}.
119- *
120112 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
121- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
122- * type to a long.
113+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
114+ * type to a long.
123115 */
124116 public long getLong(int i);
125117
126118 /**
127119 * Returns the {@code i}th value as a date.
128- * <p>
120+ * <p/>
129121 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code Date}
130122 * (for CQL type {@code timestamp}, this will be the built-in codec).
131123 *
132124 * @param i the index ({@code 0 <= i < size()}) to retrieve.
133125 * @return the value of the {@code i}th element as a data. If the
134126 * value is NULL, {@code null} is returned.
135- *
136127 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
137- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
138- * type to a {@code Date}.
128+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
129+ * type to a {@code Date}.
139130 */
140131 public Date getTimestamp(int i);
141132
142133 /**
143134 * Returns the {@code i}th value as a date (without time).
144- * <p>
135+ * <p/>
145136 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@link LocalDate}
146137 * (for CQL type {@code date}, this will be the built-in codec).
147138 *
148139 * @param i the index ({@code 0 <= i < size()}) to retrieve.
149140 * @return the value of the {@code i}th element as an date. If the
150141 * value is NULL, {@code null} is returned.
151- *
152142 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
153- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
154- * type to a {@code LocalDate}.
143+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
144+ * type to a {@code LocalDate}.
155145 */
156146 public LocalDate getDate(int i);
157147
158148 /**
159149 * Returns the {@code i}th value as a long in nanoseconds since midnight.
160- * <p>
150+ * <p/>
161151 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code long}
162152 * (for CQL type {@code time}, this will be the built-in codec).
163153 *
164154 * @param i the index ({@code 0 <= i < size()}) to retrieve.
165155 * @return the value of the {@code i}th element as a long. If the
166156 * value is NULL, {@code 0L} is returned.
167- *
168157 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
169- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
170- * type to a long.
158+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
159+ * type to a long.
171160 */
172161 public long getTime(int i);
173162
174163 /**
175164 * Returns the {@code i}th value as a float.
176- * <p>
165+ * <p/>
177166 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code float}
178167 * (for CQL type {@code float}, this will be the built-in codec).
179168 *
180169 * @param i the index ({@code 0 <= i < size()}) to retrieve.
181170 * @return the value of the {@code i}th element as a float. If the value is NULL, {@code 0.0f} is returned.
182171 * If you need to distinguish NULL and 0.0f, check first with {@link #isNull(int)} or use {@code get(i, Float.class)}.
183- *
184172 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
185- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
186- * type to a float.
173+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
174+ * type to a float.
187175 */
188176 public float getFloat(int i);
189177
190178 /**
191179 * Returns the {@code i}th value as a double.
192- * <p>
180+ * <p/>
193181 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code double}
194182 * (for CQL type {@code double}, this will be the built-in codec).
195183 *
196184 * @param i the index ({@code 0 <= i < size()}) to retrieve.
197185 * @return the value of the {@code i}th element as a double. If the value is NULL, {@code 0.0} is returned.
198186 * If you need to distinguish NULL and 0.0, check first with {@link #isNull(int)} or use {@code get(i, Double.class)}.
199- *
200187 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
201- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
202- * type to a double.
188+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
189+ * type to a double.
203190 */
204191 public double getDouble(int i);
205192
206193 /**
207194 * Returns the {@code i}th value as a {@code ByteBuffer}.
208- * <p>
195+ * <p/>
209196 * This method does not use any codec; it returns a copy of the binary representation of the value. It is up to the
210197 * caller to convert the returned value appropriately.
211198 *
212199 * @param i the index ({@code 0 <= i < size()}) to retrieve.
213200 * @return the value of the {@code i}th element as a ByteBuffer. If the
214201 * value is NULL, {@code null} is returned.
215- *
216202 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
217203 */
218204 public ByteBuffer getBytesUnsafe(int i);
219205
220206 /**
221207 * Returns the {@code i}th value as a byte array.
222- * <p>
208+ * <p/>
223209 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code ByteBuffer}
224210 * (for CQL type {@code blob}, this will be the built-in codec).
225211 *
226212 * @param i the index ({@code 0 <= i < size()}) to retrieve.
227213 * @return the value of the {@code i}th element as a byte array. If the
228214 * value is NULL, {@code null} is returned.
229- *
230215 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
231- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
232- * type to a {@code ByteBuffer}.
216+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
217+ * type to a {@code ByteBuffer}.
233218 */
234219 public ByteBuffer getBytes(int i);
235220
236221 /**
237222 * Returns the {@code i}th value as a string.
238- * <p>
223+ * <p/>
239224 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java string
240225 * (for CQL types {@code text}, {@code varchar} and {@code ascii}, this will be the built-in codec).
241226 *
242227 * @param i the index ({@code 0 <= i < size()}) to retrieve.
243228 * @return the value of the {@code i}th element as a string. If the
244229 * value is NULL, {@code null} is returned.
245- *
246230 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
247- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
248- * type to a string.
231+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
232+ * type to a string.
249233 */
250234 public String getString(int i);
251235
252236 /**
253237 * Returns the {@code i}th value as a variable length integer.
254- * <p>
238+ * <p/>
255239 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code BigInteger}
256240 * (for CQL type {@code varint}, this will be the built-in codec).
257241 *
258242 * @param i the index ({@code 0 <= i < size()}) to retrieve.
259243 * @return the value of the {@code i}th element as a variable
260244 * length integer. If the value is NULL, {@code null} is returned.
261- *
262245 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
263- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
264- * type to a {@code BigInteger}.
246+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
247+ * type to a {@code BigInteger}.
265248 */
266249 public BigInteger getVarint(int i);
267250
268251 /**
269252 * Returns the {@code i}th value as a variable length decimal.
270- * <p>
253+ * <p/>
271254 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code BigDecimal}
272255 * (for CQL type {@code decimal}, this will be the built-in codec).
273256 *
274257 * @param i the index ({@code 0 <= i < size()}) to retrieve.
275258 * @return the value of the {@code i}th element as a variable
276259 * length decimal. If the value is NULL, {@code null} is returned.
277- *
278260 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
279- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
280- * type to a {@code BigDecimal}.
261+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
262+ * type to a {@code BigDecimal}.
281263 */
282264 public BigDecimal getDecimal(int i);
283265
284266 /**
285267 * Returns the {@code i}th value as a UUID.
286- * <p>
268+ * <p/>
287269 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code UUID}
288270 * (for CQL types {@code uuid} and {@code timeuuid}, this will be the built-in codec).
289271 *
290272 * @param i the index ({@code 0 <= i < size()}) to retrieve.
291273 * @return the value of the {@code i}th element as a UUID.
292274 * If the value is NULL, {@code null} is returned.
293- *
294275 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
295- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
296- * type to a {@code UUID}.
276+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
277+ * type to a {@code UUID}.
297278 */
298279 public UUID getUUID(int i);
299280
300281 /**
301282 * Returns the {@code i}th value as an InetAddress.
302- * <p>
283+ * <p/>
303284 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to an {@code InetAddress}
304285 * (for CQL type {@code inet}, this will be the built-in codec).
305286 *
306287 * @param i the index ({@code 0 <= i < size()}) to retrieve.
307288 * @return the value of the {@code i}th element as an InetAddress.
308289 * If the value is NULL, {@code null} is returned.
309- *
310290 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
311- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
312- * type to a {@code InetAddress}.
291+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
292+ * type to a {@code InetAddress}.
313293 */
314294 public InetAddress getInet(int i);
315295
316296 /**
317297 * Returns the {@code i}th value as a list.
318- * <p>
298+ * <p/>
319299 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a list of the specified type.
320- * <p>
300+ * <p/>
321301 * If the type of the elements is generic, use {@link #getList(int, TypeToken)}.
322- * <p>
302+ * <p/>
323303 * Implementation note: the actual {@link List} implementation will depend
324304 * on the {@link TypeCodec codec} being used; therefore, callers should
325305 * make no assumptions concerning its mutability nor its thread-safety.
@@ -328,27 +308,26 @@
328308 * a CQL {@code NULL} will be mapped to an empty collection (note that Cassandra
329309 * makes no distinction between {@code NULL} and an empty collection).
330310 *
331- * @param i the index ({@code 0 <= i < size()}) to retrieve.
311+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
332312 * @param elementsClass the class for the elements of the list to retrieve.
333313 * @return the value of the {@code i}th element as a list of
334314 * {@code T} objects.
335- *
336315 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
337- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
338- * type to a list.
316+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
317+ * type to a list.
339318 */
340319 public <T> List<T> getList(int i, Class<T> elementsClass);
341320
342321 /**
343322 * Returns the {@code i}th value as a list.
344- * <p>
323+ * <p/>
345324 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a list of the specified type.
346- * <p>
325+ * <p/>
347326 * Use this variant with nested collections, which produce a generic element type:
348327 * <pre>
349328 * {@code List<List<String>> l = row.getList(1, new TypeToken<List<String>>() {});}
350329 * </pre>
351- * <p>
330+ * <p/>
352331 * Implementation note: the actual {@link List} implementation will depend
353332 * on the {@link TypeCodec codec} being used; therefore, callers should
354333 * make no assumptions concerning its mutability nor its thread-safety.
@@ -357,24 +336,23 @@
357336 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
358337 * makes no distinction between {@code NULL} and an empty collection).
359338 *
360- * @param i the index ({@code 0 <= i < size()}) to retrieve.
339+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
361340 * @param elementsType the type of the elements of the list to retrieve.
362341 * @return the value of the {@code i}th element as a list of
363342 * {@code T} objects.
364- *
365343 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
366- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
367- * type to a list.
344+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
345+ * type to a list.
368346 */
369347 public <T> List<T> getList(int i, TypeToken<T> elementsType);
370348
371349 /**
372350 * Returns the {@code i}th value as a set.
373- * <p>
351+ * <p/>
374352 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a set of the specified type.
375- * <p>
353+ * <p/>
376354 * If the type of the elements is generic, use {@link #getSet(int, TypeToken)}.
377- * <p>
355+ * <p/>
378356 * Implementation note: the actual {@link Set} implementation will depend
379357 * on the {@link TypeCodec codec} being used; therefore, callers should
380358 * make no assumptions concerning its mutability nor its thread-safety.
@@ -383,27 +361,26 @@
383361 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
384362 * makes no distinction between {@code NULL} and an empty collection).
385363 *
386- * @param i the index ({@code 0 <= i < size()}) to retrieve.
364+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
387365 * @param elementsClass the class for the elements of the set to retrieve.
388366 * @return the value of the {@code i}th element as a set of
389367 * {@code T} objects.
390- *
391368 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
392- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
393- * type to a set.
369+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
370+ * type to a set.
394371 */
395372 public <T> Set<T> getSet(int i, Class<T> elementsClass);
396373
397374 /**
398375 * Returns the {@code i}th value as a set.
399- * <p>
376+ * <p/>
400377 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a set of the specified type.
401- * <p>
378+ * <p/>
402379 * Use this variant with nested collections, which produce a generic element type:
403380 * <pre>
404381 * {@code Set<List<String>> l = row.getSet(1, new TypeToken<List<String>>() {});}
405382 * </pre>
406- * <p>
383+ * <p/>
407384 * Implementation note: the actual {@link Set} implementation will depend
408385 * on the {@link TypeCodec codec} being used; therefore, callers should
409386 * make no assumptions concerning its mutability nor its thread-safety.
@@ -412,24 +389,23 @@
412389 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
413390 * makes no distinction between {@code NULL} and an empty collection).
414391 *
415- * @param i the index ({@code 0 <= i < size()}) to retrieve.
392+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
416393 * @param elementsType the type for the elements of the set to retrieve.
417394 * @return the value of the {@code i}th element as a set of
418395 * {@code T} objects.
419- *
420396 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
421- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
422- * type to a set.
397+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
398+ * type to a set.
423399 */
424400 public <T> Set<T> getSet(int i, TypeToken<T> elementsType);
425401
426402 /**
427403 * Returns the {@code i}th value as a map.
428- * <p>
404+ * <p/>
429405 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a map of the specified types.
430- * <p>
406+ * <p/>
431407 * If the type of the keys and/or values is generic, use {@link #getMap(int, TypeToken, TypeToken)}.
432- * <p>
408+ * <p/>
433409 * Implementation note: the actual {@link Map} implementation will depend
434410 * on the {@link TypeCodec codec} being used; therefore, callers should
435411 * make no assumptions concerning its mutability nor its thread-safety.
@@ -438,29 +414,28 @@
438414 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
439415 * makes no distinction between {@code NULL} and an empty collection).
440416 *
441- * @param i the index ({@code 0 <= i < size()}) to retrieve.
442- * @param keysClass the class for the keys of the map to retrieve.
417+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
418+ * @param keysClass the class for the keys of the map to retrieve.
443419 * @param valuesClass the class for the values of the map to retrieve.
444420 * @return the value of the {@code i}th element as a map of
445421 * {@code K} to {@code V} objects.
446- *
447422 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
448- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
449- * type to a map.
423+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
424+ * type to a map.
450425 */
451426 public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass);
452427
453428
454429 /**
455430 * Returns the {@code i}th value as a map.
456- * <p>
431+ * <p/>
457432 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a map of the specified types.
458- * <p>
433+ * <p/>
459434 * Use this variant with nested collections, which produce a generic element type:
460435 * <pre>
461436 * {@code Map<Int, List<String>> l = row.getMap(1, TypeToken.of(Integer.class), new TypeToken<List<String>>() {});}
462437 * </pre>
463- * <p>
438+ * <p/>
464439 * Implementation note: the actual {@link Map} implementation will depend
465440 * on the {@link TypeCodec codec} being used; therefore, callers should
466441 * make no assumptions concerning its mutability nor its thread-safety.
@@ -469,56 +444,53 @@
469444 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
470445 * makes no distinction between {@code NULL} and an empty collection).
471446 *
472- * @param i the index ({@code 0 <= i < size()}) to retrieve.
473- * @param keysType the type for the keys of the map to retrieve.
447+ * @param i the index ({@code 0 <= i < size()}) to retrieve.
448+ * @param keysType the type for the keys of the map to retrieve.
474449 * @param valuesType the type for the values of the map to retrieve.
475450 * @return the value of the {@code i}th element as a map of
476451 * {@code K} to {@code V} objects.
477- *
478452 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
479- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
480- * type to a map.
453+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
454+ * type to a map.
481455 */
482456 public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType);
483457
484458 /**
485459 * Return the {@code i}th value as a UDT value.
486- * <p>
460+ * <p/>
487461 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code UDTValue}
488462 * (if the CQL type is a UDT, the registry will generate a codec automatically).
489463 *
490464 * @param i the index ({@code 0 <= i < size()}) to retrieve.
491465 * @return the value of the {@code i}th element as a UDT value. If the value is NULL,
492466 * then {@code null} will be returned.
493- *
494467 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
495- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
496- * type to a {@code UDTValue}.
468+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
469+ * type to a {@code UDTValue}.
497470 */
498471 public UDTValue getUDTValue(int i);
499472
500473 /**
501474 * Return the {@code i}th value as a tuple value.
502- * <p>
475+ * <p/>
503476 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code TupleValue}
504477 * (if the CQL type is a tuple, the registry will generate a codec automatically).
505478 *
506479 * @param i the index ({@code 0 <= i < size()}) to retrieve.
507480 * @return the value of the {@code i}th element as a tuple value. If the value is NULL,
508481 * then {@code null} will be returned.
509- *
510482 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
511- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
512- * type to a {@code TupleValue}.
483+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
484+ * type to a {@code TupleValue}.
513485 */
514486 public TupleValue getTupleValue(int i);
515487
516488 /**
517489 * Returns the {@code i}th value as the Java type matching its CQL type.
518- * <p>
490+ * <p/>
519491 * This method uses the {@link CodecRegistry} to find the first codec that handles the underlying CQL type. The Java type
520492 * of the returned object will be determined by the codec that was selected.
521- * <p>
493+ * <p/>
522494 * Use this method to dynamically inspect elements when types aren't known in advance, for instance if you're writing a
523495 * generic row logger. If you know the target Java type, it is generally preferable to use typed getters, such as the
524496 * ones for built-in types ({@link #getBool(int)}, {@link #getInt(int)}, etc.), or {@link #get(int, Class)} and
@@ -527,18 +499,17 @@
527499 * @param i the index to retrieve.
528500 * @return the value of the {@code i}th value as the Java type matching its CQL type.
529501 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
530- *
531502 * @see CodecRegistry#codecFor(DataType)
532503 */
533504 public Object getObject(int i);
534505
535506 /**
536507 * Returns the {@code i}th value converted to the given Java type.
537- * <p>
508+ * <p/>
538509 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to the given Java type.
539- * <p>
510+ * <p/>
540511 * If the target type is generic, use {@link #get(int, TypeToken)}.
541- * <p>
512+ * <p/>
542513 * Implementation note: the actual object returned by this method will depend
543514 * on the {@link TypeCodec codec} being used; therefore, callers should
544515 * make no assumptions concerning its mutability nor its thread-safety.
@@ -546,20 +517,20 @@
546517 * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
547518 * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
548519 *
549- * @param i the index to retrieve.
520+ * @param i the index to retrieve.
550521 * @param targetClass The Java type the value should be converted to.
551522 * @return the value of the {@code i}th value converted to the given Java type.
552523 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
553- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
554- * type to {@code targetClass}.
524+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
525+ * type to {@code targetClass}.
555526 */
556527 <T> T get(int i, Class<T> targetClass);
557528
558529 /**
559530 * Returns the {@code i}th value converted to the given Java type.
560- * <p>
531+ * <p/>
561532 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to the given Java type.
562- * <p>
533+ * <p/>
563534 * Implementation note: the actual object returned by this method will depend
564535 * on the {@link TypeCodec codec} being used; therefore, callers should
565536 * make no assumptions concerning its mutability nor its thread-safety.
@@ -567,25 +538,25 @@
567538 * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
568539 * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
569540 *
570- * @param i the index to retrieve.
541+ * @param i the index to retrieve.
571542 * @param targetType The Java type the value should be converted to.
572543 * @return the value of the {@code i}th value converted to the given Java type.
573544 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
574- * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
575- * type to {@code targetType}.
545+ * @throws CodecNotFoundException if there is no registered codec to convert the element's CQL
546+ * type to {@code targetType}.
576547 */
577548 <T> T get(int i, TypeToken<T> targetType);
578549
579550 /**
580551 * Returns the {@code i}th value converted using the given {@link TypeCodec}.
581- * <p>
552+ * <p/>
582553 * This method entirely bypasses the {@link CodecRegistry} and forces the driver to use the given codec instead.
583554 * This can be useful if the codec would collide with a previously registered one, or if you want to use the
584555 * codec just once without registering it.
585- * <p>
556+ * <p/>
586557 * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
587558 * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
588- * <p>
559+ * <p/>
589560 * Implementation note: the actual object returned by this method will depend
590561 * on the {@link TypeCodec codec} being used; therefore, callers should
591562 * make no assumptions concerning its mutability nor its thread-safety.
@@ -593,10 +564,10 @@
593564 * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
594565 * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
595566 *
596- * @param i the index to retrieve.
567+ * @param i the index to retrieve.
597568 * @param codec The {@link TypeCodec} to use to deserialize the value; may not be {@code null}.
598569 * @return the value of the {@code i}th value converted using the given {@link TypeCodec}.
599- * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
570+ * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
600571 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
601572 */
602573 <T> T get(int i, TypeCodec<T> codec);
modified driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +116 −145
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.CodecNotFoundException;
19+import com.datastax.driver.core.exceptions.InvalidTypeException;
20+import com.google.common.reflect.TypeToken;
21+
1822 import java.math.BigDecimal;
1923 import java.math.BigInteger;
2024 import java.net.InetAddress;
2125 import java.nio.ByteBuffer;
2226 import java.util.*;
2327
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.CodecNotFoundException;
27-import com.datastax.driver.core.exceptions.InvalidTypeException;
28-
2928 /**
3029 * Collection of (typed) CQL values that can be retrieved by name.
3130 */
@@ -36,30 +35,28 @@
3635 *
3736 * @param name the name to check.
3837 * @return whether the value for {@code name} is NULL.
39- *
4038 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
4139 */
4240 public boolean isNull(String name);
4341
4442 /**
4543 * Returns the value for {@code name} as a boolean.
46- * <p>
44+ * <p/>
4745 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code boolean}
4846 * (for CQL type {@code boolean}, this will be the built-in codec).
4947 *
5048 * @param name the name to retrieve.
5149 * @return the boolean value for {@code name}. If the value is NULL, {@code false} is returned.
5250 * If you need to distinguish NULL and false values, check first with {@link #isNull(String)} or use {@code get(name, Boolean.class)}.
53- *
5451 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
55- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
56- * type to a boolean.
52+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
53+ * type to a boolean.
5754 */
5855 public boolean getBool(String name);
5956
6057 /**
6158 * Returns the value for {@code name} as a byte.
62- * <p>
59+ * <p/>
6360 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code byte}
6461 * (for CQL type {@code tinyint}, this will be the built-in codec).
6562 *
@@ -67,16 +64,15 @@
6764 * @return the value for {@code name} as a byte. If the value is NULL, {@code 0} is returned.
6865 * If you need to distinguish NULL and 0, check first with {@link #isNull(String)} or use {@code get(name, Byte.class)}.
6966 * {@code 0} is returned.
70- *
7167 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
72- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
73- * type to a byte.
68+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
69+ * type to a byte.
7470 */
7571 public byte getByte(String name);
7672
7773 /**
7874 * Returns the value for {@code name} as a short.
79- * <p>
75+ * <p/>
8076 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code short}
8177 * (for CQL type {@code smallint}, this will be the built-in codec).
8278 *
@@ -84,16 +80,15 @@
8480 * @return the value for {@code name} as a short. If the value is NULL, {@code 0} is returned.
8581 * If you need to distinguish NULL and 0, check first with {@link #isNull(String)} or use {@code get(name, Short.class)}.
8682 * {@code 0} is returned.
87- *
8883 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
89- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
90- * type to a short.
84+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
85+ * type to a short.
9186 */
9287 public short getShort(String name);
9388
9489 /**
9590 * Returns the value for {@code name} as an integer.
96- * <p>
91+ * <p/>
9792 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code int}
9893 * (for CQL type {@code int}, this will be the built-in codec).
9994 *
@@ -101,115 +96,108 @@
10196 * @return the value for {@code name} as an integer. If the value is NULL, {@code 0} is returned.
10297 * If you need to distinguish NULL and 0, check first with {@link #isNull(String)} or use {@code get(name, Integer.class)}.
10398 * {@code 0} is returned.
104- *
10599 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
106- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
107- * type to an int.
100+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
101+ * type to an int.
108102 */
109103 public int getInt(String name);
110104
111105 /**
112106 * Returns the value for {@code name} as a long.
113- * <p>
107+ * <p/>
114108 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code byte}
115109 * (for CQL types {@code bigint} and {@code counter}, this will be the built-in codec).
116110 *
117111 * @param name the name to retrieve.
118112 * @return the value for {@code name} as a long. If the value is NULL, {@code 0L} is returned.
119113 * If you need to distinguish NULL and 0L, check first with {@link #isNull(String)} or use {@code get(name, Long.class)}.
120- *
121114 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
122- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
123- * type to a long.
115+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
116+ * type to a long.
124117 */
125118 public long getLong(String name);
126119
127120 /**
128121 * Returns the value for {@code name} as a date.
129- * <p>
122+ * <p/>
130123 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code Date}
131124 * (for CQL type {@code timestamp}, this will be the built-in codec).
132125 *
133126 * @param name the name to retrieve.
134127 * @return the value for {@code name} as a date. If the value is NULL,
135128 * {@code null} is returned.
136- *
137129 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
138- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
139- * type to a {@code Date}.
130+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
131+ * type to a {@code Date}.
140132 */
141133 public Date getTimestamp(String name);
142134
143135 /**
144136 * Returns the value for {@code name} as a date (without time).
145- * <p>
137+ * <p/>
146138 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@link LocalDate}
147139 * (for CQL type {@code date}, this will be the built-in codec).
148140 *
149141 * @param name the name to retrieve.
150142 * @return the value for {@code name} as a date. If the value is NULL,
151143 * {@code null} is returned.
152- *
153144 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
154- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
155- * type to a {@code LocalDate}.
145+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
146+ * type to a {@code LocalDate}.
156147 */
157148 public LocalDate getDate(String name);
158149
159150 /**
160151 * Returns the value for {@code name} as a long in nanoseconds since midnight.
161- * <p>
152+ * <p/>
162153 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code long}
163154 * (for CQL type {@code time}, this will be the built-in codec).
164155 *
165156 * @param name the name to retrieve.
166157 * @return the value for {@code name} as a long. If the value is NULL,
167158 * {@code 0L} is returned.
168- *
169159 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
170- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
171- * type to a long.
160+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
161+ * type to a long.
172162 */
173163 public long getTime(String name);
174164
175165 /**
176166 * Returns the value for {@code name} as a float.
177- * <p>
167+ * <p/>
178168 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code float}
179169 * (for CQL type {@code float}, this will be the built-in codec).
180170 *
181171 * @param name the name to retrieve.
182172 * @return the value for {@code name} as a float. If the value is NULL, {@code 0.0f} is returned.
183173 * If you need to distinguish NULL and 0.0f, check first with {@link #isNull(String)} or use {@code get(name, Float.class)}.
184- *
185174 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
186- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
187- * type to a float.
175+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
176+ * type to a float.
188177 */
189178 public float getFloat(String name);
190179
191180 /**
192181 * Returns the value for {@code name} as a double.
193- * <p>
182+ * <p/>
194183 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code double}
195184 * (for CQL type {@code double}, this will be the built-in codec).
196185 *
197186 * @param name the name to retrieve.
198187 * @return the value for {@code name} as a double. If the value is NULL, {@code 0.0} is returned.
199188 * If you need to distinguish NULL and 0.0, check first with {@link #isNull(String)} or use {@code get(name, Double.class)}.
200- *
201189 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
202- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
203- * type to a double.
190+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
191+ * type to a double.
204192 */
205193 public double getDouble(String name);
206194
207195 /**
208196 * Returns the value for {@code name} as a ByteBuffer.
209- * <p>
197+ * <p/>
210198 * This method does not use any codec; it returns a copy of the binary representation of the value. It is up to the
211199 * caller to convert the returned value appropriately.
212- *
200+ * <p/>
213201 * Note: this method always return the bytes composing the value, even if
214202 * the column is not of type BLOB. That is, this method never throw an
215203 * InvalidTypeException. However, if the type is not BLOB, it is up to the
@@ -218,114 +206,107 @@
218206 * @param name the name to retrieve.
219207 * @return the value for {@code name} as a ByteBuffer. If the value is NULL,
220208 * {@code null} is returned.
221- *
222209 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
223210 */
224211 public ByteBuffer getBytesUnsafe(String name);
225212
226213 /**
227214 * Returns the value for {@code name} as a byte array.
228- * <p>
215+ * <p/>
229216 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java {@code ByteBuffer}
230217 * (for CQL type {@code blob}, this will be the built-in codec).
231218 *
232219 * @param name the name to retrieve.
233220 * @return the value for {@code name} as a byte array. If the value is NULL,
234221 * {@code null} is returned.
235- *
236222 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
237- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
238- * type to a {@code ByteBuffer}.
223+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
224+ * type to a {@code ByteBuffer}.
239225 */
240226 public ByteBuffer getBytes(String name);
241227
242228 /**
243229 * Returns the value for {@code name} as a string.
244- * <p>
230+ * <p/>
245231 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a Java string
246232 * (for CQL types {@code text}, {@code varchar} and {@code ascii}, this will be the built-in codec).
247233 *
248234 * @param name the name to retrieve.
249235 * @return the value for {@code name} as a string. If the value is NULL,
250236 * {@code null} is returned.
251- *
252237 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
253- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
254- * type to a string.
238+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
239+ * type to a string.
255240 */
256241 public String getString(String name);
257242
258243 /**
259244 * Returns the value for {@code name} as a variable length integer.
260- * <p>
245+ * <p/>
261246 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code BigInteger}
262247 * (for CQL type {@code varint}, this will be the built-in codec).
263248 *
264249 * @param name the name to retrieve.
265250 * @return the value for {@code name} as a variable length integer.
266251 * If the value is NULL, {@code null} is returned.
267- *
268252 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
269- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
270- * type to a {@code BigInteger}.
253+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
254+ * type to a {@code BigInteger}.
271255 */
272256 public BigInteger getVarint(String name);
273257
274258 /**
275259 * Returns the value for {@code name} as a variable length decimal.
276- * <p>
260+ * <p/>
277261 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code BigDecimal}
278262 * (for CQL type {@code decimal}, this will be the built-in codec).
279263 *
280264 * @param name the name to retrieve.
281265 * @return the value for {@code name} as a variable length decimal.
282266 * If the value is NULL, {@code null} is returned.
283- *
284267 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
285- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
286- * type to a {@code BigDecimal}.
268+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
269+ * type to a {@code BigDecimal}.
287270 */
288271 public BigDecimal getDecimal(String name);
289272
290273 /**
291274 * Returns the value for {@code name} as a UUID.
292- * <p>
275+ * <p/>
293276 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code UUID}
294277 * (for CQL types {@code uuid} and {@code timeuuid}, this will be the built-in codec).
295278 *
296279 * @param name the name to retrieve.
297280 * @return the value for {@code name} as a UUID.
298281 * If the value is NULL, {@code null} is returned.
299- *
300282 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
301- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
302- * type to a {@code UUID}.
283+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
284+ * type to a {@code UUID}.
303285 */
304286 public UUID getUUID(String name);
305287
306288 /**
307289 * Returns the value for {@code name} as an InetAddress.
308- * <p>
290+ * <p/>
309291 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to an {@code InetAddress}
310292 * (for CQL type {@code inet}, this will be the built-in codec).
311293 *
312294 * @param name the name to retrieve.
313295 * @return the value for {@code name} as an InetAddress.
314296 * If the value is NULL, {@code null} is returned.
315- *
316297 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
317- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
318- * type to a {@code InetAddress}.
298+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
299+ * type to a {@code InetAddress}.
319300 */
320301 public InetAddress getInet(String name);
321302
322303 /**
323304 * Returns the value for {@code name} as a list.
324- * <p>
305+ * <p/>
325306 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a list of the specified type.
326- * <p>
307+ * <p/>
327308 * If the type of the elements is generic, use {@link #getList(String, TypeToken)}.
328- * <p>
309+ * <p/>
329310 * Implementation note: the actual {@link List} implementation will depend
330311 * on the {@link TypeCodec codec} being used; therefore, callers should
331312 * make no assumptions concerning its mutability nor its thread-safety.
@@ -334,27 +315,26 @@
334315 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
335316 * makes no distinction between {@code NULL} and an empty collection).
336317 *
337- * @param name the name to retrieve.
318+ * @param name the name to retrieve.
338319 * @param elementsClass the class for the elements of the list to retrieve.
339320 * @return the value of the {@code i}th element as a list of
340321 * {@code T} objects.
341- *
342322 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
343- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
344- * type to a list.
323+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
324+ * type to a list.
345325 */
346326 public <T> List<T> getList(String name, Class<T> elementsClass);
347327
348328 /**
349329 * Returns the value for {@code name} as a list.
350- * <p>
330+ * <p/>
351331 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a list of the specified type.
352- * <p>
332+ * <p/>
353333 * Use this variant with nested collections, which produce a generic element type:
354334 * <pre>
355335 * {@code List<List<String>> l = row.getList("theColumn", new TypeToken<List<String>>() {});}
356336 * </pre>
357- * <p>
337+ * <p/>
358338 * Implementation note: the actual {@link List} implementation will depend
359339 * on the {@link TypeCodec codec} being used; therefore, callers should
360340 * make no assumptions concerning its mutability nor its thread-safety.
@@ -363,24 +343,23 @@
363343 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
364344 * makes no distinction between {@code NULL} and an empty collection).
365345 *
366- * @param name the name to retrieve.
346+ * @param name the name to retrieve.
367347 * @param elementsType the type for the elements of the list to retrieve.
368348 * @return the value of the {@code i}th element as a list of
369349 * {@code T} objects.
370- *
371350 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
372- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
373- * type to a list.
351+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
352+ * type to a list.
374353 */
375354 public <T> List<T> getList(String name, TypeToken<T> elementsType);
376355
377356 /**
378357 * Returns the value for {@code name} as a set.
379- * <p>
358+ * <p/>
380359 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a set of the specified type.
381- * <p>
360+ * <p/>
382361 * If the type of the elements is generic, use {@link #getSet(String, TypeToken)}.
383- * <p>
362+ * <p/>
384363 * Implementation note: the actual {@link Set} implementation will depend
385364 * on the {@link TypeCodec codec} being used; therefore, callers should
386365 * make no assumptions concerning its mutability nor its thread-safety.
@@ -389,27 +368,26 @@
389368 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
390369 * makes no distinction between {@code NULL} and an empty collection).
391370 *
392- * @param name the name to retrieve.
371+ * @param name the name to retrieve.
393372 * @param elementsClass the class for the elements of the set to retrieve.
394373 * @return the value of the {@code i}th element as a set of
395374 * {@code T} objects.
396- *
397375 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
398- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
399- * type to a set.
376+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
377+ * type to a set.
400378 */
401379 public <T> Set<T> getSet(String name, Class<T> elementsClass);
402380
403381 /**
404382 * Returns the value for {@code name} as a set.
405- * <p>
383+ * <p/>
406384 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a set of the specified type.
407- * <p>
385+ * <p/>
408386 * Use this variant with nested collections, which produce a generic element type:
409387 * <pre>
410388 * {@code Set<List<String>> l = row.getSet("theColumn", new TypeToken<List<String>>() {});}
411389 * </pre>
412- * <p>
390+ * <p/>
413391 * Implementation note: the actual {@link Set} implementation will depend
414392 * on the {@link TypeCodec codec} being used; therefore, callers should
415393 * make no assumptions concerning its mutability nor its thread-safety.
@@ -418,24 +396,23 @@
418396 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
419397 * makes no distinction between {@code NULL} and an empty collection).
420398 *
421- * @param name the name to retrieve.
399+ * @param name the name to retrieve.
422400 * @param elementsType the type for the elements of the set to retrieve.
423401 * @return the value of the {@code i}th element as a set of
424402 * {@code T} objects.
425- *
426403 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
427- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
428- * type to a set.
404+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
405+ * type to a set.
429406 */
430407 public <T> Set<T> getSet(String name, TypeToken<T> elementsType);
431408
432409 /**
433410 * Returns the value for {@code name} as a map.
434- * <p>
411+ * <p/>
435412 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a map of the specified types.
436- * <p>
413+ * <p/>
437414 * If the type of the keys and/or values is generic, use {@link #getMap(String, TypeToken, TypeToken)}.
438- * <p>
415+ * <p/>
439416 * Implementation note: the actual {@link Map} implementation will depend
440417 * on the {@link TypeCodec codec} being used; therefore, callers should
441418 * make no assumptions concerning its mutability nor its thread-safety.
@@ -444,28 +421,27 @@
444421 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
445422 * makes no distinction between {@code NULL} and an empty collection).
446423 *
447- * @param name the name to retrieve.
448- * @param keysClass the class for the keys of the map to retrieve.
424+ * @param name the name to retrieve.
425+ * @param keysClass the class for the keys of the map to retrieve.
449426 * @param valuesClass the class for the values of the map to retrieve.
450427 * @return the value of {@code name} as a map of
451428 * {@code K} to {@code V} objects.
452- *
453429 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
454- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
455- * type to a map.
430+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
431+ * type to a map.
456432 */
457433 public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass);
458434
459435 /**
460436 * Returns the value for {@code name} as a map.
461- * <p>
437+ * <p/>
462438 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a map of the specified types.
463- * <p>
439+ * <p/>
464440 * Use this variant with nested collections, which produce a generic element type:
465441 * <pre>
466442 * {@code Map<Int, List<String>> l = row.getMap("theColumn", TypeToken.of(Integer.class), new TypeToken<List<String>>() {});}
467443 * </pre>
468- * <p>
444+ * <p/>
469445 * Implementation note: the actual {@link Map} implementation will depend
470446 * on the {@link TypeCodec codec} being used; therefore, callers should
471447 * make no assumptions concerning its mutability nor its thread-safety.
@@ -474,56 +450,53 @@
474450 * a CQL {@code NULL} will mapped to an empty collection (note that Cassandra
475451 * makes no distinction between {@code NULL} and an empty collection).
476452 *
477- * @param name the name to retrieve.
478- * @param keysType the class for the keys of the map to retrieve.
453+ * @param name the name to retrieve.
454+ * @param keysType the class for the keys of the map to retrieve.
479455 * @param valuesType the class for the values of the map to retrieve.
480456 * @return the value of {@code name} as a map of
481457 * {@code K} to {@code V} objects.
482- *
483458 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
484- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
485- * type to a map.
459+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
460+ * type to a map.
486461 */
487462 public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType);
488463
489464 /**
490465 * Return the value for {@code name} as a UDT value.
491- * <p>
466+ * <p/>
492467 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code UDTValue}
493468 * (if the CQL type is a UDT, the registry will generate a codec automatically).
494469 *
495470 * @param name the name to retrieve.
496471 * @return the value of {@code name} as a UDT value. If the value is NULL,
497472 * then {@code null} will be returned.
498- *
499473 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
500- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
501- * type to a {@code UDTValue}.
474+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
475+ * type to a {@code UDTValue}.
502476 */
503477 public UDTValue getUDTValue(String name);
504478
505479 /**
506480 * Return the value for {@code name} as a tuple value.
507- * <p>
481+ * <p/>
508482 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to a {@code TupleValue}
509483 * (if the CQL type is a tuple, the registry will generate a codec automatically).
510484 *
511485 * @param name the name to retrieve.
512486 * @return the value of {@code name} as a tuple value. If the value is NULL,
513487 * then {@code null} will be returned.
514- *
515488 * @throws IllegalArgumentException if {@code name} is not valid name for this object.
516- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
517- * type to a {@code TupleValue}.
489+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
490+ * type to a {@code TupleValue}.
518491 */
519492 public TupleValue getTupleValue(String name);
520493
521494 /**
522495 * Returns the value for {@code name} as the Java type matching its CQL type.
523- * <p>
496+ * <p/>
524497 * This method uses the {@link CodecRegistry} to find the first codec that handles the underlying CQL type. The Java type
525498 * of the returned object will be determined by the codec that was selected.
526- * <p>
499+ * <p/>
527500 * Use this method to dynamically inspect elements when types aren't known in advance, for instance if you're writing a
528501 * generic row logger. If you know the target Java type, it is generally preferable to use typed getters, such as the
529502 * ones for built-in types ({@link #getBool(String)}, {@link #getInt(String)}, etc.), or {@link #get(String, Class)} and
@@ -533,20 +506,18 @@
533506 * @return the value of {@code name} as the Java type matching its CQL type.
534507 * If the value is NULL and is a simple type, UDT or tuple, {@code null} is returned.
535508 * If it is NULL and is a collection type, an empty (immutable) collection is returned.
536- *
537509 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
538- *
539510 * @see CodecRegistry#codecFor(DataType)
540511 */
541512 Object getObject(String name);
542513
543514 /**
544515 * Returns the value for {@code name} converted to the given Java type.
545- * <p>
516+ * <p/>
546517 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to the given Java type.
547- * <p>
518+ * <p/>
548519 * If the target type is generic, use {@link #get(String, TypeToken)}.
549- * <p>
520+ * <p/>
550521 * Implementation note: the actual object returned by this method will depend
551522 * on the {@link TypeCodec codec} being used; therefore, callers should
552523 * make no assumptions concerning its mutability nor its thread-safety.
@@ -554,20 +525,20 @@
554525 * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
555526 * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
556527 *
557- * @param name the name to retrieve.
528+ * @param name the name to retrieve.
558529 * @param targetClass The Java type the value should be converted to.
559530 * @return the value for {@code name} value converted to the given Java type.
560531 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
561- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
562- * type to {@code targetClass}.
532+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
533+ * type to {@code targetClass}.
563534 */
564535 <T> T get(String name, Class<T> targetClass);
565536
566537 /**
567538 * Returns the value for {@code name} converted to the given Java type.
568- * <p>
539+ * <p/>
569540 * This method uses the {@link CodecRegistry} to find a codec to convert the underlying CQL type to the given Java type.
570- * <p>
541+ * <p/>
571542 * Implementation note: the actual object returned by this method will depend
572543 * on the {@link TypeCodec codec} being used; therefore, callers should
573544 * make no assumptions concerning its mutability nor its thread-safety.
@@ -575,25 +546,25 @@
575546 * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
576547 * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
577548 *
578- * @param name the name to retrieve.
549+ * @param name the name to retrieve.
579550 * @param targetType The Java type the value should be converted to.
580551 * @return the value for {@code name} value converted to the given Java type.
581552 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
582- * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
583- * type to {@code targetType}.
553+ * @throws CodecNotFoundException if there is no registered codec to convert the underlying CQL
554+ * type to {@code targetType}.
584555 */
585556 <T> T get(String name, TypeToken<T> targetType);
586557
587558 /**
588559 * Returns the value for {@code name} converted using the given {@link TypeCodec}.
589- * <p>
560+ * <p/>
590561 * This method entirely bypasses the {@link CodecRegistry} and forces the driver to use the given codec instead.
591562 * This can be useful if the codec would collide with a previously registered one, or if you want to use the
592563 * codec just once without registering it.
593- * <p>
564+ * <p/>
594565 * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
595566 * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
596- * <p>
567+ * <p/>
597568 * Implementation note: the actual object returned by this method will depend
598569 * on the {@link TypeCodec codec} being used; therefore, callers should
599570 * make no assumptions concerning its mutability nor its thread-safety.
@@ -601,10 +572,10 @@
601572 * codec-dependent; by default, a CQL {@code NULL} value translates to {@code null} for
602573 * simple CQL types, UDTs and tuples, and to empty collections for all CQL collection types.
603574 *
604- * @param name the name to retrieve.
575+ * @param name the name to retrieve.
605576 * @param codec The {@link TypeCodec} to use to deserialize the value; may not be {@code null}.
606577 * @return the value of the {@code i}th value converted using the given {@link TypeCodec}.
607- * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
578+ * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
608579 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
609580 */
610581 <T> T get(String name, TypeCodec<T> codec);
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +24 −21
@@ -15,20 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.ImmutableList;
19+import com.google.common.util.concurrent.ListenableFuture;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+
1823 import java.net.InetAddress;
1924 import java.net.InetSocketAddress;
2025 import java.util.Set;
2126 import java.util.concurrent.atomic.AtomicReference;
2227 import java.util.concurrent.locks.ReentrantLock;
2328
24-import com.google.common.collect.ImmutableList;
25-import com.google.common.util.concurrent.ListenableFuture;
26-import org.slf4j.Logger;
27-import org.slf4j.LoggerFactory;
28-
2929 /**
3030 * A Cassandra node.
31- *
31+ * <p/>
3232 * This class keeps the information the driver maintain on a given Cassandra node.
3333 */
3434 public class Host {
@@ -39,9 +39,12 @@
3939
4040 private final InetSocketAddress address;
4141
42- enum State { ADDED, DOWN, UP }
42+ enum State {ADDED, DOWN, UP}
43+
4344 volatile State state;
44- /** Ensures state change notifications for that host are handled serially */
45+ /**
46+ * Ensures state change notifications for that host are handled serially
47+ */
4548 final ReentrantLock notificationsLock = new ReentrantLock(true);
4649
4750 final ConvictionPolicy convictionPolicy;
@@ -98,7 +101,7 @@
98101
99102 /**
100103 * Returns the node address.
101- * <p>
104+ * <p/>
102105 * This is a shortcut for {@code getSocketAddress().getAddress()}.
103106 *
104107 * @return the node {@link InetAddress}.
@@ -118,7 +121,7 @@
118121
119122 /**
120123 * Returns the name of the datacenter this host is part of.
121- * <p>
124+ * <p/>
122125 * The returned datacenter name is the one as known by Cassandra.
123126 * It is also possible for this information to be unavailable. In that
124127 * case this method returns {@code null}, and the caller should always be aware
@@ -132,7 +135,7 @@
132135
133136 /**
134137 * Returns the name of the rack this host is part of.
135- * <p>
138+ * <p/>
136139 * The returned rack name is the one as known by Cassandra.
137140 * It is also possible for this information to be unavailable. In that case
138141 * this method returns {@code null}, and the caller should always aware of this
@@ -146,7 +149,7 @@
146149
147150 /**
148151 * The Cassandra version the host is running.
149- * <p>
152+ * <p/>
150153 * As for other host information fetch from Cassandra above, the returned
151154 * version can theoretically be null if the information is unavailable.
152155 *
@@ -171,7 +174,7 @@
171174
172175 /**
173176 * Returns whether the host is considered up by the driver.
174- * <p>
177+ * <p/>
175178 * Please note that this is only the view of the driver and may not reflect
176179 * reality. In particular a node can be down but the driver hasn't detected
177180 * it yet, or it can have been restarted and the driver hasn't detected it
@@ -188,7 +191,7 @@
188191
189192 /**
190193 * Returns a description of the host's state, as seen by the driver.
191- * <p>
194+ * <p/>
192195 * This is exposed for debugging purposes only; the format of this string might
193196 * change between driver versions, so clients should not make any assumptions
194197 * about it.
@@ -202,7 +205,7 @@
202205 /**
203206 * Returns a {@code ListenableFuture} representing the completion of the reconnection
204207 * attempts scheduled after a host is marked {@code DOWN}.
205- * <p>
208+ * <p/>
206209 * <b>If the caller cancels this future,</b> the driver will not try to reconnect to
207210 * this host until it receives an UP event for it. Note that this could mean never, if
208211 * the node was marked down because of a driver-side error (e.g. read timeout) but no
@@ -217,14 +220,14 @@
217220
218221 /**
219222 * Triggers an asynchronous reconnection attempt to this host.
220- * <p>
223+ * <p/>
221224 * This method is intended for load balancing policies that mark hosts as {@link HostDistance#IGNORED IGNORED},
222225 * but still need a way to periodically check these hosts' states (UP / DOWN).
223- * <p>
226+ * <p/>
224227 * For a host that is at distance {@code IGNORED}, this method will try to reconnect exactly once: if
225228 * reconnection succeeds, the host is marked {@code UP}; otherwise, no further attempts will be scheduled.
226229 * It has no effect if the node is already {@code UP}, or if a reconnection attempt is already in progress.
227- * <p>
230+ * <p/>
228231 * Note that if the host is <em>not</em> a distance {@code IGNORED}, this method <em>will</em> trigger a periodic
229232 * reconnection attempt if the reconnection fails.
230233 */
@@ -235,7 +238,7 @@
235238 @Override
236239 public boolean equals(Object other) {
237240 if (other instanceof Host) {
238- Host that = (Host)other;
241+ Host that = (Host) other;
239242 return this.address.equals(that.address);
240243 }
241244 return false;
@@ -266,7 +269,7 @@
266269 /**
267270 * Interface for listeners that are interested in hosts added, up, down and
268271 * removed events.
269- * <p>
272+ * <p/>
270273 * It is possible for the same event to be fired multiple times,
271274 * particularly for up or down events. Therefore, a listener should ignore
272275 * the same event if it has already been notified of a node's state.
@@ -275,7 +278,7 @@
275278
276279 /**
277280 * Called when a new node is added to the cluster.
278- * <p>
281+ * <p/>
279282 * The newly added node should be considered up.
280283 *
281284 * @param host the host that has been newly added.
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +29 −25
@@ -15,6 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.AuthenticationException;
19+import com.datastax.driver.core.exceptions.ConnectionException;
20+import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
21+import com.datastax.driver.core.utils.MoreFutures;
22+import com.google.common.annotations.VisibleForTesting;
23+import com.google.common.base.Throwables;
24+import com.google.common.collect.Lists;
25+import com.google.common.util.concurrent.*;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+
1829 import java.util.ArrayList;
1930 import java.util.List;
2031 import java.util.ListIterator;
@@ -26,22 +37,7 @@
2637 import java.util.concurrent.locks.Lock;
2738 import java.util.concurrent.locks.ReentrantLock;
2839
29-import com.google.common.annotations.VisibleForTesting;
30-import com.google.common.base.Throwables;
31-import com.google.common.collect.Lists;
32-import com.google.common.util.concurrent.*;
33-import org.slf4j.Logger;
34-import org.slf4j.LoggerFactory;
35-
36-import com.datastax.driver.core.exceptions.AuthenticationException;
37-import com.datastax.driver.core.exceptions.ConnectionException;
38-import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
39-import com.datastax.driver.core.utils.MoreFutures;
40-
41-import static com.datastax.driver.core.Connection.State.GONE;
42-import static com.datastax.driver.core.Connection.State.OPEN;
43-import static com.datastax.driver.core.Connection.State.RESURRECTING;
44-import static com.datastax.driver.core.Connection.State.TRASHED;
40+import static com.datastax.driver.core.Connection.State.*;
4541
4642 class HostConnectionPool implements Connection.Owner {
4743
@@ -55,9 +51,13 @@
5551
5652 final List<Connection> connections;
5753 private final AtomicInteger open;
58- /** The total number of in-flight requests on all connections of this pool. */
54+ /**
55+ * The total number of in-flight requests on all connections of this pool.
56+ */
5957 final AtomicInteger totalInFlight = new AtomicInteger();
60- /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
58+ /**
59+ * The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}
60+ */
6161 private final AtomicInteger maxTotalInFlight = new AtomicInteger();
6262 @VisibleForTesting
6363 final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
@@ -151,7 +151,7 @@
151151 forceClose(connections);
152152 } else {
153153 logger.debug("Created connection pool to host {} ({} connections needed, {} successfully opened)",
154- host, coreSize, connections.size());
154+ host, coreSize, connections.size());
155155 phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
156156 initFuture.set(null);
157157 }
@@ -271,7 +271,7 @@
271271 } else if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
272272 // Add a connection if we fill the first n-1 connections and almost fill the last one
273273 int currentCapacity = (connectionCount - 1) * options().getMaxRequestsPerConnection(hostDistance)
274- + options().getNewConnectionThreshold(hostDistance);
274+ + options().getNewConnectionThreshold(hostDistance);
275275 if (totalInFlightCount > currentCapacity)
276276 maybeSpawnNewConnection();
277277 }
@@ -548,7 +548,9 @@
548548 cleanupTrash(now);
549549 }
550550
551- /** If we have more active connections than needed, trash some of them */
551+ /**
552+ * If we have more active connections than needed, trash some of them
553+ */
552554 private void shrinkIfBelowCapacity() {
553555 int currentLoad = maxTotalInFlight.getAndSet(totalInFlight.get());
554556
@@ -561,7 +563,7 @@
561563 int toTrash = Math.max(0, actual - needed);
562564
563565 logger.trace("Current inFlight = {}, {} connections needed, {} connections available, trashing {}",
564- currentLoad, needed, actual, toTrash);
566+ currentLoad, needed, actual, toTrash);
565567
566568 if (toTrash <= 0)
567569 return;
@@ -574,7 +576,9 @@
574576 }
575577 }
576578
577- /** Close connections that have been sitting in the trash for too long */
579+ /**
580+ * Close connections that have been sitting in the trash for too long
581+ */
578582 private void cleanupTrash(long now) {
579583 for (Connection connection : trash) {
580584 if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
@@ -614,8 +618,8 @@
614618 future = new CloseFuture.Forwarding(discardAvailableConnections());
615619
616620 return closeFuture.compareAndSet(null, future)
617- ? future
618- : closeFuture.get(); // We raced, it's ok, return the future that was actually set
621+ ? future
622+ : closeFuture.get(); // We raced, it's ok, return the future that was actually set
619623 }
620624
621625 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/IndexMetadata.java +19 −19
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Iterator;
19-import java.util.Map;
20-
2118 import com.google.common.base.Objects;
2219 import com.google.common.base.Predicate;
2320 import com.google.common.collect.ImmutableMap;
2421 import com.google.common.collect.Iterables;
2522
23+import java.util.Iterator;
24+import java.util.Map;
25+
2626 /**
2727 * An immutable representation of secondary index metadata.
2828 */
@@ -109,16 +109,16 @@
109109 options = SimpleJSONParser.parseStringMap(indexOptionsCol);
110110 }
111111 String target = targetFromLegacyOptions(column, options);
112- return new IndexMetadata((TableMetadata)column.getParent(), indexName, kind, target, options);
112+ return new IndexMetadata((TableMetadata) column.getParent(), indexName, kind, target, options);
113113 }
114114
115115 private static String targetFromLegacyOptions(ColumnMetadata column, Map<String, String> options) {
116116 String columnName = Metadata.escapeId(column.getName());
117- if(options.containsKey(INDEX_KEYS_OPTION_NAME))
117+ if (options.containsKey(INDEX_KEYS_OPTION_NAME))
118118 return String.format("keys(%s)", columnName);
119- if(options.containsKey(INDEX_ENTRIES_OPTION_NAME))
119+ if (options.containsKey(INDEX_ENTRIES_OPTION_NAME))
120120 return String.format("entries(%s)", columnName);
121- if(column.getType() instanceof DataType.CollectionType && column.getType().isFrozen())
121+ if (column.getType() instanceof DataType.CollectionType && column.getType().isFrozen())
122122 return String.format("full(%s)", columnName);
123123 // Note: the keyword 'values' is not accepted as a valid index target function until 3.0
124124 return columnName;
@@ -162,7 +162,7 @@
162162
163163 /**
164164 * Returns whether this index is a custom one.
165- * <p>
165+ * <p/>
166166 * If it is indeed a custom index, {@link #getIndexClassName} will
167167 * return the name of the class used in Cassandra to implement that
168168 * index.
@@ -195,7 +195,7 @@
195195
196196 /**
197197 * Returns a CQL query representing this index.
198- *
198+ * <p/>
199199 * This method returns a single 'CREATE INDEX' query corresponding to
200200 * this index definition.
201201 *
@@ -206,26 +206,26 @@
206206 String tableName = Metadata.escapeId(table.getName());
207207 String indexName = Metadata.escapeId(this.name);
208208 return isCustomIndex()
209- ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s' %s;", indexName, keyspaceName, tableName, getTarget(), getIndexClassName(), getOptionsAsCql())
210- : String.format("CREATE INDEX %s ON %s.%s (%s);", indexName, keyspaceName, tableName, getTarget());
209+ ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s' %s;", indexName, keyspaceName, tableName, getTarget(), getIndexClassName(), getOptionsAsCql())
210+ : String.format("CREATE INDEX %s ON %s.%s (%s);", indexName, keyspaceName, tableName, getTarget());
211211 }
212212
213213 /**
214214 * Builds a string representation of the custom index options.
215215 *
216216 * @return String representation of the custom index options, similar to what Cassandra stores in
217- * the 'index_options' column of the 'schema_columns' table in the 'system' keyspace.
217+ * the 'index_options' column of the 'schema_columns' table in the 'system' keyspace.
218218 */
219219 private String getOptionsAsCql() {
220220 Iterable<Map.Entry<String, String>> filtered = Iterables.filter(options.entrySet(), new Predicate<Map.Entry<String, String>>() {
221221 @Override
222222 public boolean apply(Map.Entry<String, String> input) {
223223 return
224- !input.getKey().equals(TARGET_OPTION_NAME) &&
225- !input.getKey().equals(CUSTOM_INDEX_OPTION_NAME);
224+ !input.getKey().equals(TARGET_OPTION_NAME) &&
225+ !input.getKey().equals(CUSTOM_INDEX_OPTION_NAME);
226226 }
227227 });
228- if(Iterables.isEmpty(filtered)) return "";
228+ if (Iterables.isEmpty(filtered)) return "";
229229 StringBuilder builder = new StringBuilder();
230230 builder.append("WITH OPTIONS = {");
231231 Iterator<Map.Entry<String, String>> it = filtered.iterator();
@@ -250,12 +250,12 @@
250250 if (!(obj instanceof IndexMetadata))
251251 return false;
252252
253- IndexMetadata other = (IndexMetadata)obj;
253+ IndexMetadata other = (IndexMetadata) obj;
254254
255255 return Objects.equal(name, other.name)
256- && Objects.equal(kind, other.kind)
257- && Objects.equal(target, other.target)
258- && Objects.equal(options, other.options);
256+ && Objects.equal(kind, other.kind)
257+ && Objects.equal(target, other.target)
258+ && Objects.equal(options, other.options);
259259 }
260260
261261 }
modified driver-core/src/main/java/com/datastax/driver/core/JdkSSLOptions.java +7 −7
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.security.NoSuchAlgorithmException;
19-
2018 import io.netty.channel.socket.SocketChannel;
2119 import io.netty.handler.ssl.SslHandler;
20+
2221 import javax.net.ssl.SSLContext;
2322 import javax.net.ssl.SSLEngine;
23+import java.security.NoSuchAlgorithmException;
2424
2525 /**
2626 * {@link SSLOptions} implementation based on built-in JDK classes.
@@ -42,7 +42,7 @@
4242 /**
4343 * Creates a new instance.
4444 *
45- * @param context the SSL context.
45+ * @param context the SSL context.
4646 * @param cipherSuites the cipher suites to use.
4747 */
4848 protected JdkSSLOptions(SSLContext context, String[] cipherSuites) {
@@ -58,8 +58,8 @@
5858
5959 /**
6060 * Creates an SSL engine each time a connection is established.
61- *
62- * <p>
61+ * <p/>
62+ * <p/>
6363 * You might want to override this if you need to fine-tune the engine's configuration
6464 * (for example enabling hostname verification).
6565 *
@@ -91,7 +91,7 @@
9191
9292 /**
9393 * Set the SSL context to use.
94- * <p>
94+ * <p/>
9595 * If this method isn't called, a context with the default options will be used,
9696 * and you can use the default
9797 * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization">JSSE System properties</a>
@@ -108,7 +108,7 @@
108108
109109 /**
110110 * Set the cipher suites to use.
111- * <p>
111+ * <p/>
112112 * If this method isn't called, the default is to present all the eligible client ciphers to the server.
113113 *
114114 * @param cipherSuites the cipher suites to use.
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +17 −21
@@ -15,25 +15,25 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.annotations.VisibleForTesting;
19+import com.google.common.collect.Lists;
20+
1821 import java.util.Collection;
1922 import java.util.Collections;
2023 import java.util.HashMap;
2124 import java.util.Map;
2225 import java.util.concurrent.ConcurrentHashMap;
2326
24-import com.google.common.annotations.VisibleForTesting;
25-import com.google.common.collect.Lists;
26-
2727 /**
2828 * Describes a keyspace defined in this cluster.
2929 */
3030 public class KeyspaceMetadata {
3131
32- public static final String KS_NAME = "keyspace_name";
33- private static final String DURABLE_WRITES = "durable_writes";
34- private static final String STRATEGY_CLASS = "strategy_class";
32+ public static final String KS_NAME = "keyspace_name";
33+ private static final String DURABLE_WRITES = "durable_writes";
34+ private static final String STRATEGY_CLASS = "strategy_class";
3535 private static final String STRATEGY_OPTIONS = "strategy_options";
36- private static final String REPLICATION = "replication";
36+ private static final String REPLICATION = "replication";
3737
3838 private final String name;
3939 private final boolean durableWrites;
@@ -177,9 +177,8 @@
177177 /**
178178 * Returns the definition of a function in this keyspace.
179179 *
180- * @param name the name of the function.
180+ * @param name the name of the function.
181181 * @param argumentTypes the types of the function's arguments.
182- *
183182 * @return the function definition if it exists in this keyspace, {@code null} otherwise.
184183 */
185184 public FunctionMetadata getFunction(String name, Collection<DataType> argumentTypes) {
@@ -189,9 +188,8 @@
189188 /**
190189 * Returns the definition of a function in this keyspace.
191190 *
192- * @param name the name of the function.
191+ * @param name the name of the function.
193192 * @param argumentTypes the types of the function's arguments.
194- *
195193 * @return the function definition if it exists in this keyspace, {@code null} otherwise.
196194 */
197195 public FunctionMetadata getFunction(String name, DataType... argumentTypes) {
@@ -215,9 +213,8 @@
215213 /**
216214 * Returns the definition of an aggregate in this keyspace.
217215 *
218- * @param name the name of the aggregate.
216+ * @param name the name of the aggregate.
219217 * @param argumentTypes the types of the aggregate's arguments.
220- *
221218 * @return the aggregate definition if it exists in this keyspace, {@code null} otherwise.
222219 */
223220 public AggregateMetadata getAggregate(String name, Collection<DataType> argumentTypes) {
@@ -227,9 +224,8 @@
227224 /**
228225 * Returns the definition of an aggregate in this keyspace.
229226 *
230- * @param name the name of the aggregate.
227+ * @param name the name of the aggregate.
231228 * @param argumentTypes the types of the aggregate's arguments.
232- *
233229 * @return the aggregate definition if it exists in this keyspace, {@code null} otherwise.
234230 */
235231 public AggregateMetadata getAggregate(String name, DataType... argumentTypes) {
@@ -253,11 +249,11 @@
253249 /**
254250 * Returns a {@code String} containing CQL queries representing this
255251 * keyspace and the user types and tables it contains.
256- * <p>
252+ * <p/>
257253 * In other words, this method returns the queries that would allow to
258254 * recreate the schema of this keyspace, along with all its user
259255 * types/tables.
260- * <p>
256+ * <p/>
261257 * Note that the returned String is formatted to be human readable (for
262258 * some definition of human readable at least).
263259 *
@@ -275,10 +271,10 @@
275271 for (TableMetadata tm : tables.values())
276272 sb.append('\n').append(tm.exportAsString()).append('\n');
277273
278- for (FunctionMetadata fm: functions.values())
274+ for (FunctionMetadata fm : functions.values())
279275 sb.append('\n').append(fm.exportAsString()).append('\n');
280276
281- for (AggregateMetadata am: aggregates.values())
277+ for (AggregateMetadata am : aggregates.values())
282278 sb.append('\n').append(am.exportAsString()).append('\n');
283279
284280 return sb.toString();
@@ -286,7 +282,7 @@
286282
287283 /**
288284 * Returns a CQL query representing this keyspace.
289- * <p>
285+ * <p/>
290286 * This method returns a single 'CREATE KEYSPACE' query with the options
291287 * corresponding to this keyspace definition.
292288 *
@@ -320,7 +316,7 @@
320316 if (o == null || getClass() != o.getClass())
321317 return false;
322318
323- KeyspaceMetadata that = (KeyspaceMetadata)o;
319+ KeyspaceMetadata that = (KeyspaceMetadata) o;
324320
325321 if (durableWrites != that.durableWrites)
326322 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/LocalDate.java +16 −22
@@ -25,13 +25,13 @@
2525
2626 /**
2727 * A date with no time components, no time zone, in the ISO 8601 calendar.
28- *
28+ * <p/>
2929 * Note that ISO 8601 has a number of differences with the default gregorian calendar used in Java:
3030 * <ul>
31- * <li>it uses a proleptic gregorian calendar, meaning that it's gregorian indefinitely back in the past (there is no gregorian change);</li>
32- * <li>there is a year 0.</li>
31+ * <li>it uses a proleptic gregorian calendar, meaning that it's gregorian indefinitely back in the past (there is no gregorian change);</li>
32+ * <li>there is a year 0.</li>
3333 * </ul>
34- *
34+ * <p/>
3535 * This class implements these differences, so that year/month/day fields match exactly the ones in
3636 * CQL string literals.
3737 *
@@ -56,7 +56,6 @@
5656 * Builds a new instance from a number of days since January 1st, 1970 GMT.
5757 *
5858 * @param daysSinceEpoch the number of days.
59- *
6059 * @return the new instance.
6160 */
6261 public static LocalDate fromDaysSinceEpoch(int daysSinceEpoch) {
@@ -69,33 +68,29 @@
6968 * it will be rounded towards 0.
7069 *
7170 * @param millisSinceEpoch the number of milliseconds since January 1st, 1970 GMT.
72- *
7371 * @return the new instance.
74- *
7572 * @throws IllegalArgumentException if the date is not in the range [-5877641-06-23; 5881580-07-11].
7673 */
7774 public static LocalDate fromMillisSinceEpoch(long millisSinceEpoch) throws IllegalArgumentException {
7875 long daysSinceEpoch = TimeUnit.MILLISECONDS.toDays(millisSinceEpoch);
7976 checkArgument(daysSinceEpoch >= Integer.MIN_VALUE && daysSinceEpoch <= Integer.MAX_VALUE,
80- "Date should be in the range [-5877641-06-23; 5881580-07-11]");
77+ "Date should be in the range [-5877641-06-23; 5881580-07-11]");
8178
82- return new LocalDate((int)daysSinceEpoch);
79+ return new LocalDate((int) daysSinceEpoch);
8380 }
8481
8582 /**
8683 * Builds a new instance from a year/month/day specification.
87- *
84+ * <p/>
8885 * This method is not lenient, i.e. '2014-12-32' will not be treated as '2015-01-01', but
8986 * instead throw an {@code IllegalArgumentException}.
9087 *
91- * @param year the year in ISO format (see {@link LocalDate this class's Javadoc}).
92- * @param month the month. It is 1-based (e.g. 1 for January).
88+ * @param year the year in ISO format (see {@link LocalDate this class's Javadoc}).
89+ * @param month the month. It is 1-based (e.g. 1 for January).
9390 * @param dayOfMonth the day of the month.
94- *
9591 * @return the new instance.
96- *
9792 * @throws IllegalArgumentException if the corresponding date does not exist in the ISO8601
98- * calendar.
93+ * calendar.
9994 */
10095 public static LocalDate fromYearMonthDay(int year, int month, int dayOfMonth) {
10196 int calendarYear = (year <= 0) ? -year + 1 : year;
@@ -166,18 +161,17 @@
166161 * Return a new {@link LocalDate} with the specified (signed) amount
167162 * of time added to (or subtracted from) the given {@link Calendar} field,
168163 * based on the calendar's rules.
169- * <p>
164+ * <p/>
170165 * Note that adding any amount to a field smaller than
171166 * {@link Calendar#DAY_OF_MONTH} will remain without effect,
172167 * as this class does not keep time components.
173- * <p>
168+ * <p/>
174169 * See {@link Calendar} javadocs for more information.
175170 *
176- * @param field a {@link Calendar} field to modify.
171+ * @param field a {@link Calendar} field to modify.
177172 * @param amount the amount of date or time to be added to the field.
178173 * @return a new {@link LocalDate} with the specified (signed) amount
179174 * of time added to (or subtracted from) the given {@link Calendar} field.
180- *
181175 * @throws IllegalArgumentException if the new date is not in the range [-5877641-06-23; 5881580-07-11].
182176 */
183177 public LocalDate add(int field, int amount) {
@@ -195,7 +189,7 @@
195189 return true;
196190
197191 if (o instanceof LocalDate) {
198- LocalDate that = (LocalDate)o;
192+ LocalDate that = (LocalDate) o;
199193 return this.daysSinceEpoch == that.daysSinceEpoch;
200194 }
201195 return false;
@@ -209,8 +203,8 @@
209203 @Override
210204 public String toString() {
211205 return String.format("%d-%s-%s", getYear(),
212- pad2(getMonth()),
213- pad2(getDay()));
206+ pad2(getMonth()),
207+ pad2(getDay()));
214208 }
215209
216210 private static String pad2(int i) {
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/MaterializedViewMetadata.java +40 −40
@@ -16,16 +16,15 @@
1616 package com.datastax.driver.core;
1717
1818
19-import java.util.*;
20-
2119 import com.google.common.base.Objects;
22-
2320 import org.slf4j.Logger;
2421 import org.slf4j.LoggerFactory;
2522
23+import java.util.*;
24+
2625 /**
27- * An immutable representation of a materialized view.
28- * Materialized views are available starting from Cassandra 3.0.
26+ * An immutable representation of a materialized view.
27+ * Materialized views are available starting from Cassandra 3.0.
2928 */
3029 public class MaterializedViewMetadata extends TableOrView {
3130
@@ -38,18 +37,18 @@
3837 private final String whereClause;
3938
4039 private MaterializedViewMetadata(
41- KeyspaceMetadata keyspace,
42- TableMetadata baseTable,
43- String name,
44- UUID id,
45- List<ColumnMetadata> partitionKey,
46- List<ColumnMetadata> clusteringColumns,
47- Map<String, ColumnMetadata> columns,
48- boolean includeAllColumns,
49- String whereClause,
50- TableOptionsMetadata options,
51- List<ClusteringOrder> clusteringOrder,
52- VersionNumber cassandraVersion) {
40+ KeyspaceMetadata keyspace,
41+ TableMetadata baseTable,
42+ String name,
43+ UUID id,
44+ List<ColumnMetadata> partitionKey,
45+ List<ColumnMetadata> clusteringColumns,
46+ Map<String, ColumnMetadata> columns,
47+ boolean includeAllColumns,
48+ String whereClause,
49+ TableOptionsMetadata options,
50+ List<ClusteringOrder> clusteringOrder,
51+ VersionNumber cassandraVersion) {
5352 super(keyspace, name, id, partitionKey, clusteringColumns, columns, options, clusteringOrder, cassandraVersion);
5453 this.baseTable = baseTable;
5554 this.includeAllColumns = includeAllColumns;
@@ -61,10 +60,10 @@
6160 String name = row.getString("view_name");
6261 String tableName = row.getString("base_table_name");
6362 TableMetadata baseTable = keyspace.tables.get(tableName);
64- if(baseTable == null) {
63+ if (baseTable == null) {
6564 logger.trace(String.format("Cannot find base table %s for materialized view %s.%s: "
66- + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\") will return null",
67- tableName, keyspace.getName(), name, keyspace.getName(), name));
65+ + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\") will return null",
66+ tableName, keyspace.getName(), name, keyspace.getName(), name));
6867 return null;
6968 }
7069
@@ -89,20 +88,20 @@
8988 // See ControlConnection#refreshSchema for why we'd rather not probably this further. Since table options is one thing
9089 // that tends to change often in Cassandra, it's worth special casing this.
9190 logger.error(String.format("Error parsing schema options for view %s.%s: "
92- + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\").getOptions() will return null",
93- keyspace.getName(), name, keyspace.getName(), name), e);
91+ + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\").getOptions() will return null",
92+ keyspace.getName(), name, keyspace.getName(), name), e);
9493 }
9594
9695 MaterializedViewMetadata view = new MaterializedViewMetadata(
97- keyspace, baseTable, name, id, partitionKey, clusteringColumns, columns,
98- includeAllColumns, whereClause, options, clusteringOrder, cassandraVersion);
96+ keyspace, baseTable, name, id, partitionKey, clusteringColumns, columns,
97+ includeAllColumns, whereClause, options, clusteringOrder, cassandraVersion);
9998
10099 // We use this temporary set just so non PK columns are added in lexicographical order, which is the one of a
101100 // 'SELECT * FROM ...'
102101 Set<ColumnMetadata> otherColumns = new TreeSet<ColumnMetadata>(columnMetadataComparator);
103102 for (ColumnMetadata.Raw rawCol : rawCols.values()) {
104103 DataType dataType;
105- if(cassandraVersion.getMajor() >= 3) {
104+ if (cassandraVersion.getMajor() >= 3) {
106105 dataType = DataTypeCqlNameParser.parse(rawCol.dataType, cluster, keyspace.getName(), keyspace.userTypes, keyspace.userTypes, false, false);
107106 } else {
108107 ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
@@ -146,6 +145,7 @@
146145
147146 /**
148147 * Return this materialized view's base table.
148+ *
149149 * @return this materialized view's base table.
150150 */
151151 public TableMetadata getBaseTable() {
@@ -161,20 +161,20 @@
161161
162162 StringBuilder sb = new StringBuilder();
163163 sb.append("CREATE MATERIALIZED VIEW ")
164- .append(keyspaceName).append('.').append(viewName)
165- .append(" AS ");
164+ .append(keyspaceName).append('.').append(viewName)
165+ .append(" AS ");
166166 newLine(sb, formatted);
167167
168168 // SELECT
169169 sb.append("SELECT ");
170- if(includeAllColumns) {
170+ if (includeAllColumns) {
171171 sb.append(" * ");
172172 } else {
173173 Iterator<ColumnMetadata> it = columns.values().iterator();
174- while(it.hasNext()) {
174+ while (it.hasNext()) {
175175 ColumnMetadata column = it.next();
176176 sb.append(spaces(4, formatted)).append(Metadata.escapeId(column.getName()));
177- if(it.hasNext()) sb.append(",");
177+ if (it.hasNext()) sb.append(",");
178178 sb.append(" ");
179179 newLine(sb, formatted);
180180 }
@@ -220,21 +220,21 @@
220220 if (!(other instanceof MaterializedViewMetadata))
221221 return false;
222222
223- MaterializedViewMetadata that = (MaterializedViewMetadata)other;
223+ MaterializedViewMetadata that = (MaterializedViewMetadata) other;
224224 return Objects.equal(this.name, that.name) &&
225- Objects.equal(this.id, that.id) &&
226- Objects.equal(this.partitionKey, that.partitionKey) &&
227- Objects.equal(this.clusteringColumns, that.clusteringColumns) &&
228- Objects.equal(this.columns, that.columns) &&
229- Objects.equal(this.options, that.options) &&
230- Objects.equal(this.clusteringOrder, that.clusteringOrder) &&
231- Objects.equal(this.baseTable.getName(), that.baseTable.getName()) &&
232- this.includeAllColumns == that.includeAllColumns;
225+ Objects.equal(this.id, that.id) &&
226+ Objects.equal(this.partitionKey, that.partitionKey) &&
227+ Objects.equal(this.clusteringColumns, that.clusteringColumns) &&
228+ Objects.equal(this.columns, that.columns) &&
229+ Objects.equal(this.options, that.options) &&
230+ Objects.equal(this.clusteringOrder, that.clusteringOrder) &&
231+ Objects.equal(this.baseTable.getName(), that.baseTable.getName()) &&
232+ this.includeAllColumns == that.includeAllColumns;
233233 }
234234
235235 @Override
236236 public int hashCode() {
237237 return Objects.hashCode(name, id, partitionKey, clusteringColumns, columns, options, clusteringOrder,
238- baseTable.getName(), includeAllColumns);
238+ baseTable.getName(), includeAllColumns);
239239 }
240240 }
modified driver-core/src/main/java/com/datastax/driver/core/Message.java +65 −47
@@ -15,9 +15,8 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
2120 import io.netty.buffer.ByteBuf;
2221 import io.netty.channel.ChannelHandler;
2322 import io.netty.channel.ChannelHandlerContext;
@@ -27,8 +26,8 @@
2726 import org.slf4j.Logger;
2827 import org.slf4j.LoggerFactory;
2928
30-import com.datastax.driver.core.exceptions.DriverInternalError;
31-import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
29+import java.nio.ByteBuffer;
30+import java.util.*;
3231
3332 /**
3433 * A message from the CQL binary protocol.
@@ -41,6 +40,7 @@
4140
4241 public interface Coder<R extends Request> {
4342 public void encode(R request, ByteBuf dest, ProtocolVersion version);
43+
4444 public int encodedSize(R request, ProtocolVersion version);
4545 }
4646
@@ -53,11 +53,13 @@
5353 /**
5454 * A generic key-value custom payload. Custom payloads are simply
5555 * ignored by the default QueryHandler implementation server-side.
56+ *
5657 * @since Protocol V4
5758 */
5859 private volatile Map<String, ByteBuffer> customPayload;
5960
60- protected Message() {}
61+ protected Message() {
62+ }
6163
6264 public Message setStreamId(int streamId) {
6365 this.streamId = streamId;
@@ -68,11 +70,11 @@
6870 return streamId;
6971 }
7072
71- public Map<String,ByteBuffer> getCustomPayload() {
73+ public Map<String, ByteBuffer> getCustomPayload() {
7274 return customPayload;
7375 }
7476
75- public Message setCustomPayload(Map<String,ByteBuffer> customPayload) {
77+ public Message setCustomPayload(Map<String, ByteBuffer> customPayload) {
7678 this.customPayload = customPayload;
7779 return this;
7880 }
@@ -80,15 +82,15 @@
8082 public static abstract class Request extends Message {
8183
8284 public enum Type {
83- STARTUP (1, Requests.Startup.coder),
84- CREDENTIALS (4, Requests.Credentials.coder),
85- OPTIONS (5, Requests.Options.coder),
86- QUERY (7, Requests.Query.coder),
87- PREPARE (9, Requests.Prepare.coder),
88- EXECUTE (10, Requests.Execute.coder),
89- REGISTER (11, Requests.Register.coder),
90- BATCH (13, Requests.Batch.coder),
91- AUTH_RESPONSE (15, Requests.AuthResponse.coder);
85+ STARTUP(1, Requests.Startup.coder),
86+ CREDENTIALS(4, Requests.Credentials.coder),
87+ OPTIONS(5, Requests.Options.coder),
88+ QUERY(7, Requests.Query.coder),
89+ PREPARE(9, Requests.Prepare.coder),
90+ EXECUTE(10, Requests.Execute.coder),
91+ REGISTER(11, Requests.Register.coder),
92+ BATCH(13, Requests.Batch.coder),
93+ AUTH_RESPONSE(15, Requests.AuthResponse.coder);
9294
9395 public final int opcode;
9496 public final Coder<?> coder;
@@ -117,36 +119,51 @@
117119
118120 ConsistencyLevel consistency() {
119121 switch (this.type) {
120- case QUERY: return ((Requests.Query)this).options.consistency;
121- case EXECUTE: return ((Requests.Execute)this).options.consistency;
122- case BATCH: return ((Requests.Batch)this).options.consistency;
123- default: return null;
122+ case QUERY:
123+ return ((Requests.Query) this).options.consistency;
124+ case EXECUTE:
125+ return ((Requests.Execute) this).options.consistency;
126+ case BATCH:
127+ return ((Requests.Batch) this).options.consistency;
128+ default:
129+ return null;
124130 }
125131 }
126132
127133 ConsistencyLevel serialConsistency() {
128134 switch (this.type) {
129- case QUERY: return ((Requests.Query)this).options.serialConsistency;
130- case EXECUTE: return ((Requests.Execute)this).options.serialConsistency;
131- case BATCH: return ((Requests.Batch)this).options.serialConsistency;
132- default: return null;
135+ case QUERY:
136+ return ((Requests.Query) this).options.serialConsistency;
137+ case EXECUTE:
138+ return ((Requests.Execute) this).options.serialConsistency;
139+ case BATCH:
140+ return ((Requests.Batch) this).options.serialConsistency;
141+ default:
142+ return null;
133143 }
134144 }
135145
136146 long defaultTimestamp() {
137147 switch (this.type) {
138- case QUERY: return ((Requests.Query)this).options.defaultTimestamp;
139- case EXECUTE: return ((Requests.Execute)this).options.defaultTimestamp;
140- case BATCH: return ((Requests.Batch)this).options.defaultTimestamp;
141- default: return 0;
148+ case QUERY:
149+ return ((Requests.Query) this).options.defaultTimestamp;
150+ case EXECUTE:
151+ return ((Requests.Execute) this).options.defaultTimestamp;
152+ case BATCH:
153+ return ((Requests.Batch) this).options.defaultTimestamp;
154+ default:
155+ return 0;
142156 }
143157 }
144158
145159 ByteBuffer pagingState() {
146160 switch (this.type) {
147- case QUERY: return ((Requests.Query)this).options.pagingState;
148- case EXECUTE: return ((Requests.Execute)this).options.pagingState;
149- default: return null;
161+ case QUERY:
162+ return ((Requests.Query) this).options.pagingState;
163+ case EXECUTE:
164+ return ((Requests.Execute) this).options.pagingState;
165+ default:
166+ return null;
150167 }
151168 }
152169
@@ -162,19 +179,20 @@
162179 public static abstract class Response extends Message {
163180
164181 public enum Type {
165- ERROR (0, Responses.Error.decoder),
166- READY (2, Responses.Ready.decoder),
167- AUTHENTICATE (3, Responses.Authenticate.decoder),
168- SUPPORTED (6, Responses.Supported.decoder),
169- RESULT (8, Responses.Result.decoder),
170- EVENT (12, Responses.Event.decoder),
171- AUTH_CHALLENGE (14, Responses.AuthChallenge.decoder),
172- AUTH_SUCCESS (16, Responses.AuthSuccess.decoder);
182+ ERROR(0, Responses.Error.decoder),
183+ READY(2, Responses.Ready.decoder),
184+ AUTHENTICATE(3, Responses.Authenticate.decoder),
185+ SUPPORTED(6, Responses.Supported.decoder),
186+ RESULT(8, Responses.Result.decoder),
187+ EVENT(12, Responses.Event.decoder),
188+ AUTH_CHALLENGE(14, Responses.AuthChallenge.decoder),
189+ AUTH_SUCCESS(16, Responses.AuthSuccess.decoder);
173190
174191 public final int opcode;
175192 public final Decoder<?> decoder;
176193
177194 private static final Type[] opcodeIdx;
195+
178196 static {
179197 int maxOpcode = -1;
180198 for (Type type : Type.values())
@@ -247,10 +265,10 @@
247265 assert codecRegistry != null;
248266 Response response = Response.Type.fromOpcode(frame.header.opcode).decoder.decode(frame.body, frame.header.version, codecRegistry);
249267 response
250- .setTracingId(tracingId)
251- .setWarnings(warnings)
252- .setCustomPayload(customPayload)
253- .setStreamId(frame.header.streamId);
268+ .setTracingId(tracingId)
269+ .setWarnings(warnings)
270+ .setCustomPayload(customPayload)
271+ .setStreamId(frame.header.streamId);
254272 out.add(response);
255273 } finally {
256274 frame.body.release();
@@ -277,13 +295,13 @@
277295 if (customPayload != null) {
278296 if (protocolVersion.compareTo(ProtocolVersion.V4) < 0)
279297 throw new UnsupportedFeatureException(
280- protocolVersion,
281- "Custom payloads are only supported since native protocol V4");
298+ protocolVersion,
299+ "Custom payloads are only supported since native protocol V4");
282300 flags.add(Frame.Header.Flag.CUSTOM_PAYLOAD);
283301 }
284302
285303 @SuppressWarnings("unchecked")
286- Coder<Request> coder = (Coder<Request>)request.type.coder;
304+ Coder<Request> coder = (Coder<Request>) request.type.coder;
287305 int messageSize = coder.encodedSize(request, protocolVersion);
288306 int payloadLength = -1;
289307 if (customPayload != null) {
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +34 −38
@@ -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.*;
@@ -23,13 +29,6 @@
2329 import java.util.concurrent.locks.ReentrantLock;
2430 import java.util.regex.Pattern;
2531
26-import com.google.common.base.Joiner;
27-import com.google.common.collect.ImmutableMap;
28-import com.google.common.collect.ImmutableSet;
29-import com.google.common.collect.Maps;
30-import org.slf4j.Logger;
31-import org.slf4j.LoggerFactory;
32-
3332 /**
3433 * Keeps metadata on the connected cluster, including known nodes and schema definitions.
3534 */
@@ -60,12 +59,12 @@
6059 return;
6160
6261 Token.Factory factory = partitioner == null
63- ? (tokenMap == null ? null : tokenMap.factory)
64- : Token.getFactory(partitioner);
62+ ? (tokenMap == null ? null : tokenMap.factory)
63+ : Token.getFactory(partitioner);
6564 if (factory == null)
6665 return;
6766
68- this.tokenMap = TokenMap.build(factory, allTokens, keyspaces.values());
67+ this.tokenMap = TokenMap.build(factory, allTokens, keyspaces.values());
6968 } finally {
7069 lock.unlock();
7170 }
@@ -158,7 +157,7 @@
158157 // without keyspace prefix, because that's how
159158 // they appear in a schema change event (in targetSignature)
160159 if (argumentType instanceof UserType) {
161- UserType userType = (UserType)argumentType;
160+ UserType userType = (UserType) argumentType;
162161 String typeName = Metadata.escapeId(userType.getTypeName());
163162 if (userType.isFrozen())
164163 sb.append("frozen<");
@@ -175,7 +174,7 @@
175174
176175 /**
177176 * Quote a keyspace, table or column identifier to make it case sensitive.
178- * <p>
177+ * <p/>
179178 * CQL identifiers, including keyspace, table and column ones, are case insensitive
180179 * by default. Case sensitive identifiers can however be provided by enclosing
181180 * the identifier in double quotes (see the
@@ -195,7 +194,7 @@
195194
196195 /**
197196 * Returns the token ranges that define data distribution in the ring.
198- * <p>
197+ * <p/>
199198 * Note that this information is refreshed asynchronously by the control
200199 * connection, when schema or ring topology changes. It might occasionally
201200 * be stale.
@@ -211,13 +210,13 @@
211210 /**
212211 * Returns the token ranges that are replicated on the given host, for the given
213212 * keyspace.
214- * <p>
213+ * <p/>
215214 * Note that this information is refreshed asynchronously by the control
216215 * connection, when schema or ring topology changes. It might occasionally
217216 * be stale (or even empty).
218217 *
219218 * @param keyspace the name of the keyspace to get token ranges for.
220- * @param host the host.
219+ * @param host the host.
221220 * @return the (immutable) set of token ranges for {@code host} as known
222221 * by the driver. Note that the result might be stale or empty if metadata
223222 * was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -240,14 +239,14 @@
240239
241240 /**
242241 * Returns the set of hosts that are replica for a given partition key.
243- * <p>
242+ * <p/>
244243 * Note that this information is refreshed asynchronously by the control
245244 * connection, when schema or ring topology changes. It might occasionally
246245 * be stale (or even empty).
247246 *
248- * @param keyspace the name of the keyspace to get replicas for.
247+ * @param keyspace the name of the keyspace to get replicas for.
249248 * @param partitionKey the partition key for which to find the set of
250- * replica.
249+ * replica.
251250 * @return the (immutable) set of replicas for {@code partitionKey} as known
252251 * by the driver. Note that the result might be stale or empty if metadata was
253252 * explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -265,13 +264,13 @@
265264
266265 /**
267266 * Returns the set of hosts that are replica for a given token range.
268- * <p>
267+ * <p/>
269268 * Note that this information is refreshed asynchronously by the control
270269 * connection, when schema or ring topology changes. It might occasionally
271270 * be stale (or even empty).
272271 *
273272 * @param keyspace the name of the keyspace to get replicas for.
274- * @param range the token range.
273+ * @param range the token range.
275274 * @return the (immutable) set of replicas for {@code range} as known by the driver.
276275 * Note that the result might be stale or empty if metadata was explicitly disabled
277276 * with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -316,7 +315,7 @@
316315
317316 /**
318317 * Checks whether hosts that are currently up agree on the schema definition.
319- * <p>
318+ * <p/>
320319 * This method performs a one-time check only, without any form of retry; therefore {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}
321320 * does not apply in this case.
322321 *
@@ -336,7 +335,7 @@
336335 * Returns the metadata of a keyspace given its name.
337336 *
338337 * @param keyspace the name of the keyspace for which metadata should be
339- * returned.
338+ * returned.
340339 * @return the metadata of the requested keyspace or {@code null} if {@code
341340 * keyspace} is not a known keyspace. Note that the result might be stale or null if
342341 * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
@@ -365,13 +364,13 @@
365364 /**
366365 * Returns a {@code String} containing CQL queries representing the schema
367366 * of this cluster.
368- *
367+ * <p/>
369368 * In other words, this method returns the queries that would allow to
370369 * recreate the schema of this cluster.
371- *
370+ * <p/>
372371 * Note that the returned String is formatted to be human readable (for
373372 * some definition of human readable at least).
374- *
373+ * <p/>
375374 * It might be stale or empty if metadata was explicitly disabled with
376375 * {@link QueryOptions#setMetadataEnabled(boolean)}.
377376 *
@@ -413,10 +412,9 @@
413412 *
414413 * @param tokenStr the string representation.
415414 * @return the token.
416- *
417415 * @throws IllegalStateException if the token factory was not initialized. This would typically
418- * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
419- * before startup.
416+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
417+ * before startup.
420418 */
421419 public Token newToken(String tokenStr) {
422420 TokenMap current = tokenMap;
@@ -429,12 +427,11 @@
429427 * Builds a new {@link TokenRange}.
430428 *
431429 * @param start the start token.
432- * @param end the end token.
430+ * @param end the end token.
433431 * @return the range.
434- *
435432 * @throws IllegalStateException if the token factory was not initialized. This would typically
436- * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
437- * before startup.
433+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
434+ * before startup.
438435 */
439436 public TokenRange newTokenRange(Token start, Token end) {
440437 TokenMap current = tokenMap;
@@ -615,14 +612,13 @@
615612 Map<String, Map<Token, Set<Host>>> tokenToHosts = new HashMap<String, Map<Token, Set<Host>>>();
616613 Map<ReplicationStrategy, Map<Token, Set<Host>>> replStrategyToHosts = new HashMap<ReplicationStrategy, Map<Token, Set<Host>>>();
617614 Map<String, Map<Host, Set<TokenRange>>> hostsToRanges = new HashMap<String, Map<Host, Set<TokenRange>>>();
618- for (KeyspaceMetadata keyspace : keyspaces)
619- {
615+ for (KeyspaceMetadata keyspace : keyspaces) {
620616 ReplicationStrategy strategy = keyspace.replicationStrategy();
621617 Map<Token, Set<Host>> ksTokens = replStrategyToHosts.get(strategy);
622618 if (ksTokens == null) {
623619 ksTokens = (strategy == null)
624- ? makeNonReplicatedMap(tokenToPrimary)
625- : strategy.computeTokenToReplicaMap(keyspace.getName(), tokenToPrimary, ring);
620+ ? makeNonReplicatedMap(tokenToPrimary)
621+ : strategy.computeTokenToReplicaMap(keyspace.getName(), tokenToPrimary, ring);
626622 replStrategyToHosts.put(strategy, ksTokens);
627623 }
628624
@@ -675,8 +671,8 @@
675671 private static Set<TokenRange> makeTokenRanges(List<Token> ring, Token.Factory factory) {
676672 ImmutableSet.Builder<TokenRange> builder = ImmutableSet.builder();
677673 // JAVA-684: if there is only one token, return the range ]minToken, minToken]
678- if(ring.size() == 1) {
679- builder.add(new TokenRange(factory.minToken(), factory.minToken(), factory));
674+ if (ring.size() == 1) {
675+ builder.add(new TokenRange(factory.minToken(), factory.minToken(), factory));
680676 } else {
681677 for (int i = 0; i < ring.size(); i++) {
682678 Token start = ring.get(i);
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +17 −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
@@ -297,11 +296,11 @@
297296
298297 /**
299298 * Returns the number of connection to Cassandra nodes errors.
300- * <p>
299+ * <p/>
301300 * This represents the number of times that a request to a Cassandra node
302301 * has failed due to a connection problem. This thus also corresponds to
303302 * how often the driver had to pick a fallback host for a request.
304- * <p>
303+ * <p/>
305304 * You can expect a few connection errors when a Cassandra node fails
306305 * (or is stopped) ,but if that number grows continuously you likely have
307306 * a problem.
@@ -542,6 +541,7 @@
542541 public Counter getIgnoresOnOtherErrors() {
543542 return ignoresOnOtherErrors;
544543 }
544+
545545 /**
546546 * Returns the number of times a speculative execution was started
547547 * because a previous execution did not complete within the delay
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +36 −36
@@ -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.buffer.PooledByteBufAllocator;
2220 import io.netty.channel.ChannelOption;
@@ -25,15 +23,17 @@
2523 import io.netty.util.HashedWheelTimer;
2624 import io.netty.util.Timer;
2725
26+import java.util.concurrent.ThreadFactory;
27+
2828 /**
2929 * A set of hooks that allow clients to customize the driver's underlying Netty layer.
30- * <p>
30+ * <p/>
3131 * Clients that need to hook into the driver's underlying Netty layer can
3232 * subclass this class and provide the necessary customization by overriding
3333 * its methods.
34- * <p>
34+ * <p/>
3535 * Typically, clients would register this class with {@link Cluster#builder()}:
36- *
36+ * <p/>
3737 * <pre>
3838 * NettyOptions nettyOptions = ...
3939 * Cluster cluster = Cluster.builder()
@@ -41,24 +41,24 @@
4141 * .withNettyOptions(nettyOptions)
4242 * .build();
4343 * </pre>
44- *
44+ * <p/>
4545 * <strong>Extending the NettyOptions API</strong>
46- * <p>
46+ * <p/>
4747 * Contrary to other driver options, the options available in this class should
4848 * be considered as advanced features and as such, <em>they should only be
4949 * modified by expert users</em>.
50- * <p>
50+ * <p/>
5151 * <strong>A misconfiguration introduced by the means of this API can have unexpected results
5252 * and cause the driver to completely fail to connect.</strong>
53- * <p>
53+ * <p/>
5454 * Moreover, since versions 2.0.9 and 2.1.4 (see JAVA-538),
5555 * the driver is available in two different flavors: with a standard Maven dependency on Netty,
5656 * or with a "shaded" (internalized) Netty dependency.
57- * <p>
57+ * <p/>
5858 * Given that NettyOptions API exposes Netty classes ({@link SocketChannel}, etc.),
5959 * <em>it should only be extended by clients using the non-shaded
6060 * version of driver</em>.
61- * <p>
61+ * <p/>
6262 * <strong>Extending this API with shaded Netty classes is not supported,
6363 * and in particular for OSGi applications, it is likely that such a configuration would lead to
6464 * compile and/or runtime errors.</strong>
@@ -74,15 +74,15 @@
7474
7575 /**
7676 * Return the {@code EventLoopGroup} instance to use.
77- * <p>
77+ * <p/>
7878 * This hook is invoked only once at {@link Cluster} initialization;
7979 * the returned instance will be kept in use throughout the cluster lifecycle.
80- * <p>
80+ * <p/>
8181 * Typically, implementors would return a newly-created instance;
8282 * it is however possible to re-use a shared instance, but in this
8383 * case implementors should also override {@link #onClusterClose(EventLoopGroup)}
8484 * to prevent the shared instance to be closed when the cluster is closed.
85- * <p>
85+ * <p/>
8686 * The default implementation returns a new instance of {@code io.netty.channel.epoll.EpollEventLoopGroup}
8787 * if {@link NettyUtil#isEpollAvailable() epoll is available},
8888 * or {@code io.netty.channel.nio.NioEventLoopGroup} otherwise.
@@ -98,11 +98,11 @@
9898
9999 /**
100100 * Return the specific {@code SocketChannel} subclass to use.
101- * <p>
101+ * <p/>
102102 * This hook is invoked only once at {@link Cluster} initialization;
103103 * the returned instance will then be used each time the driver creates a new {@link Connection}
104104 * and configures a new instance of {@link Bootstrap} for it.
105- * <p>
105+ * <p/>
106106 * The default implementation returns {@code io.netty.channel.epoll.EpollSocketChannel} if {@link NettyUtil#isEpollAvailable() epoll is available},
107107 * or {@code io.netty.channel.socket.nio.NioSocketChannel} otherwise.
108108 *
@@ -115,13 +115,13 @@
115115 /**
116116 * Hook invoked each time the driver creates a new {@link Connection}
117117 * and configures a new instance of {@link Bootstrap} for it.
118- * <p>
118+ * <p/>
119119 * This hook is guaranteed to be called <em>after</em> the driver has applied all
120120 * {@link SocketOptions}s.
121- * <p>
121+ * <p/>
122122 * This is a good place to add extra {@link io.netty.channel.ChannelHandler ChannelOption}s to the boostrap; e.g.
123123 * plug a custom {@link io.netty.buffer.ByteBufAllocator ByteBufAllocator} implementation:
124- *
124+ * <p/>
125125 * <pre>
126126 * ByteBufAllocator myCustomByteBufAllocator = ...
127127 *
@@ -129,7 +129,7 @@
129129 * bootstrap.option(ChannelOption.ALLOCATOR, myCustomByteBufAllocator);
130130 * }
131131 * </pre>
132- *
132+ * <p/>
133133 * Note that the default implementation of this method configures a pooled {@code ByteBufAllocator} (Netty 4.0
134134 * defaults to unpooled). If you override this method to set unrelated options, make sure you call
135135 * {@code super.afterBootstrapInitialized(bootstrap)}.
@@ -144,21 +144,21 @@
144144 /**
145145 * Hook invoked each time the driver creates a new {@link Connection}
146146 * and initializes the {@link SocketChannel channel}.
147- * <p>
147+ * <p/>
148148 * This hook is guaranteed to be called <em>after</em> the driver has registered
149149 * all its internal channel handlers, and applied the configured {@link SSLOptions}, if any.
150- * <p>
150+ * <p/>
151151 * This is a good place to add extra {@link io.netty.channel.ChannelHandler ChannelHandler}s
152152 * to the channel's pipeline; e.g. to add a custom SSL handler to the beginning of the handler chain,
153153 * do the following:
154- *
154+ * <p/>
155155 * <pre>
156156 * ChannelPipeline pipeline = channel.pipeline();
157157 * SSLEngine myCustomSSLEngine = ...
158158 * SslHandler myCustomSSLHandler = new SslHandler(myCustomSSLEngine);
159159 * pipeline.addFirst("ssl", myCustomSSLHandler);
160160 * </pre>
161- *
161+ * <p/>
162162 * Note: if you intend to provide your own SSL implementation,
163163 * do not enable the driver's built-in {@link SSLOptions} at the same time.
164164 *
@@ -171,15 +171,15 @@
171171
172172 /**
173173 * Hook invoked when the cluster is shutting down after a call to {@link Cluster#close()}.
174- * <p>
174+ * <p/>
175175 * This is guaranteed to be called only after all connections have been individually
176176 * closed, and their channels closed, and only once per {@link EventLoopGroup} instance.
177- * <p>
177+ * <p/>
178178 * This gives the implementor a chance to close the {@link EventLoopGroup} properly, if required.
179- * <p>
179+ * <p/>
180180 * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully() graceful shutdown}
181181 * of the passed {@link EventLoopGroup}, then waits uninterruptibly for the shutdown to complete or timeout.
182- * <p>
182+ * <p/>
183183 * Implementation note: if the {@link EventLoopGroup} instance is being shared, or used for other purposes than to
184184 * coordinate Netty events for the current cluster, then it should not be shut down here;
185185 * subclasses would have to override this method accordingly to take the appropriate action.
@@ -192,17 +192,17 @@
192192
193193 /**
194194 * Return the {@link Timer} instance used by Read Timeouts and Speculative Execution.
195- * <p>
195+ * <p/>
196196 * This hook is invoked only once at {@link Cluster} initialization;
197197 * the returned instance will be kept in use throughout the cluster lifecycle.
198- * <p>
198+ * <p/>
199199 * Typically, implementors would return a newly-created instance;
200200 * it is however possible to re-use a shared instance, but in this
201201 * case implementors should also override {@link #onClusterClose(Timer)}
202202 * to prevent the shared instance to be closed when the cluster is closed.
203- * <p>
203+ * <p/>
204204 * The default implementation returns a new instance created by {@link HashedWheelTimer#HashedWheelTimer(ThreadFactory)}.
205- *
205+ *
206206 * @param threadFactory The {@link ThreadFactory} to use when creating a new {@link HashedWheelTimer} instance;
207207 * The driver will provide its own internal thread factory here.
208208 * It is safe to ignore it and use another thread factory.
@@ -214,14 +214,14 @@
214214
215215 /**
216216 * Hook invoked when the cluster is shutting down after a call to {@link Cluster#close()}.
217- * <p>
217+ * <p/>
218218 * This is guaranteed to be called only after all connections have been individually
219219 * closed, and their channels closed, and only once per {@link Timer} instance.
220- * <p>
220+ * <p/>
221221 * This gives the implementor a chance to close the {@link Timer} properly, if required.
222- * <p>
222+ * <p/>
223223 * The default implementation calls a {@link Timer#stop()} of the passed {@link Timer} instance.
224- * <p>
224+ * <p/>
225225 * Implementation note: if the {@link Timer} instance is being shared, or used for other purposes than to
226226 * schedule actions for the current cluster, than it should not be stopped here;
227227 * subclasses would have to override this method accordingly to take the appropriate action.
modified driver-core/src/main/java/com/datastax/driver/core/NettySSLOptions.java +1 −1
@@ -21,7 +21,7 @@
2121
2222 /**
2323 * {@link SSLOptions} implementation based on Netty's SSL context.
24- * <p>
24+ * <p/>
2525 * Netty has the ability to use OpenSSL if available, instead of the JDK's built-in engine. This yields better performance.
2626 */
2727 public class NettySSLOptions implements SSLOptions {
modified driver-core/src/main/java/com/datastax/driver/core/NettyUtil.java +14 −15
@@ -15,10 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.lang.reflect.Constructor;
19-import java.util.Locale;
20-import java.util.concurrent.ThreadFactory;
21-
2218 import com.google.common.base.Throwables;
2319 import io.netty.channel.EventLoopGroup;
2420 import io.netty.channel.nio.NioEventLoopGroup;
@@ -27,6 +23,10 @@
2723 import org.slf4j.Logger;
2824 import org.slf4j.LoggerFactory;
2925
26+import java.lang.reflect.Constructor;
27+import java.util.Locale;
28+import java.util.concurrent.ThreadFactory;
29+
3030 /**
3131 * A set of utilities related to the underlying Netty layer.
3232 */
@@ -45,7 +45,7 @@
4545
4646 private static final Class<? extends SocketChannel> EPOLL_CHANNEL_CLASS;
4747
48- private static final Class[] EVENT_GROUP_ARGUMENTS = { int.class, ThreadFactory.class };
48+ private static final Class[] EVENT_GROUP_ARGUMENTS = {int.class, ThreadFactory.class};
4949
5050 static {
5151 boolean shaded;
@@ -68,13 +68,13 @@
6868 Class<?> epoll = Class.forName("io.netty.channel.epoll.Epoll");
6969 if (FORCE_NIO) {
7070 LOGGER.info("Found Netty's native epoll transport in the classpath, "
71- + "but NIO was forced through the FORCE_NIO system property.");
71+ + "but NIO was forced through the FORCE_NIO system property.");
7272 } else if (!System.getProperty("os.name", "").toLowerCase(Locale.US).equals("linux")) {
7373 LOGGER.warn("Found Netty's native epoll transport, but not running on linux-based operating " +
74- "system. Using NIO instead.");
75- } else if (!(Boolean)epoll.getMethod("isAvailable").invoke(null)) {
74+ "system. Using NIO instead.");
75+ } else if (!(Boolean) epoll.getMethod("isAvailable").invoke(null)) {
7676 LOGGER.warn("Found Netty's native epoll transport in the classpath, but epoll is not available. "
77- + "Using NIO instead.", (Throwable)epoll.getMethod("unavailabilityCause").invoke(null));
77+ + "Using NIO instead.", (Throwable) epoll.getMethod("unavailabilityCause").invoke(null));
7878 } else {
7979 LOGGER.info("Found Netty's native epoll transport in the classpath, using it");
8080 useEpoll = true;
@@ -86,16 +86,16 @@
8686 }
8787 } else {
8888 LOGGER.info("Detected shaded Netty classes in the classpath; native epoll transport will not work properly, "
89- + "defaulting to NIO.");
89+ + "defaulting to NIO.");
9090 }
9191 USE_EPOLL = useEpoll;
9292 Constructor<? extends EventLoopGroup> constructor = null;
9393 Class<? extends SocketChannel> channelClass = null;
9494 if (USE_EPOLL) {
9595 try {
96- channelClass = (Class<? extends SocketChannel>)Class.forName("io.netty.channel.epoll.EpollSocketChannel");
96+ channelClass = (Class<? extends SocketChannel>) Class.forName("io.netty.channel.epoll.EpollSocketChannel");
9797 Class<?> epoolEventLoupGroupClass = Class.forName("io.netty.channel.epoll.EpollEventLoopGroup");
98- constructor = (Constructor<? extends EventLoopGroup>)epoolEventLoupGroupClass.getDeclaredConstructor(EVENT_GROUP_ARGUMENTS);
98+ constructor = (Constructor<? extends EventLoopGroup>) epoolEventLoupGroupClass.getDeclaredConstructor(EVENT_GROUP_ARGUMENTS);
9999 } catch (Exception e) {
100100 throw new AssertionError("Netty's native epoll is in use but cannot locate Epoll classes, this should not happen: " + e);
101101 }
@@ -105,7 +105,6 @@
105105 }
106106
107107 /**
108- *
109108 * @return true if the current driver bundle is using shaded Netty classes, false otherwise.
110109 */
111110
@@ -122,7 +121,7 @@
122121
123122 /**
124123 * Return a new instance of {@link EventLoopGroup}.
125- * <p>
124+ * <p/>
126125 * Returns an instance of {@link io.netty.channel.epoll.EpollEventLoopGroup} if {@link #isEpollAvailable() epoll is available},
127126 * or an instance of {@link NioEventLoopGroup} otherwise.
128127 *
@@ -143,7 +142,7 @@
143142
144143 /**
145144 * Return the SocketChannel class to use.
146- * <p>
145+ * <p/>
147146 * Returns an instance of {@link io.netty.channel.epoll.EpollSocketChannel} if {@link #isEpollAvailable() epoll is available},
148147 * or an instance of {@link NioSocketChannel} otherwise.
149148 *
modified driver-core/src/main/java/com/datastax/driver/core/PagingState.java +14 −16
@@ -16,20 +16,20 @@
1616
1717 package com.datastax.driver.core;
1818
19+import com.datastax.driver.core.exceptions.PagingStateException;
20+import com.datastax.driver.core.utils.Bytes;
21+
1922 import java.nio.ByteBuffer;
2023 import java.security.MessageDigest;
2124 import java.security.NoSuchAlgorithmException;
2225 import java.util.Arrays;
2326
24-import com.datastax.driver.core.exceptions.PagingStateException;
25-import com.datastax.driver.core.utils.Bytes;
26-
2727 /**
2828 * The paging state of a query.
29- *
29+ * <p/>
3030 * This object represents the next page to be fetched if the query is
3131 * multi page. It can be saved and reused later on the same statement.
32- *
32+ * <p/>
3333 * The PagingState can be serialized and deserialized either as a String
3434 * or as a byte array.
3535 *
@@ -59,15 +59,15 @@
5959 int hashSize = pagingStateBB.getShort();
6060 if (pagingSize + hashSize != pagingStateBB.remaining() && pagingSize + hashSize + 2 != pagingStateBB.remaining()) {
6161 throw new PagingStateException("Cannot deserialize paging state, invalid format. "
62- + "The serialized form was corrupted, or not initially generated from a PagingState object.");
62+ + "The serialized form was corrupted, or not initially generated from a PagingState object.");
6363 }
6464 this.pagingState = new byte[pagingSize];
6565 pagingStateBB.get(this.pagingState);
6666 this.hash = new byte[hashSize];
6767 pagingStateBB.get(this.hash);
6868 this.protocolVersion = (pagingStateBB.remaining() > 0)
69- ? ProtocolVersion.fromInt(pagingStateBB.getShort())
70- : ProtocolVersion.V2;
69+ ? ProtocolVersion.fromInt(pagingStateBB.getShort())
70+ : ProtocolVersion.V2;
7171 }
7272
7373 private byte[] hash(Statement statement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
@@ -78,12 +78,12 @@
7878 try {
7979 md = MessageDigest.getInstance("MD5");
8080 if (statement instanceof BoundStatement) {
81- BoundStatement bs = ((BoundStatement)statement);
81+ BoundStatement bs = ((BoundStatement) statement);
8282 md.update(bs.preparedStatement().getQueryString().getBytes());
8383 values = bs.wrapper.values;
8484 } else {
8585 //it is a RegularStatement since Batch statements are not allowed
86- RegularStatement rs = (RegularStatement)statement;
86+ RegularStatement rs = (RegularStatement) statement;
8787 md.update(rs.getQueryString().getBytes());
8888 values = rs.getValues(protocolVersion, codecRegistry);
8989 }
@@ -109,13 +109,13 @@
109109 private ByteBuffer generateCompleteOutput() {
110110 ByteBuffer res = ByteBuffer.allocate(pagingState.length + hash.length + 6);
111111
112- res.putShort((short)pagingState.length);
113- res.putShort((short)hash.length);
112+ res.putShort((short) pagingState.length);
113+ res.putShort((short) hash.length);
114114
115115 res.put(pagingState);
116116 res.put(hash);
117117
118- res.putShort((short)protocolVersion.toInt());
118+ res.putShort((short) protocolVersion.toInt());
119119
120120 res.rewind();
121121
@@ -136,7 +136,6 @@
136136 *
137137 * @param string the string value.
138138 * @return the PagingState object created.
139- *
140139 * @throws PagingStateException if the string does not have the correct format.
141140 */
142141 public static PagingState fromString(String string) {
@@ -145,7 +144,7 @@
145144 return new PagingState(complete);
146145 } catch (Exception e) {
147146 throw new PagingStateException("Cannot deserialize paging state, invalid format. "
148- + "The serialized form was corrupted, or not initially generated from a PagingState object.", e);
147+ + "The serialized form was corrupted, or not initially generated from a PagingState object.", e);
149148 }
150149 }
151150
@@ -163,7 +162,6 @@
163162 *
164163 * @param pagingState The byte array representation.
165164 * @return the PagingState object created.
166- *
167165 * @throws PagingStateException if the byte array does not have the correct format.
168166 */
169167 public static PagingState fromBytes(byte[] pagingState) {
modified driver-core/src/main/java/com/datastax/driver/core/ParseUtils.java +36 −37
@@ -31,27 +31,27 @@
3131 * Valid ISO-8601 patterns for CQL timestamp literals.
3232 */
3333 private static final String[] iso8601Patterns = new String[]{
34- "yyyy-MM-dd HH:mm",
35- "yyyy-MM-dd HH:mm:ss",
36- "yyyy-MM-dd HH:mmZ",
37- "yyyy-MM-dd HH:mm:ssZ",
38- "yyyy-MM-dd HH:mm:ss.SSS",
39- "yyyy-MM-dd HH:mm:ss.SSSZ",
40- "yyyy-MM-dd'T'HH:mm",
41- "yyyy-MM-dd'T'HH:mmZ",
42- "yyyy-MM-dd'T'HH:mm:ss",
43- "yyyy-MM-dd'T'HH:mm:ssZ",
44- "yyyy-MM-dd'T'HH:mm:ss.SSS",
45- "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
46- "yyyy-MM-dd",
47- "yyyy-MM-ddZ"
34+ "yyyy-MM-dd HH:mm",
35+ "yyyy-MM-dd HH:mm:ss",
36+ "yyyy-MM-dd HH:mmZ",
37+ "yyyy-MM-dd HH:mm:ssZ",
38+ "yyyy-MM-dd HH:mm:ss.SSS",
39+ "yyyy-MM-dd HH:mm:ss.SSSZ",
40+ "yyyy-MM-dd'T'HH:mm",
41+ "yyyy-MM-dd'T'HH:mmZ",
42+ "yyyy-MM-dd'T'HH:mm:ss",
43+ "yyyy-MM-dd'T'HH:mm:ssZ",
44+ "yyyy-MM-dd'T'HH:mm:ss.SSS",
45+ "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
46+ "yyyy-MM-dd",
47+ "yyyy-MM-ddZ"
4848 };
4949
5050 /**
5151 * Returns the index of the first character in toParse from idx that is not a "space".
5252 *
5353 * @param toParse the string to skip space on.
54- * @param idx the index to start skipping space from.
54+ * @param idx the index to start skipping space from.
5555 * @return the index of the first character in toParse from idx that is not a "space.
5656 */
5757 public static int skipSpaces(String toParse, int idx) {
@@ -65,11 +65,10 @@
6565 * index of the first character after this value.
6666 *
6767 * @param toParse the string to skip a value form.
68- * @param idx the index to start parsing a value from.
68+ * @param idx the index to start parsing a value from.
6969 * @return the index ending the CQL value starting at {@code idx}.
70- *
7170 * @throws IllegalArgumentException if idx doesn't point to the start of a valid CQL
72- * value.
71+ * value.
7372 */
7473 public static int skipCQLValue(String toParse, int idx) {
7574 if (idx >= toParse.length())
@@ -141,11 +140,10 @@
141140 * index of the first character after this identifier.
142141 *
143142 * @param toParse the string to skip an identifier from.
144- * @param idx the index to start parsing an identifier from.
143+ * @param idx the index to start parsing an identifier from.
145144 * @return the index ending the CQL identifier starting at {@code idx}.
146- *
147145 * @throws IllegalArgumentException if idx doesn't point to the start of a valid CQL
148- * identifier.
146+ * identifier.
149147 */
150148 public static int skipCQLId(String toParse, int idx) {
151149 if (idx >= toParse.length())
@@ -185,8 +183,8 @@
185183 */
186184 public static boolean isIdentifierChar(int c) {
187185 return (c >= '0' && c <= '9')
188- || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
189- || c == '-' || c == '+' || c == '.' || c == '_' || c == '&';
186+ || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
187+ || c == '-' || c == '+' || c == '.' || c == '_' || c == '&';
190188 }
191189
192190 /**
@@ -202,7 +200,7 @@
202200 public static boolean isBlank(int c) {
203201 return c == ' ' || c == '\t' || c == '\n';
204202 }
205-
203+
206204 /**
207205 * Check whether the given string corresponds
208206 * to a valid CQL long literal.
@@ -260,13 +258,13 @@
260258
261259 /**
262260 * Parse the given string as a date, using one of the accepted ISO-8601 date patterns.
263- * <p>
261+ * <p/>
264262 * This method is adapted from Apache Commons {@code DateUtils.parseStrictly()} method (that is used Cassandra side
265263 * to parse date strings)..
266264 *
265+ * @throws ParseException If the given string is not a valid ISO-8601 date.
267266 * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps">Working with timestamps</a>
268267 * section of CQL specification.
269- * @throws ParseException If the given string is not a valid ISO-8601 date.
270268 */
271269 public static Date parseDate(String str) throws ParseException {
272270 SimpleDateFormat parser = new SimpleDateFormat();
@@ -295,13 +293,13 @@
295293
296294 /**
297295 * Parse the given string as a date, using the supplied date pattern.
298- * <p>
296+ * <p/>
299297 * This method is adapted from Apache Commons {@code DateUtils.parseStrictly()} method (that is used Cassandra side
300298 * to parse date strings)..
301299 *
300+ * @throws ParseException If the given string cannot be parsed with the given pattern.
302301 * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps">Working with timestamps</a>
303302 * section of CQL specification.
304- * @throws ParseException If the given string cannot be parsed with the given pattern.
305303 */
306304 public static Date parseDate(String str, String pattern) throws ParseException {
307305 SimpleDateFormat parser = new SimpleDateFormat();
@@ -328,7 +326,7 @@
328326
329327 /**
330328 * Parse the given string as a time, using the following time pattern: {@code hh:mm:ss[.fffffffff]}.
331- * <p>
329+ * <p/>
332330 * This method is loosely based on {@code java.sql.Timestamp}.
333331 *
334332 * @param str The string to parse.
@@ -406,16 +404,16 @@
406404 * section of CQL specification.
407405 */
408406 public static String formatTime(long value) {
409- int nano = (int)(value % 1000000000);
407+ int nano = (int) (value % 1000000000);
410408 value -= nano;
411409 value /= 1000000000;
412- int seconds = (int)(value % 60);
410+ int seconds = (int) (value % 60);
413411 value -= seconds;
414412 value /= 60;
415- int minutes = (int)(value % 60);
413+ int minutes = (int) (value % 60);
416414 value -= minutes;
417415 value /= 60;
418- int hours = (int)(value % 24);
416+ int hours = (int) (value % 24);
419417 value -= hours;
420418 value /= 24;
421419 assert (value == 0);
@@ -435,13 +433,13 @@
435433 * {@code String.replace()} is a bit too inefficient (see JAVA-67).
436434 * This methods is specially useful for escaping single quotes
437435 * in CQL strings:
438- *
436+ * <p/>
439437 * <pre>{@code
440438 * ParseUtils.replaceChar(value, '\'', "''");
441439 * }</pre>
442440 *
443- * @param text The text.
444- * @param search The character to search for.
441+ * @param text The text.
442+ * @param search The character to search for.
445443 * @param replacement The replacement.
446444 * @return The text with all occurrences of {@code search} replaced with {@code replacement}.
447445 */
@@ -479,6 +477,7 @@
479477 sb.append(String.format("%0" + digits + "d", value));
480478 }
481479
482- private ParseUtils() {}
480+ private ParseUtils() {
481+ }
483482
484483 }
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,11 +306,11 @@
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
318316 @Override
modified driver-core/src/main/java/com/datastax/driver/core/PlainTextAuthProvider.java +9 −8
@@ -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.
@@ -72,7 +73,7 @@
7273 * Uses the supplied credentials and the SASL PLAIN mechanism to login
7374 * to the server.
7475 *
75- * @param host the Cassandra host with which we want to authenticate
76+ * @param host the Cassandra host with which we want to authenticate
7677 * @param authenticator the configured authenticator on the host
7778 * @return an Authenticator instance which can be used to perform
7879 * authentication negotiations on behalf of the client
@@ -118,7 +119,7 @@
118119
119120 Map<String, String> getCredentials() {
120121 return ImmutableMap.of("username", new String(username, Charsets.UTF_8),
121- "password", new String(password, Charsets.UTF_8));
122+ "password", new String(password, Charsets.UTF_8));
122123 }
123124 }
124125 }
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +83 −96
@@ -15,35 +15,35 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Map;
19-import java.util.concurrent.Executor;
20-
2118 import com.google.common.base.Preconditions;
2219 import com.google.common.collect.ImmutableMap;
2320 import com.google.common.util.concurrent.MoreExecutors;
2421
22+import java.util.Map;
23+import java.util.concurrent.Executor;
24+
2525 import static com.datastax.driver.core.HostDistance.LOCAL;
2626 import static com.datastax.driver.core.HostDistance.REMOTE;
2727
2828 /**
2929 * Options related to connection pooling.
30- * <p>
30+ * <p/>
3131 * The driver uses connections in an asynchronous manner, meaning that
3232 * multiple requests can be submitted on the same connection at the same
3333 * time. Therefore only a relatively small number of connections is needed.
3434 * For each host, the driver uses a connection pool that may have a variable
3535 * size (it will automatically adjust to the current load).
36- * <p>
36+ * <p/>
3737 * With {@code ProtocolVersion#V2} or below, there are at most 128 simultaneous
3838 * requests per connection, so the pool defaults to a variable size. You will
3939 * typically raise the maximum capacity by adding more connections with
4040 * {@link #setMaxConnectionsPerHost(HostDistance, int)}.
41- * <p>
41+ * <p/>
4242 * With {@code ProtocolVersion#V3} or above, there are up to 32768 requests per
4343 * connection, and the pool defaults to a fixed size of 1. You will typically
4444 * raise the maximum capacity by allowing more simultaneous requests per connection
4545 * ({@link #setMaxRequestsPerConnection(HostDistance, int)}).
46- * <p>
46+ * <p/>
4747 * All parameters can be separately set for {@code LOCAL} and
4848 * {@code REMOTE} hosts ({@link HostDistance}). For {@code IGNORED} hosts,
4949 * no connections are created so these settings cannot be changed.
@@ -53,27 +53,27 @@
5353 static final int UNSET = Integer.MIN_VALUE;
5454
5555 private static final Map<ProtocolVersion, Map<String, Integer>> DEFAULTS = ImmutableMap.<ProtocolVersion, Map<String, Integer>>of(
56- ProtocolVersion.V2, ImmutableMap.<String, Integer>builder()
57- .put("corePoolLocal", 2)
58- .put("maxPoolLocal", 8)
59- .put("corePoolRemote", 1)
60- .put("maxPoolRemote", 2)
61- .put("newConnectionThresholdLocal", 100)
62- .put("newConnectionThresholdRemote", 100)
63- .put("maxRequestsPerConnectionLocal", 128)
64- .put("maxRequestsPerConnectionRemote", 128)
65- .build(),
66-
67- ProtocolVersion.V3, ImmutableMap.<String, Integer>builder()
68- .put("corePoolLocal", 1)
69- .put("maxPoolLocal", 1)
70- .put("corePoolRemote", 1)
71- .put("maxPoolRemote", 1)
72- .put("newConnectionThresholdLocal", 800)
73- .put("newConnectionThresholdRemote", 200)
74- .put("maxRequestsPerConnectionLocal", 1024)
75- .put("maxRequestsPerConnectionRemote", 256)
76- .build()
56+ ProtocolVersion.V2, ImmutableMap.<String, Integer>builder()
57+ .put("corePoolLocal", 2)
58+ .put("maxPoolLocal", 8)
59+ .put("corePoolRemote", 1)
60+ .put("maxPoolRemote", 2)
61+ .put("newConnectionThresholdLocal", 100)
62+ .put("newConnectionThresholdRemote", 100)
63+ .put("maxRequestsPerConnectionLocal", 128)
64+ .put("maxRequestsPerConnectionRemote", 128)
65+ .build(),
66+
67+ ProtocolVersion.V3, ImmutableMap.<String, Integer>builder()
68+ .put("corePoolLocal", 1)
69+ .put("maxPoolLocal", 1)
70+ .put("corePoolRemote", 1)
71+ .put("maxPoolRemote", 1)
72+ .put("newConnectionThresholdLocal", 800)
73+ .put("newConnectionThresholdRemote", 200)
74+ .put("maxRequestsPerConnectionLocal", 1024)
75+ .put("maxRequestsPerConnectionRemote", 256)
76+ .build()
7777 );
7878
7979 private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
@@ -87,9 +87,9 @@
8787
8888 // The defaults for these fields depend on the protocol version, which is only known after control connection initialization.
8989 // Yet if the user set them before initialization, we want to keep their values. So we use -1 to mean "uninitialized".
90- private final int[] coreConnections = new int[]{ UNSET, UNSET, 0 };
91- private final int[] maxConnections = new int[]{ UNSET, UNSET, 0 };
92- private final int[] newConnectionThreshold = new int[]{ UNSET, UNSET, 0 };
90+ private final int[] coreConnections = new int[]{UNSET, UNSET, 0};
91+ private final int[] maxConnections = new int[]{UNSET, UNSET, 0};
92+ private final int[] newConnectionThreshold = new int[]{UNSET, UNSET, 0};
9393 private volatile int maxRequestsPerConnectionLocal = UNSET;
9494 private volatile int maxRequestsPerConnectionRemote = UNSET;
9595
@@ -118,24 +118,22 @@
118118
119119 /**
120120 * Sets the core number of connections per host.
121- * <p>
121+ * <p/>
122122 * For the provided {@code distance}, this corresponds to the number of
123123 * connections initially created and kept open to each host of that
124124 * distance.
125- * <p>
125+ * <p/>
126126 * The default value is:
127127 * <ul>
128- * <li>with {@code ProtocolVersion#V2} or below: 2 for {@code LOCAL} hosts and 1 for {@code REMOTE} hosts.</li>
129- * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
128+ * <li>with {@code ProtocolVersion#V2} or below: 2 for {@code LOCAL} hosts and 1 for {@code REMOTE} hosts.</li>
129+ * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
130130 * </ul>
131131 *
132- * @param distance the {@code HostDistance} for which to set this threshold.
132+ * @param distance the {@code HostDistance} for which to set this threshold.
133133 * @param newCoreConnections the value to set
134134 * @return this {@code PoolingOptions}.
135- *
136135 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
137- * or if {@code newCoreConnections} is greater than the maximum value for this distance.
138- *
136+ * or if {@code newCoreConnections} is greater than the maximum value for this distance.
139137 * @see #setConnectionsPerHost(HostDistance, int, int)
140138 */
141139 public synchronized PoolingOptions setCoreConnectionsPerHost(HostDistance distance, int newCoreConnections) {
@@ -164,23 +162,21 @@
164162
165163 /**
166164 * Sets the maximum number of connections per host.
167- * <p>
165+ * <p/>
168166 * For the provided {@code distance}, this corresponds to the maximum
169167 * number of connections that can be created per host at that distance.
170- * <p>
168+ * <p/>
171169 * The default value is:
172170 * <ul>
173- * <li>with {@code ProtocolVersion#V2} or below: 8 for {@code LOCAL} hosts and 2 for {@code REMOTE} hosts.</li>
174- * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
171+ * <li>with {@code ProtocolVersion#V2} or below: 8 for {@code LOCAL} hosts and 2 for {@code REMOTE} hosts.</li>
172+ * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
175173 * </ul>
176174 *
177- * @param distance the {@code HostDistance} for which to set this threshold.
175+ * @param distance the {@code HostDistance} for which to set this threshold.
178176 * @param newMaxConnections the value to set
179177 * @return this {@code PoolingOptions}.
180- *
181178 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
182- * or if {@code newMaxConnections} is less than the core value for this distance.
183- *
179+ * or if {@code newMaxConnections} is less than the core value for this distance.
184180 * @see #setConnectionsPerHost(HostDistance, int, int)
185181 */
186182 public synchronized PoolingOptions setMaxConnectionsPerHost(HostDistance distance, int newMaxConnections) {
@@ -196,17 +192,16 @@
196192
197193 /**
198194 * Sets the core and maximum number of connections per host in one call.
199- * <p>
195+ * <p/>
200196 * This is a convenience method that is equivalent to calling {@link #setCoreConnectionsPerHost(HostDistance, int)}
201197 * and {@link #setMaxConnectionsPerHost(HostDistance, int)}.
202198 *
203199 * @param distance the {@code HostDistance} for which to set these threshold.
204- * @param core the core number of connections.
205- * @param max the max number of connections.
200+ * @param core the core number of connections.
201+ * @param max the max number of connections.
206202 * @return this {@code PoolingOptions}.
207- *
208203 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
209- * or if {@code core} > {@code max}.
204+ * or if {@code core} > {@code max}.
210205 */
211206 public synchronized PoolingOptions setConnectionsPerHost(HostDistance distance, int core, int max) {
212207 if (distance == HostDistance.IGNORED)
@@ -223,7 +218,6 @@
223218 *
224219 * @param distance the {@code HostDistance} for which to return this threshold.
225220 * @return the configured threshold, or the default one if none have been set.
226- *
227221 * @see #setNewConnectionThreshold(HostDistance, int)
228222 */
229223 public int getNewConnectionThreshold(HostDistance distance) {
@@ -232,29 +226,28 @@
232226
233227 /**
234228 * Sets the threshold that triggers the creation of a new connection to a host.
235- * <p>
229+ * <p/>
236230 * A new connection gets created if:
237231 * <ul>
238- * <li>N connections are open</li>
239- * <li><tt>N < {@link #getMaxConnectionsPerHost(HostDistance)}</tt></li>
240- * <li>the number of active requests is more than
241- * <tt>(N - 1) * {@link #getMaxRequestsPerConnection(HostDistance)} + {@link #getNewConnectionThreshold(HostDistance)}</tt>
242- * </li>
232+ * <li>N connections are open</li>
233+ * <li><tt>N < {@link #getMaxConnectionsPerHost(HostDistance)}</tt></li>
234+ * <li>the number of active requests is more than
235+ * <tt>(N - 1) * {@link #getMaxRequestsPerConnection(HostDistance)} + {@link #getNewConnectionThreshold(HostDistance)}</tt>
236+ * </li>
243237 * </ul>
244238 * In other words, if all but the last connection are full, and the last connection is above this threshold.
245- * <p>
239+ * <p/>
246240 * The default value is:
247241 * <ul>
248- * <li>with {@code ProtocolVersion#V2} or below: 100 for all hosts.</li>
249- * <li>with {@code ProtocolVersion#V3} or above: 800 for {@code LOCAL} hosts and 200 for {@code REMOTE} hosts.</li>
242+ * <li>with {@code ProtocolVersion#V2} or below: 100 for all hosts.</li>
243+ * <li>with {@code ProtocolVersion#V3} or above: 800 for {@code LOCAL} hosts and 200 for {@code REMOTE} hosts.</li>
250244 * </ul>
251245 *
252246 * @param distance the {@code HostDistance} for which to configure this threshold.
253247 * @param newValue the value to set (between 0 and 128).
254248 * @return this {@code PoolingOptions}.
255- *
256249 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code maxSimultaneousRequests}
257- * is not in range, or if {@code newValue} is less than the minimum value for this distance.
250+ * is not in range, or if {@code newValue} is less than the minimum value for this distance.
258251 */
259252 public synchronized PoolingOptions setNewConnectionThreshold(HostDistance distance, int newValue) {
260253 if (distance == HostDistance.IGNORED)
@@ -270,7 +263,6 @@
270263 *
271264 * @param distance the {@code HostDistance} for which to return this threshold.
272265 * @return the maximum number of requests per connection at distance {@code distance}.
273- *
274266 * @see #setMaxRequestsPerConnection(HostDistance, int)
275267 */
276268 public int getMaxRequestsPerConnection(HostDistance distance) {
@@ -286,24 +278,23 @@
286278
287279 /**
288280 * Sets the maximum number of requests per connection.
289- * <p>
281+ * <p/>
290282 * The default value is:
291283 * <ul>
292- * <li>with {@code ProtocolVersion#V2} or below: 128 for all hosts (there should not be any reason to change this).</li>
293- * <li>with {@code ProtocolVersion#V3} or above: 1024 for {@code LOCAL} hosts and 256 for {@code REMOTE} hosts.
294- * These values were chosen so that the default V2 and V3 configuration generate the same load on a Cassandra cluster.
295- * Protocol V3 can go much higher (up to 32768), so if your number of clients is low, don't hesitate to experiment with
296- * higher values. If you have more than one connection per host, consider also adjusting
297- * {@link #setNewConnectionThreshold(HostDistance, int)}.
298- * </li>
284+ * <li>with {@code ProtocolVersion#V2} or below: 128 for all hosts (there should not be any reason to change this).</li>
285+ * <li>with {@code ProtocolVersion#V3} or above: 1024 for {@code LOCAL} hosts and 256 for {@code REMOTE} hosts.
286+ * These values were chosen so that the default V2 and V3 configuration generate the same load on a Cassandra cluster.
287+ * Protocol V3 can go much higher (up to 32768), so if your number of clients is low, don't hesitate to experiment with
288+ * higher values. If you have more than one connection per host, consider also adjusting
289+ * {@link #setNewConnectionThreshold(HostDistance, int)}.
290+ * </li>
299291 * </ul>
300292 *
301- * @param distance the {@code HostDistance} for which to set this threshold.
293+ * @param distance the {@code HostDistance} for which to set this threshold.
302294 * @param newMaxRequests the value to set.
303295 * @return this {@code PoolingOptions}.
304- *
305296 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
306- * or if {@code newMaxConnections} is not within the allowed range.
297+ * or if {@code newMaxConnections} is not within the allowed range.
307298 */
308299 public PoolingOptions setMaxRequestsPerConnection(HostDistance distance, int newMaxRequests) {
309300 checkRequestsPerConnectionRange(newMaxRequests, "Max requests per connection", distance);
@@ -332,13 +323,12 @@
332323
333324 /**
334325 * Sets the timeout before an idle connection is removed.
335- * <p>
326+ * <p/>
336327 * The order of magnitude should be a few minutes (the default is 120 seconds). The
337328 * timeout that triggers the removal has a granularity of 10 seconds.
338329 *
339330 * @param idleTimeoutSeconds the new timeout in seconds.
340331 * @return this {@code PoolingOptions}.
341- *
342332 * @throws IllegalArgumentException if the timeout is negative.
343333 */
344334 public PoolingOptions setIdleTimeoutSeconds(int idleTimeoutSeconds) {
@@ -359,15 +349,14 @@
359349
360350 /**
361351 * Sets the timeout when trying to acquire a connection from a host's pool.
362- * <p>
352+ * <p/>
363353 * If no connection is available within that time, the driver will try the
364354 * next host from the query plan.
365- * <p>
355+ * <p/>
366356 * The default is 5 seconds. If this option is set to zero, the driver won't wait at all.
367357 *
368358 * @param poolTimeoutMillis the new value in milliseconds.
369359 * @return this {@code PoolingOptions}
370- *
371360 * @throws IllegalArgumentException if the timeout is negative.
372361 */
373362 public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
@@ -379,6 +368,7 @@
379368
380369 /**
381370 * Returns the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive.
371+ *
382372 * @return the interval.
383373 */
384374 public int getHeartbeatIntervalSeconds() {
@@ -387,17 +377,16 @@
387377
388378 /**
389379 * Sets the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive.
390- * <p>
380+ * <p/>
391381 * This is an application-level keep-alive, provided for convenience since adjusting the TCP keep-alive might not be
392382 * practical in all environments.
393- * <p>
383+ * <p/>
394384 * This option should be set higher than {@link SocketOptions#getReadTimeoutMillis()}.
395- * <p>
385+ * <p/>
396386 * The default value for this option is 30 seconds.
397387 *
398388 * @param heartbeatIntervalSeconds the new value in seconds. If set to 0, it will disable the feature.
399389 * @return this {@code PoolingOptions}
400- *
401390 * @throws IllegalArgumentException if the interval is negative.
402391 */
403392 public PoolingOptions setHeartbeatIntervalSeconds(int heartbeatIntervalSeconds) {
@@ -420,11 +409,11 @@
420409
421410 /**
422411 * Sets the executor to use for connection initialization.
423- * <p>
412+ * <p/>
424413 * Connections are open in a completely asynchronous manner. Since initializing the transport
425414 * requires separate CQL queries, the futures representing the completion of these queries are
426415 * transformed and chained. This executor is where these transformations happen.
427- * <p>
416+ * <p/>
428417 * <b>This is an advanced option, which should be rarely needed in practice.</b> It defaults to
429418 * Guava's {@code MoreExecutors.sameThreadExecutor()}, which results in running the transformations
430419 * on the network I/O threads; this is fine if the transformations are fast and not I/O bound
@@ -435,7 +424,6 @@
435424 *
436425 * @param initializationExecutor the executor to use
437426 * @return this {@code PoolingOptions}
438- *
439427 * @throws java.lang.NullPointerException if the executor is null
440428 */
441429 public PoolingOptions setInitializationExecutor(Executor initializationExecutor) {
@@ -448,8 +436,8 @@
448436 this.protocolVersion = protocolVersion;
449437
450438 ProtocolVersion referenceVersion = (protocolVersion.compareTo(ProtocolVersion.V2) <= 0)
451- ? ProtocolVersion.V2
452- : ProtocolVersion.V3;
439+ ? ProtocolVersion.V2
440+ : ProtocolVersion.V3;
453441 Map<String, Integer> defaults = DEFAULTS.get(referenceVersion);
454442
455443 if (coreConnections[LOCAL.ordinal()] == UNSET)
@@ -485,7 +473,7 @@
485473 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
486474 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
487475 * hosts and to drop/add connections to each hosts according to the computed distance.
488- * <p>
476+ * <p/>
489477 * Note that, due to backward compatibility issues, this method is not interruptible. If the
490478 * caller thread gets interrupted, the method will complete and only then re-interrupt the
491479 * thread (which you can check with {@code Thread.currentThread().isInterrupted()}).
@@ -498,7 +486,6 @@
498486 * Requests the driver to re-evaluate the {@link HostDistance} for a given node.
499487 *
500488 * @param host the host to refresh.
501- *
502489 * @see #refreshConnectedHosts()
503490 */
504491 public void refreshConnectedHost(Host host) {
@@ -508,18 +495,18 @@
508495 private void checkRequestsPerConnectionRange(int value, String description, HostDistance distance) {
509496 // If we don't know the protocol version yet, use the highest possible upper bound, this will get checked again when possible
510497 int max = (protocolVersion == null || protocolVersion.compareTo(ProtocolVersion.V3) >= 0)
511- ? StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3
512- : StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2;
498+ ? StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3
499+ : StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2;
513500
514501 if (value < 0 || value > max)
515502 throw new IllegalArgumentException(String.format("%s for %s hosts must be in the range (0, %d)",
516- description, distance, max));
503+ description, distance, max));
517504 }
518505
519506 private static void checkConnectionsPerHostOrder(int core, int max, HostDistance distance) {
520507 if (core > max)
521508 throw new IllegalArgumentException(String.format("Core connections for %s hosts must be less than max (%d > %d)",
522- distance, core, max));
509+ distance, core, max));
523510 }
524511
525512 /**
modified driver-core/src/main/java/com/datastax/driver/core/PreparedId.java +2 −4
@@ -18,8 +18,7 @@
1818 /**
1919 * Identifies a PreparedStatement.
2020 */
21-public class PreparedId
22-{
21+public class PreparedId {
2322 // This class is mostly here to group PreparedStatement data that are need for
2423 // execution but that we don't want to expose publicly (see JAVA-195)
2524 final MD5Digest id;
@@ -30,8 +29,7 @@
3029 final int[] routingKeyIndexes;
3130 final ProtocolVersion protocolVersion;
3231
33- PreparedId(MD5Digest id, ColumnDefinitions metadata, ColumnDefinitions resultSetMetadata, int[] routingKeyIndexes, ProtocolVersion protocolVersion)
34- {
32+ PreparedId(MD5Digest id, ColumnDefinitions metadata, ColumnDefinitions resultSetMetadata, int[] routingKeyIndexes, ProtocolVersion protocolVersion) {
3533 this.id = id;
3634 this.metadata = metadata;
3735 this.resultSetMetadata = resultSetMetadata;
modified driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java +37 −41
@@ -15,21 +15,21 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Map;
20-
2118 import com.datastax.driver.core.exceptions.InvalidTypeException;
2219 import com.datastax.driver.core.policies.RetryPolicy;
2320
21+import java.nio.ByteBuffer;
22+import java.util.Map;
23+
2424 /**
2525 * Represents a prepared statement, a query with bound variables that has been
2626 * prepared (pre-parsed) by the database.
27- * <p>
27+ * <p/>
2828 * A prepared statement can be executed once concrete values have been provided
2929 * for the bound variables. A prepared statement and the values for its
3030 * bound variables constitute a BoundStatement and can be executed (by
3131 * {@link Session#execute}).
32- * <p>
32+ * <p/>
3333 * A {@code PreparedStatement} object allows you to define specific defaults
3434 * for the different properties of a {@link Statement} (Consistency level, tracing, ...),
3535 * in which case those properties will be inherited as default by every
@@ -51,35 +51,33 @@
5151 /**
5252 * Creates a new BoundStatement object and bind its variables to the
5353 * provided values.
54- * <p>
54+ * <p/>
5555 * While the number of {@code values} cannot be greater than the number of bound
5656 * variables, the number of {@code values} may be fewer than the number of bound
5757 * variables. In that case, the remaining variables will have to be bound
5858 * to values by another mean because the resulting {@code BoundStatement}
5959 * being executable.
60- * <p>
60+ * <p/>
6161 * This method is a convenience for {@code new BoundStatement(this).bind(...)}.
6262 *
6363 * @param values the values to bind to the variables of the newly created
64- * BoundStatement.
64+ * BoundStatement.
6565 * @return the newly created {@code BoundStatement} with its variables
6666 * bound to {@code values}.
67- *
6867 * @throws IllegalArgumentException if more {@code values} are provided
69- * than there is of bound variables in this statement.
70- * @throws InvalidTypeException if any of the provided value is not of
71- * correct type to be bound to the corresponding bind variable.
72- * @throws NullPointerException if one of {@code values} is a collection
73- * (List, Set or Map) containing a null value. Nulls are not supported in
74- * collections by CQL.
75- *
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.
7674 * @see BoundStatement#bind
7775 */
7876 public BoundStatement bind(Object... values);
7977
8078 /**
8179 * Creates a new BoundStatement object for this prepared statement.
82- * <p>
80+ * <p/>
8381 * This method do not bind any values to any of the prepared variables. Said
8482 * values need to be bound on the resulting statement using BoundStatement's
8583 * setters methods ({@link BoundStatement#setInt}, {@link BoundStatement#setLong}, ...).
@@ -90,23 +88,22 @@
9088
9189 /**
9290 * Sets the routing key for this prepared statement.
93- * <p>
91+ * <p/>
9492 * While you can provide a fixed routing key for all executions of this prepared
9593 * statement with this method, it is not mandatory to provide
9694 * one through this method. This method should only be used
9795 * if the partition key of the prepared query is not part of the prepared
9896 * variables (that is if the partition key is fixed).
99- * <p>
97+ * <p/>
10098 * Note that if the partition key is part of the prepared variables, the
10199 * routing key will be automatically computed once those variables are bound.
102- * <p>
100+ * <p/>
103101 * If the partition key is neither fixed nor part of the prepared variables (e.g.
104102 * a composite partition key where only some of the components are bound), the
105103 * routing key can also be set on each bound statement.
106104 *
107105 * @param routingKey the raw (binary) value to use as routing key.
108106 * @return this {@code PreparedStatement} object.
109- *
110107 * @see Statement#getRoutingKey
111108 * @see BoundStatement#getRoutingKey
112109 */
@@ -114,15 +111,14 @@
114111
115112 /**
116113 * Sets the routing key for this query.
117- * <p>
114+ * <p/>
118115 * See {@link #setRoutingKey(ByteBuffer)} for more information. This
119116 * method is a variant for when the query partition key is composite and
120117 * the routing key must be built from multiple values.
121118 *
122119 * @param routingKeyComponents the raw (binary) values to compose to obtain
123- * the routing key.
120+ * the routing key.
124121 * @return this {@code PreparedStatement} object.
125- *
126122 * @see Statement#getRoutingKey
127123 */
128124 public PreparedStatement setRoutingKey(ByteBuffer... routingKeyComponents);
@@ -138,10 +134,10 @@
138134 /**
139135 * Sets a default consistency level for all bound statements
140136 * created from this prepared statement.
141- * <p>
137+ * <p/>
142138 * If no consistency level is set through this method, the bound statement
143139 * created from this object will use the default consistency level (ONE).
144- * <p>
140+ * <p/>
145141 * Changing the default consistency level is not retroactive, it only
146142 * applies to BoundStatement created after the change.
147143 *
@@ -162,18 +158,17 @@
162158 /**
163159 * Sets a default serial consistency level for all bound statements
164160 * created from this prepared statement.
165- * <p>
161+ * <p/>
166162 * If no serial consistency level is set through this method, the bound statement
167163 * created from this object will use the default serial consistency level (SERIAL).
168- * <p>
164+ * <p/>
169165 * Changing the default serial consistency level is not retroactive, it only
170166 * applies to BoundStatement created after the change.
171167 *
172168 * @param serialConsistency the default serial consistency level to set.
173169 * @return this {@code PreparedStatement} object.
174- *
175170 * @throws IllegalArgumentException if {@code serialConsistency} is not one of
176- * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
171+ * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
177172 */
178173 public PreparedStatement setSerialConsistencyLevel(ConsistencyLevel serialConsistency);
179174
@@ -189,7 +184,7 @@
189184 /**
190185 * Returns the string of the query that was prepared to yield this {@code
191186 * PreparedStatement}.
192- * <p>
187+ * <p/>
193188 * Note that a CQL3 query may be implicitly applied to the current keyspace
194189 * (that is, if the keyspace is not explicitly qualified in the query
195190 * itself). For prepared queries, the current keyspace used is the one at
@@ -242,7 +237,7 @@
242237 /**
243238 * Convenience method to set a default retry policy for the {@code BoundStatement}
244239 * created from this prepared statement.
245- * <p>
240+ * <p/>
246241 * Note that this method is completely optional. By default, the retry policy
247242 * used is the one returned {@link com.datastax.driver.core.policies.Policies#getRetryPolicy}
248243 * in the cluster configuration. This method is only useful if you want
@@ -274,17 +269,17 @@
274269 * Return the incoming payload, that is, the payload that the server
275270 * sent back with its {@code PREPARED} response, if any,
276271 * or {@code null}, if the server did not include any custom payload.
277- * <p>
272+ * <p/>
278273 * Note that if an incoming payload is present,
279274 * and if no outgoing payload has been {@link #setOutgoingPayload(Map) explicitly set}, then each time
280275 * a {@link BoundStatement} is created (with either {@link #bind()} or {@link #bind(Object...)}),
281276 * the resulting {@link BoundStatement} will inherit from this value
282277 * as its default outgoing payload.
283- * <p>
278+ * <p/>
284279 * Implementors should return a read-only view of the original map, but even though,
285280 * its values would remain inherently mutable.
286281 * Callers should take care not to modify the returned map in any way.
287- * <p>
282+ * <p/>
288283 * This feature is only available with {@link ProtocolVersion#V4} or above; with lower
289284 * versions, this method will always return {@code null}.
290285 *
@@ -296,17 +291,18 @@
296291
297292 /**
298293 * Return the outgoing payload currently associated with this statement.
299- * <p>
294+ * <p/>
300295 * If this is set to a non-null value, each time a {@link BoundStatement} is
301296 * created (with either {@link #bind()} or {@link #bind(Object...)}),
302297 * the resulting {@link BoundStatement} will inherit from this value
303298 * as its default outgoing payload.
304- * <p>
299+ * <p/>
305300 * Implementors should return a read-only view of the original map, but even though,
306301 * its values would remain inherently mutable.
307302 * Callers should take care not to modify the returned map in any way.
308- * <p>
303+ * <p/>
309304 * This feature is only available with {@link ProtocolVersion#V4} or above.
305+ *
310306 * @return this statement's outgoing payload, if any, or {@code null} if no outgoing payload is set
311307 * @since 2.2
312308 */
@@ -314,16 +310,16 @@
314310
315311 /**
316312 * Associate the given payload with this prepared statement.
317- * <p>
313+ * <p/>
318314 * If this is set to a non-null value, each time a {@link BoundStatement} is
319315 * created (with either {@link #bind()} or {@link #bind(Object...)}),
320316 * the resulting {@link BoundStatement} will inherit from this value
321317 * as its default outgoing payload.
322- * <p>
318+ * <p/>
323319 * Implementors should make a defensive, thread-safe copy of the given map, but even though,
324320 * its values would remain inherently mutable.
325321 * Callers should take care not to modify the original map once it is passed to this method.
326- * <p>
322+ * <p/>
327323 * This feature is only available with {@link ProtocolVersion#V4} or above.
328324 * Trying to include custom payloads in requests sent by the driver
329325 * under lower protocol versions will result in an
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolEvent.java +9 −12
@@ -15,20 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import io.netty.buffer.ByteBuf;
19+
1820 import java.net.InetSocketAddress;
1921 import java.util.Collections;
2022 import java.util.List;
2123
22-import io.netty.buffer.ByteBuf;
23-
24-import static com.datastax.driver.core.SchemaElement.AGGREGATE;
25-import static com.datastax.driver.core.SchemaElement.FUNCTION;
26-import static com.datastax.driver.core.SchemaElement.KEYSPACE;
27-import static com.datastax.driver.core.SchemaElement.TABLE;
24+import static com.datastax.driver.core.SchemaElement.*;
2825
2926 class ProtocolEvent {
3027
31- public enum Type { TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE }
28+ public enum Type {TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE}
3229
3330 public final Type type;
3431
@@ -49,7 +46,7 @@
4946 }
5047
5148 public static class TopologyChange extends ProtocolEvent {
52- public enum Change { NEW_NODE, REMOVED_NODE, MOVED_NODE }
49+ public enum Change {NEW_NODE, REMOVED_NODE, MOVED_NODE}
5350
5451 public final Change change;
5552 public final InetSocketAddress node;
@@ -75,7 +72,7 @@
7572
7673 public static class StatusChange extends ProtocolEvent {
7774
78- public enum Status { UP, DOWN }
75+ public enum Status {UP, DOWN}
7976
8077 public final Status status;
8178 public final InetSocketAddress node;
@@ -101,7 +98,7 @@
10198
10299 public static class SchemaChange extends ProtocolEvent {
103100
104- public enum Change { CREATED, UPDATED, DROPPED }
101+ public enum Change {CREATED, UPDATED, DROPPED}
105102
106103 public final Change change;
107104 public final SchemaElement targetType;
@@ -140,8 +137,8 @@
140137 targetKeyspace = CBUtil.readString(bb);
141138 targetName = (targetType == KEYSPACE) ? "" : CBUtil.readString(bb);
142139 targetSignature = (targetType == FUNCTION || targetType == AGGREGATE)
143- ? CBUtil.readStringList(bb)
144- : Collections.<String>emptyList();
140+ ? CBUtil.readStringList(bb)
141+ : Collections.<String>emptyList();
145142 return new SchemaChange(change, targetType, targetKeyspace, targetName, targetSignature);
146143 default:
147144 throw version.unsupported();
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +26 −20
@@ -26,21 +26,27 @@
2626 * Compression supported by the Cassandra binary protocol.
2727 */
2828 public enum Compression {
29- /** No compression */
29+ /**
30+ * No compression
31+ */
3032 NONE("") {
3133 @Override
3234 FrameCompressor compressor() {
3335 return null;
3436 }
3537 },
36- /** Snappy compression */
38+ /**
39+ * Snappy compression
40+ */
3741 SNAPPY("snappy") {
3842 @Override
3943 FrameCompressor compressor() {
4044 return FrameCompressor.SnappyCompressor.instance;
4145 }
4246 },
43- /** LZ4 compression */
47+ /**
48+ * LZ4 compression
49+ */
4450 LZ4("lz4") {
4551 @Override
4652 FrameCompressor compressor() {
@@ -68,7 +74,9 @@
6874 public String toString() {
6975 return protocolName;
7076 }
71- };
77+ }
78+
79+ ;
7280
7381 /**
7482 * The default port for Cassandra native binary protocol: 9042.
@@ -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,14 +125,14 @@
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 {@code null}, in which case the
122- * version used will be the biggest version supported by the <em>first</em> node the driver connects to.
123- * See {@link Cluster.Builder#withProtocolVersion} for more details.
124- * @param sslOptions the SSL options to use. Use {@code null} if SSL is not
125- * to be used.
126- * @param authProvider the {@code AuthProvider} to use for authentication against
127- * the Cassandra nodes.
130+ * version used will be the biggest version supported by the <em>first</em> node the driver connects to.
131+ * See {@link Cluster.Builder#withProtocolVersion} for more details.
132+ * @param sslOptions the SSL options to use. Use {@code null} if SSL is not
133+ * to be used.
134+ * @param authProvider the {@code AuthProvider} to use for authentication against
135+ * the Cassandra nodes.
128136 */
129137 public ProtocolOptions(int port, ProtocolVersion protocolVersion, int maxSchemaAgreementWaitSeconds, SSLOptions sslOptions, AuthProvider authProvider) {
130138 this.port = port;
@@ -136,7 +144,6 @@
136144
137145 /**
138146 * @throws IllegalArgumentException if {@code protocolVersion} does not correspond to any known version.
139- *
140147 * @deprecated This is provided for backward compatibility; use {@link #ProtocolOptions(int, ProtocolVersion, int, SSLOptions, AuthProvider))} instead.
141148 */
142149 @Deprecated
@@ -172,7 +179,7 @@
172179
173180 /**
174181 * Returns the compression used by the protocol.
175- * <p>
182+ * <p/>
176183 * By default, compression is not used.
177184 *
178185 * @return the compression used.
@@ -183,18 +190,17 @@
183190
184191 /**
185192 * Sets the compression to use.
186- * <p>
193+ * <p/>
187194 * Note that while this setting can be changed at any time, it will
188195 * only apply to newly created connections.
189196 *
190197 * @param compression the compression algorithm to use (or {@code
191- * Compression.NONE} to disable compression).
198+ * Compression.NONE} to disable compression).
192199 * @return this {@code ProtocolOptions} object.
193- *
194200 * @throws IllegalStateException if the compression requested is not
195- * available. Most compression algorithms require that the relevant be
196- * present in the classpath. If not, the compression will be
197- * unavailable.
201+ * available. Most compression algorithms require that the relevant be
202+ * present in the classpath. If not, the compression will be
203+ * unavailable.
198204 */
199205 public ProtocolOptions setCompression(Compression compression) {
200206 if (compression != Compression.NONE && compression.compressor() == null)
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java +2 −2
@@ -19,10 +19,10 @@
1919
2020 /**
2121 * Parent class for {@link Authenticator} implementations that support native protocol v1 authentication.
22- *
22+ * <p/>
2323 * Protocol v1 uses simple, credentials-based authentication (as opposed to SASL for later protocol versions).
2424 * In order to support protocol v1, an authenticator must extend this class.
25- *
25+ * <p/>
2626 * We use an abstract class instead of an interface because we don't want to expose {@link #getCredentials()}.
2727 *
2828 * @see <a href="https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v1.spec">Native protocol v1 specification</a>
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolVersion.java +6 −8
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Map;
19-
20-import com.google.common.collect.ImmutableMap.Builder;
18+import com.datastax.driver.core.exceptions.DriverInternalError;
2119 import com.google.common.collect.ImmutableMap;
20+import com.google.common.collect.ImmutableMap.Builder;
2221
23-import com.datastax.driver.core.exceptions.DriverInternalError;
22+import java.util.Map;
2423
2524 /**
2625 * Versions of the native protocol supported by the driver.
@@ -30,8 +29,7 @@
3029 V1("1.2.0", 1),
3130 V2("2.0.0", 2),
3231 V3("2.1.0", 3),
33- V4("2.2.0", 4)
34- ;
32+ V4("2.2.0", 4);
3533
3634 /**
3735 * The most recent protocol version supported by the driver.
@@ -48,7 +46,7 @@
4846
4947 boolean isSupportedBy(Host host) {
5048 return host.getCassandraVersion() == null ||
51- isSupportedBy(host.getCassandraVersion());
49+ isSupportedBy(host.getCassandraVersion());
5250 }
5351
5452 VersionNumber minCassandraVersion() {
@@ -73,6 +71,7 @@
7371 }
7472
7573 private static final Map<Integer, ProtocolVersion> INT_TO_VERSION;
74+
7675 static {
7776 Builder<Integer, ProtocolVersion> builder = ImmutableMap.builder();
7877 for (ProtocolVersion version : values()) {
@@ -86,7 +85,6 @@
8685 *
8786 * @param i the version as an integer.
8887 * @return the matching enum value.
89- *
9088 * @throws IllegalArgumentException if the argument doesn't match any known version.
9189 */
9290 public static ProtocolVersion fromInt(int i) {
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +66 −65
@@ -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");
@@ -216,7 +216,7 @@
216216
217217 /**
218218 * Creates a new {@link QueryLogger.Builder} instance.
219- * <p>
219+ * <p/>
220220 * This is a convenience method for {@code new QueryLogger.Builder()}.
221221 *
222222 * @return the new QueryLogger builder.
@@ -297,10 +297,10 @@
297297 /**
298298 * A QueryLogger that uses a dynamic threshold in milliseconds
299299 * to track slow queries.
300- * <p>
300+ * <p/>
301301 * Dynamic thresholds are based on per-host latency percentiles, as computed
302302 * by {@link PerHostPercentileTracker}.
303- * <p>
303+ * <p/>
304304 * <b>This class is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
305305 * to change.</b>
306306 */
@@ -357,7 +357,7 @@
357357 * and logged as such by the driver.
358358 *
359359 * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
360- * It must be comprised between 0 inclusive and 100 exclusive.
360+ * It must be comprised between 0 inclusive and 100 exclusive.
361361 * @throws IllegalArgumentException if {@code slowQueryLatencyThresholdPercentile < 0 || slowQueryLatencyThresholdPercentile >= 100}.
362362 */
363363 public void setSlowQueryLatencyThresholdPercentile(double slowQueryLatencyThresholdPercentile) {
@@ -405,7 +405,7 @@
405405
406406 /**
407407 * Enables slow query latency tracking based on constant thresholds.
408- * <p>
408+ * <p/>
409409 * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
410410 * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
411411 * not both.
@@ -423,22 +423,22 @@
423423
424424 /**
425425 * Enables slow query latency tracking based on dynamic thresholds.
426- * <p>
426+ * <p/>
427427 * Dynamic thresholds are based on per-host latency percentiles, as computed
428428 * by {@link PerHostPercentileTracker}.
429- * <p>
429+ * <p/>
430430 * Note: You should either use {@link #withConstantThreshold(long) constant thresholds}
431431 * or {@link #withDynamicThreshold(PerHostPercentileTracker, double) dynamic thresholds},
432432 * not both.
433- * <p>
433+ * <p/>
434434 * <b>This feature is currently provided as a beta preview: it hasn't been extensively tested yet, and the API is still subject
435435 * to change.</b>
436436 *
437- * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
438- * Cannot be {@code null}.
437+ * @param perHostPercentileLatencyTracker the {@link PerHostPercentileTracker} instance to use for recording per-host latency histograms.
438+ * Cannot be {@code null}.
439439 * @param slowQueryLatencyThresholdPercentile Slow queries threshold percentile.
440- * It must be comprised between 0 inclusive and 100 exclusive.
441- * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
440+ * It must be comprised between 0 inclusive and 100 exclusive.
441+ * The default value is {@link #DEFAULT_SLOW_QUERY_THRESHOLD_PERCENTILE}
442442 * @return this {@link Builder} instance (for method chaining).
443443 */
444444 @Beta
@@ -504,11 +504,12 @@
504504
505505 /**
506506 * Build the {@link QueryLogger} instance.
507+ *
507508 * @return the {@link QueryLogger} instance.
508509 * @throws IllegalArgumentException if the builder is unable to build a valid instance due to incorrect settings.
509510 */
510511 public QueryLogger build() {
511- if(constantThreshold) {
512+ if (constantThreshold) {
512513 return new ConstantThresholdQueryLogger(maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdMillis);
513514 } else {
514515 return new DynamicThresholdQueryLogger(maxQueryStringLength, maxParameterValueLength, maxLoggedParameters, slowQueryLatencyThresholdPercentile, perHostPercentileLatencyTracker);
@@ -648,13 +649,13 @@
648649 if (showParameterValues) {
649650 StringBuilder params = new StringBuilder();
650651 if (statement instanceof BoundStatement) {
651- appendParameters((BoundStatement)statement, params, maxLoggedParameters);
652+ appendParameters((BoundStatement) statement, params, maxLoggedParameters);
652653 } else if (statement instanceof BatchStatement) {
653- BatchStatement batchStatement = (BatchStatement)statement;
654+ BatchStatement batchStatement = (BatchStatement) statement;
654655 int remaining = maxLoggedParameters;
655656 for (Statement inner : batchStatement.getStatements()) {
656657 if (inner instanceof BoundStatement) {
657- remaining = appendParameters((BoundStatement)inner, params, remaining);
658+ remaining = appendParameters((BoundStatement) inner, params, remaining);
658659 }
659660 }
660661 }
@@ -669,12 +670,12 @@
669670 protected String statementAsString(Statement statement) {
670671 StringBuilder sb = new StringBuilder();
671672 if (statement instanceof BatchStatement) {
672- BatchStatement bs = (BatchStatement)statement;
673+ BatchStatement bs = (BatchStatement) statement;
673674 int statements = bs.getStatements().size();
674675 int boundValues = countBoundValues(bs);
675676 sb.append("[" + statements + " statements, " + boundValues + " bound values] ");
676677 } else if (statement instanceof BoundStatement) {
677- int boundValues = ((BoundStatement)statement).wrapper.values.length;
678+ int boundValues = ((BoundStatement) statement).wrapper.values.length;
678679 sb.append("[" + boundValues + " bound values] ");
679680 }
680681
@@ -686,7 +687,7 @@
686687 int count = 0;
687688 for (Statement s : bs.getStatements()) {
688689 if (s instanceof BoundStatement)
689- count += ((BoundStatement)s).wrapper.values.length;
690+ count += ((BoundStatement) s).wrapper.values.length;
690691 }
691692 return count;
692693 }
@@ -711,8 +712,8 @@
711712 else
712713 buffer.append(", ");
713714 String value = statement.isSet(i)
714- ? parameterValueAsString(definitions.get(i), statement.wrapper.values[i])
715- : "<UNSET>";
715+ ? parameterValueAsString(definitions.get(i), statement.wrapper.values[i])
716+ : "<UNSET>";
716717 buffer.append(String.format("%s:%s", metadata.getName(i), value));
717718 }
718719 if (numberOfLoggedParameters < numberOfParameters) {
@@ -736,7 +737,7 @@
736737 int maxBufferLength = Math.max(2, (maxParameterValueLength - 2) / 2);
737738 boolean bufferTooLarge = raw.remaining() > maxBufferLength;
738739 if (bufferTooLarge) {
739- raw = (ByteBuffer)raw.duplicate().limit(maxBufferLength);
740+ raw = (ByteBuffer) raw.duplicate().limit(maxBufferLength);
740741 }
741742 Object value = codec.deserialize(raw, protocolVersion());
742743 valueStr = codec.format(value);
@@ -768,16 +769,16 @@
768769
769770 protected int append(Statement statement, StringBuilder buffer, int remaining) {
770771 if (statement instanceof StatementWrapper)
771- statement = ((StatementWrapper)statement).getWrappedStatement();
772+ statement = ((StatementWrapper) statement).getWrappedStatement();
772773
773774 if (statement instanceof RegularStatement) {
774- RegularStatement rs = (RegularStatement)statement;
775+ RegularStatement rs = (RegularStatement) statement;
775776 String query = rs.getQueryString();
776777 remaining = append(query.trim(), buffer, remaining);
777778 } else if (statement instanceof BoundStatement) {
778- remaining = append(((BoundStatement)statement).preparedStatement().getQueryString().trim(), buffer, remaining);
779+ remaining = append(((BoundStatement) statement).preparedStatement().getQueryString().trim(), buffer, remaining);
779780 } else if (statement instanceof BatchStatement) {
780- BatchStatement batchStatement = (BatchStatement)statement;
781+ BatchStatement batchStatement = (BatchStatement) statement;
781782 remaining = append("BEGIN", buffer, remaining);
782783 switch (batchStatement.batchType) {
783784 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 +27 −31
@@ -15,16 +15,16 @@
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.exceptions.UnsupportedProtocolVersionException;
2220 import com.datastax.driver.core.querybuilder.BuiltStatement;
2321 import com.datastax.driver.core.schemabuilder.SchemaStatement;
2422
23+import java.nio.ByteBuffer;
24+
2525 /**
2626 * A regular (non-prepared and non batched) CQL statement.
27- * <p>
27+ * <p/>
2828 * This class represents a query string along with query options (and optionally
2929 * binary values, see {@code getValues}). It can be extended but {@link SimpleStatement}
3030 * is provided as a simple implementation to build a {@code RegularStatement} directly
@@ -35,7 +35,8 @@
3535 /**
3636 * Creates a new RegularStatement.
3737 */
38- protected RegularStatement() {}
38+ protected RegularStatement() {
39+ }
3940
4041 /**
4142 * Returns the query string for this statement.
@@ -45,28 +46,26 @@
4546 * process of generating the query. Note that it might be
4647 * possible to use the no-arg {@link #getQueryString()}
4748 * depending on the type of statement this is called on.
48- *
4949 * @return a valid CQL query string.
50- *
5150 * @see #getQueryString()
5251 */
5352 public abstract String getQueryString(CodecRegistry codecRegistry);
5453
5554 /**
5655 * Returns the query string for this statement.
57- * <p>
56+ * <p/>
5857 * This method calls {@link #getQueryString(CodecRegistry)} with {@link CodecRegistry#DEFAULT_INSTANCE}.
5958 * Whether you should use this or the other variant depends on the type of statement this is
6059 * called on:
6160 * <ul>
62- * <li>for a {@link SimpleStatement} or {@link SchemaStatement}, the codec registry isn't
63- * actually needed, so it's always safe to use this method;</li>
64- * <li>for a {@link BuiltStatement} you can use this method if you use no custom codecs, or if
65- * your custom codecs are registered with the default registry. Otherwise, use the other method and
66- * provide the registry that contains your codecs (see {@link BuiltStatement} for more explanations
67- * on why this is so);</li>
68- * <li>for a {@link BatchStatement}, use the first rule if it contains no built statements,
69- * or the second rule otherwise.</li>
61+ * <li>for a {@link SimpleStatement} or {@link SchemaStatement}, the codec registry isn't
62+ * actually needed, so it's always safe to use this method;</li>
63+ * <li>for a {@link BuiltStatement} you can use this method if you use no custom codecs, or if
64+ * your custom codecs are registered with the default registry. Otherwise, use the other method and
65+ * provide the registry that contains your codecs (see {@link BuiltStatement} for more explanations
66+ * on why this is so);</li>
67+ * <li>for a {@link BatchStatement}, use the first rule if it contains no built statements,
68+ * or the second rule otherwise.</li>
7069 * </ul>
7170 *
7271 * @return a valid CQL query string.
@@ -77,7 +76,7 @@
7776
7877 /**
7978 * The values to use for this statement.
80- * <p>
79+ * <p/>
8180 * Note: Values for a RegularStatement (i.e. if this method does not return
8281 * {@code null}) are not supported with the native protocol version 1: you
8382 * will get an {@link UnsupportedProtocolVersionException} when submitting
@@ -87,11 +86,10 @@
8786 *
8887 * @param protocolVersion the protocol version that will be used to serialize
8988 * the values.
90- * @param codecRegistry the codec registry that will be used to serialize the
91- * values.
92- *
89+ * @param codecRegistry the codec registry that will be used to serialize the
90+ * values.
9391 * @throws InvalidTypeException if one of the values is not of a type
94- * that can be serialized to a CQL3 type
92+ * that can be serialized to a CQL3 type
9593 * @see SimpleStatement#SimpleStatement(String, Object...)
9694 */
9795 public abstract ByteBuffer[] getValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry);
@@ -106,10 +104,8 @@
106104 * Note that it might be possible to use the no-arg
107105 * {@link #hasValues()} depending on the type of
108106 * statement this is called on.
109- *
110107 * @return {@code false} if {@link #getValues} returns {@code null}, {@code true}
111108 * otherwise.
112- *
113109 * @see #hasValues()
114110 */
115111 public abstract boolean hasValues(CodecRegistry codecRegistry);
@@ -117,19 +113,19 @@
117113 /**
118114 * Whether or not this statement has values, that is if {@code getValues}
119115 * will return {@code null} or not.
120- * <p>
116+ * <p/>
121117 * This method calls {@link #hasValues(CodecRegistry)} with {@link ProtocolVersion#NEWEST_SUPPORTED}.
122118 * Whether you should use this or the other variant depends on the type of statement this is
123119 * called on:
124120 * <ul>
125- * <li>for a {@link SimpleStatement} or {@link SchemaStatement}, the codec registry isn't
126- * actually needed, so it's always safe to use this method;</li>
127- * <li>for a {@link BuiltStatement} you can use this method if you use no custom codecs, or if
128- * your custom codecs are registered with the default registry. Otherwise, use the other method and
129- * provide the registry that contains your codecs (see {@link BuiltStatement} for more explanations
130- * on why this is so);</li>
131- * <li>for a {@link BatchStatement}, use the first rule if it contains no built statements,
132- * or the second rule otherwise.</li>
121+ * <li>for a {@link SimpleStatement} or {@link SchemaStatement}, the codec registry isn't
122+ * actually needed, so it's always safe to use this method;</li>
123+ * <li>for a {@link BuiltStatement} you can use this method if you use no custom codecs, or if
124+ * your custom codecs are registered with the default registry. Otherwise, use the other method and
125+ * provide the registry that contains your codecs (see {@link BuiltStatement} for more explanations
126+ * on why this is so);</li>
127+ * <li>for a {@link BatchStatement}, use the first rule if it contains no built statements,
128+ * or the second rule otherwise.</li>
133129 * </ul>
134130 *
135131 * @return {@code false} if {@link #getValues} returns {@code null}, {@code true}
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +12 −13
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import com.google.common.collect.ImmutableSet;
2119 import com.google.common.collect.Maps;
2220 import com.google.common.collect.Sets;
2321 import org.slf4j.Logger;
2422 import org.slf4j.LoggerFactory;
2523
24+import java.util.*;
25+
2626 /*
2727 * Computes the token->list<replica> association, given the token ring and token->primary token map.
2828 *
@@ -42,8 +42,7 @@
4242 return repFactorString == null ? null : new SimpleStrategy(Integer.parseInt(repFactorString));
4343 } else if (strategyClass.contains("NetworkTopologyStrategy")) {
4444 Map<String, Integer> dcRfs = new HashMap<String, Integer>();
45- for (Map.Entry<String, String> entry : replicationOptions.entrySet())
46- {
45+ for (Map.Entry<String, String> entry : replicationOptions.entrySet()) {
4746 if (entry.getKey().equals("class"))
4847 continue;
4948
@@ -83,7 +82,7 @@
8382 // Consecutive sections of the ring can assigned to the same host
8483 Set<Host> replicas = new LinkedHashSet<Host>();
8584 for (int j = 0; j < ring.size() && replicas.size() < rf; j++)
86- replicas.add(tokenToPrimary.get(getTokenWrapping(i+j, ring)));
85+ replicas.add(tokenToPrimary.get(getTokenWrapping(i + j, ring)));
8786 replicaMap.put(ring.get(i), ImmutableSet.copyOf(replicas));
8887 }
8988 return replicaMap;
@@ -96,7 +95,7 @@
9695 if (o == null || getClass() != o.getClass())
9796 return false;
9897
99- SimpleStrategy that = (SimpleStrategy)o;
98+ SimpleStrategy that = (SimpleStrategy) o;
10099
101100 return replicationFactor == that.replicationFactor;
102101
@@ -119,7 +118,7 @@
119118
120119 Map<Token, Set<Host>> computeTokenToReplicaMap(String keyspaceName, Map<Token, Host> tokenToPrimary, List<Token> ring) {
121120
122- // This is essentially a copy of org.apache.cassandra.locator.NetworkTopologyStrategy
121+ // This is essentially a copy of org.apache.cassandra.locator.NetworkTopologyStrategy
123122 Map<String, Set<String>> racks = getRacksInDcs(tokenToPrimary.values());
124123 Map<Token, Set<Host>> replicaMap = new HashMap<Token, Set<Host>>(tokenToPrimary.size());
125124 Map<String, Integer> dcHostCount = Maps.newHashMapWithExpectedSize(replicationFactors.size());
@@ -127,7 +126,7 @@
127126 // find maximum number of nodes in each DC
128127 for (Host host : Sets.newHashSet(tokenToPrimary.values())) {
129128 String dc = host.getDatacenter();
130- if(dcHostCount.get(dc) == null) {
129+ if (dcHostCount.get(dc) == null) {
131130 dcHostCount.put(dc, 0);
132131 }
133132 dcHostCount.put(dc, dcHostCount.get(dc) + 1);
@@ -190,9 +189,9 @@
190189 int achievedFactor = entry.getValue().size();
191190 if (achievedFactor < expectedFactor && !warnedDcs.contains(dcName)) {
192191 logger.warn("Error while computing token map for keyspace {} with datacenter {}: "
193- + "could not achieve replication factor {} (found {} replicas only), "
194- + "check your keyspace replication settings.",
195- keyspaceName, dcName, expectedFactor, achievedFactor);
192+ + "could not achieve replication factor {} (found {} replicas only), "
193+ + "check your keyspace replication settings.",
194+ keyspaceName, dcName, expectedFactor, achievedFactor);
196195 // only warn once per DC
197196 warnedDcs.add(dcName);
198197 }
@@ -206,7 +205,7 @@
206205 private boolean allDone(Map<String, Set<Host>> map, Map<String, Integer> dcHostCount) {
207206 for (Map.Entry<String, Set<Host>> entry : map.entrySet()) {
208207 String dc = entry.getKey();
209- int dcCount = dcHostCount.get(dc) == null? 0 : dcHostCount.get(dc);
208+ int dcCount = dcHostCount.get(dc) == null ? 0 : dcHostCount.get(dc);
210209 if (entry.getValue().size() < Math.min(replicationFactors.get(dc), dcCount))
211210 return false;
212211 }
@@ -233,7 +232,7 @@
233232 if (o == null || getClass() != o.getClass())
234233 return false;
235234
236- NetworkTopologyStrategy that = (NetworkTopologyStrategy)o;
235+ NetworkTopologyStrategy that = (NetworkTopologyStrategy) o;
237236
238237 return replicationFactors.equals(that.replicationFactors);
239238
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +72 −70
@@ -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.Collections;
2031 import java.util.Iterator;
@@ -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.
@@ -68,7 +67,7 @@
6867
6968 public RequestHandler(SessionManager manager, Callback callback, Statement statement) {
7069 this.id = Long.toString(System.identityHashCode(this));
71- if(logger.isTraceEnabled())
70+ if (logger.isTraceEnabled())
7271 logger.trace("[{}] {}", id, statement);
7372 this.manager = manager;
7473 this.callback = callback;
@@ -79,12 +78,12 @@
7978 this.queryPlan = new QueryPlan(manager.loadBalancingPolicy().newQueryPlan(manager.poolsState.keyspace, statement));
8079 this.speculativeExecutionPlan = manager.speculativeExecutionPolicy().newPlan(manager.poolsState.keyspace, statement);
8180 this.allowSpeculativeExecutions = statement != Statement.DEFAULT
82- && statement.isIdempotentWithDefault(manager.configuration().getQueryOptions());
81+ && statement.isIdempotentWithDefault(manager.configuration().getQueryOptions());
8382 this.statement = statement;
8483
8584 this.timerContext = metricsEnabled()
86- ? metrics().getRequestsTimer().time()
87- : null;
85+ ? metrics().getRequestsTimer().time()
86+ : null;
8887 this.startTime = System.nanoTime();
8988 }
9089
@@ -119,7 +118,7 @@
119118 private void scheduleExecution(long delayMillis) {
120119 if (isDone.get() || delayMillis <= 0)
121120 return;
122- if(logger.isTraceEnabled())
121+ if (logger.isTraceEnabled())
123122 logger.trace("[{}] Schedule next speculative execution in {} ms", id, delayMillis);
124123 scheduledExecutions.add(scheduler.newTimeout(newExecutionTask, delayMillis, TimeUnit.MILLISECONDS));
125124 }
@@ -158,12 +157,12 @@
158157
159158 private void setFinalResult(SpeculativeExecution execution, Connection connection, Message.Response response) {
160159 if (!isDone.compareAndSet(false, true)) {
161- if(logger.isTraceEnabled())
160+ if (logger.isTraceEnabled())
162161 logger.trace("[{}] Got beaten to setting the result", execution.id);
163162 return;
164163 }
165164
166- if(logger.isTraceEnabled())
165+ if (logger.isTraceEnabled())
167166 logger.trace("[{}] Setting final result", execution.id);
168167
169168 cancelPendingExecutions(execution);
@@ -185,19 +184,19 @@
185184 callback.onSet(connection, response, info, statement, System.nanoTime() - startTime);
186185 } catch (Exception e) {
187186 callback.onException(connection,
188- new DriverInternalError("Unexpected exception while setting final result from " + response, e),
189- System.nanoTime() - startTime, /*unused*/0);
187+ new DriverInternalError("Unexpected exception while setting final result from " + response, e),
188+ System.nanoTime() - startTime, /*unused*/0);
190189 }
191190 }
192191
193192 private void setFinalException(SpeculativeExecution execution, Connection connection, Exception exception) {
194193 if (!isDone.compareAndSet(false, true)) {
195- if(logger.isTraceEnabled())
194+ if (logger.isTraceEnabled())
196195 logger.trace("[{}] Got beaten to setting final exception", execution.id);
197196 return;
198197 }
199198
200- if(logger.isTraceEnabled())
199+ if (logger.isTraceEnabled())
201200 logger.trace("[{}] Setting final exception", execution.id);
202201
203202 cancelPendingExecutions(execution);
@@ -216,7 +215,7 @@
216215 runningExecutions.remove(execution);
217216 if (runningExecutions.isEmpty())
218217 setFinalException(execution, null, new NoHostAvailableException(
219- errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors));
218+ errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors));
220219 }
221220
222221 private boolean metricsEnabled() {
@@ -229,12 +228,13 @@
229228
230229 private RetryPolicy retryPolicy() {
231230 return statement.getRetryPolicy() == null
232- ? manager.configuration().getPolicies().getRetryPolicy()
233- : statement.getRetryPolicy();
231+ ? manager.configuration().getPolicies().getRetryPolicy()
232+ : statement.getRetryPolicy();
234233 }
235234
236235 interface Callback extends Connection.ResponseCallback {
237236 void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency);
237+
238238 void register(RequestHandler handler);
239239 }
240240
@@ -268,7 +268,7 @@
268268 this.id = RequestHandler.this.id + "-" + position;
269269 this.request = request;
270270 this.queryStateRef = new AtomicReference<QueryState>(QueryState.INITIAL);
271- if(logger.isTraceEnabled())
271+ if (logger.isTraceEnabled())
272272 logger.trace("[{}] Starting", id);
273273 }
274274
@@ -276,7 +276,7 @@
276276 try {
277277 Host host;
278278 while (!isDone.get() && (host = queryPlan.next()) != null && !queryStateRef.get().isCancelled()) {
279- if(logger.isTraceEnabled())
279+ if (logger.isTraceEnabled())
280280 logger.trace("[{}] Querying node {}", id, host);
281281 if (query(host))
282282 return;
@@ -431,7 +431,7 @@
431431 if (previous.isCancelled()) {
432432 return;
433433 } else if (previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_IN_PROGRESS)) {
434- if(logger.isTraceEnabled())
434+ if (logger.isTraceEnabled())
435435 logger.trace("[{}] Cancelled while in progress", id);
436436 // The connectionHandler should be non-null, but we might miss the update if we're racing with write().
437437 // If it's still null, this will be handled by re-checking queryStateRef at the end of write().
@@ -439,7 +439,7 @@
439439 connectionHandler.connection.release();
440440 return;
441441 } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) {
442- if(logger.isTraceEnabled())
442+ if (logger.isTraceEnabled())
443443 logger.trace("[{}] Cancelled while complete", id);
444444 return;
445445 }
@@ -458,9 +458,9 @@
458458 public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
459459 QueryState queryState = queryStateRef.get();
460460 if (!queryState.isInProgressAt(retryCount) ||
461- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
461+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
462462 logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
463- retryCount, queryState, queryStateRef.get());
463+ retryCount, queryState, queryStateRef.get());
464464 return;
465465 }
466466
@@ -473,7 +473,7 @@
473473 setFinalResult(connection, response);
474474 break;
475475 case ERROR:
476- Responses.Error err = (Responses.Error)response;
476+ Responses.Error err = (Responses.Error) response;
477477 exceptionToReport = err.asException(connection.address);
478478 RetryPolicy.RetryDecision retry = null;
479479 RetryPolicy retryPolicy = retryPolicy();
@@ -481,13 +481,13 @@
481481 case READ_TIMEOUT:
482482 connection.release();
483483 assert err.infos instanceof ReadTimeoutException;
484- ReadTimeoutException rte = (ReadTimeoutException)err.infos;
484+ ReadTimeoutException rte = (ReadTimeoutException) err.infos;
485485 retry = retryPolicy.onReadTimeout(statement,
486- rte.getConsistencyLevel(),
487- rte.getRequiredAcknowledgements(),
488- rte.getReceivedAcknowledgements(),
489- rte.wasDataRetrieved(),
490- retriesByPolicy);
486+ rte.getConsistencyLevel(),
487+ rte.getRequiredAcknowledgements(),
488+ rte.getReceivedAcknowledgements(),
489+ rte.wasDataRetrieved(),
490+ retriesByPolicy);
491491 if (metricsEnabled()) {
492492 metrics().getErrorMetrics().getReadTimeouts().inc();
493493 if (retry.getType() == Type.RETRY)
@@ -499,13 +499,13 @@
499499 case WRITE_TIMEOUT:
500500 connection.release();
501501 assert err.infos instanceof WriteTimeoutException;
502- WriteTimeoutException wte = (WriteTimeoutException)err.infos;
502+ WriteTimeoutException wte = (WriteTimeoutException) err.infos;
503503 retry = retryPolicy.onWriteTimeout(statement,
504- wte.getConsistencyLevel(),
505- wte.getWriteType(),
506- wte.getRequiredAcknowledgements(),
507- wte.getReceivedAcknowledgements(),
508- retriesByPolicy);
504+ wte.getConsistencyLevel(),
505+ wte.getWriteType(),
506+ wte.getRequiredAcknowledgements(),
507+ wte.getReceivedAcknowledgements(),
508+ retriesByPolicy);
509509 if (metricsEnabled()) {
510510 metrics().getErrorMetrics().getWriteTimeouts().inc();
511511 if (retry.getType() == Type.RETRY)
@@ -517,12 +517,12 @@
517517 case UNAVAILABLE:
518518 connection.release();
519519 assert err.infos instanceof UnavailableException;
520- UnavailableException ue = (UnavailableException)err.infos;
520+ UnavailableException ue = (UnavailableException) err.infos;
521521 retry = retryPolicy.onUnavailable(statement,
522- ue.getConsistencyLevel(),
523- ue.getRequiredReplicas(),
524- ue.getAliveReplicas(),
525- retriesByPolicy);
522+ ue.getConsistencyLevel(),
523+ ue.getRequiredReplicas(),
524+ ue.getAliveReplicas(),
525+ retriesByPolicy);
526526 if (metricsEnabled()) {
527527 metrics().getErrorMetrics().getUnavailables().inc();
528528 if (retry.getType() == Type.RETRY)
@@ -536,8 +536,8 @@
536536 assert exceptionToReport instanceof OverloadedException;
537537 logger.warn("Host {} is overloaded.", connection.address);
538538 retry = retryPolicy.onRequestError(statement,
539- request().consistency(),
540- (OverloadedException)exceptionToReport, retriesByPolicy);
539+ request().consistency(),
540+ (OverloadedException) exceptionToReport, retriesByPolicy);
541541 if (metricsEnabled()) {
542542 metrics().getErrorMetrics().getOthers().inc();
543543 if (retry.getType() == Type.RETRY)
@@ -553,8 +553,8 @@
553553 // Defunct connection
554554 connection.defunct(exceptionToReport);
555555 retry = retryPolicy.onRequestError(statement,
556- request().consistency(),
557- (ServerError)exceptionToReport, retriesByPolicy);
556+ request().consistency(),
557+ (ServerError) exceptionToReport, retriesByPolicy);
558558 if (metricsEnabled()) {
559559 metrics().getErrorMetrics().getOthers().inc();
560560 if (retry.getType() == Type.RETRY)
@@ -576,7 +576,7 @@
576576 case UNPREPARED:
577577 // Do not release connection yet, because we might reuse it to send the PREPARE message (see write() call below)
578578 assert err.infos instanceof MD5Digest;
579- MD5Digest id = (MD5Digest)err.infos;
579+ MD5Digest id = (MD5Digest) err.infos;
580580 PreparedStatement toPrepare = manager.cluster.manager.preparedQueries.get(id);
581581 if (toPrepare == null) {
582582 // This shouldn't happen
@@ -596,12 +596,12 @@
596596 // that's shared with other requests).
597597 connection.release();
598598 throw new IllegalStateException(String.format("Statement was prepared on keyspace %s, can't execute it on %s (%s)",
599- toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString()));
599+ toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString()));
600600 }
601601
602602 logger.info("Query {} is not prepared on {}, preparing before retrying executing. "
603- + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems",
604- toPrepare.getQueryString(), connection.address);
603+ + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems",
604+ toPrepare.getQueryString(), connection.address);
605605
606606 write(connection, prepareAndRetry(toPrepare.getQueryString()));
607607 // we're done for now, the prepareAndRetry callback will handle the rest
@@ -658,9 +658,9 @@
658658 public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
659659 QueryState queryState = queryStateRef.get();
660660 if (!queryState.isInProgressAt(retryCount) ||
661- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
661+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
662662 logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
663- retryCount, queryState, queryStateRef.get());
663+ retryCount, queryState, queryStateRef.get());
664664 return;
665665 }
666666
@@ -668,7 +668,7 @@
668668
669669 switch (response.type) {
670670 case RESULT:
671- if (((Responses.Result)response).kind == Responses.Result.Kind.PREPARED) {
671+ if (((Responses.Result) response).kind == Responses.Result.Kind.PREPARED) {
672672 logger.debug("Scheduling retry now that query is prepared");
673673 retry(true, null);
674674 } else {
@@ -698,9 +698,9 @@
698698 public boolean onTimeout(Connection connection, long latency, int retryCount) {
699699 QueryState queryState = queryStateRef.get();
700700 if (!queryState.isInProgressAt(retryCount) ||
701- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
701+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
702702 logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
703- retryCount, queryState, queryStateRef.get());
703+ retryCount, queryState, queryStateRef.get());
704704 return false;
705705 }
706706 connection.release();
@@ -715,9 +715,9 @@
715715 public void onException(Connection connection, Exception exception, 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("onException 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;
722722 }
723723
@@ -727,7 +727,7 @@
727727
728728 if (exception instanceof ConnectionException) {
729729 RetryPolicy retryPolicy = retryPolicy();
730- RetryPolicy.RetryDecision decision = retryPolicy.onRequestError(statement, request().consistency(), (ConnectionException)exception, retriesByPolicy);
730+ RetryPolicy.RetryDecision decision = retryPolicy.onRequestError(statement, request().consistency(), (ConnectionException) exception, retriesByPolicy);
731731 if (metricsEnabled()) {
732732 metrics().getErrorMetrics().getConnectionErrors().inc();
733733 if (decision.getType() == Type.RETRY)
@@ -752,9 +752,9 @@
752752 public boolean onTimeout(Connection connection, long latency, int retryCount) {
753753 QueryState queryState = queryStateRef.get();
754754 if (!queryState.isInProgressAt(retryCount) ||
755- !queryStateRef.compareAndSet(queryState, queryState.complete())) {
755+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
756756 logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
757- retryCount, queryState, queryStateRef.get());
757+ retryCount, queryState, queryStateRef.get());
758758 return false;
759759 }
760760
@@ -801,7 +801,7 @@
801801
802802 /**
803803 * The state of a SpeculativeExecution.
804- *
804+ * <p/>
805805 * This is used to prevent races between request completion (either success or error) and timeout.
806806 * A retry is in progress once we have written the request to the connection and until we get back a response (see onSet
807807 * or onException) or a timeout (see onTimeout).
@@ -855,7 +855,9 @@
855855 this.iterator = iterator;
856856 }
857857
858- /** @return null if there are no more hosts */
858+ /**
859+ * @return null if there are no more hosts
860+ */
859861 synchronized Host next() {
860862 return iterator.hasNext() ? iterator.next() : null;
861863 }
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +36 −31
@@ -15,18 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.ImmutableMap;
19+import io.netty.buffer.ByteBuf;
20+
1821 import java.nio.ByteBuffer;
1922 import java.util.Collections;
2023 import java.util.EnumSet;
2124 import java.util.List;
2225 import java.util.Map;
2326
24-import com.google.common.collect.ImmutableMap;
25-import io.netty.buffer.ByteBuf;
26-
2727 class Requests {
2828
29- private Requests() {}
29+ private Requests() {
30+ }
3031
3132 public static class Startup extends Message.Request {
3233 private static final String CQL_VERSION_OPTION = "CQL_VERSION";
@@ -88,9 +89,9 @@
8889
8990 public static class Options extends Message.Request {
9091
91- public static final Message.Coder<Options> coder = new Message.Coder<Options>()
92- {
93- public void encode(Options msg, ByteBuf dest, ProtocolVersion version) {}
92+ public static final Message.Coder<Options> coder = new Message.Coder<Options>() {
93+ public void encode(Options msg, ByteBuf dest, ProtocolVersion version) {
94+ }
9495
9596 public int encodedSize(Options msg, ProtocolVersion version) {
9697 return 0;
@@ -117,7 +118,7 @@
117118
118119 public int encodedSize(Query msg, ProtocolVersion version) {
119120 return CBUtil.sizeOfLongString(msg.query)
120- + msg.options.encodedSize(version);
121+ + msg.options.encodedSize(version);
121122 }
122123 };
123124
@@ -160,7 +161,7 @@
160161
161162 public int encodedSize(Execute msg, ProtocolVersion version) {
162163 return CBUtil.sizeOfBytes(msg.statementId.bytes)
163- + msg.options.encodedSize(version);
164+ + msg.options.encodedSize(version);
164165 }
165166 };
166167
@@ -202,8 +203,7 @@
202203 public static EnumSet<QueryFlag> deserialize(int flags) {
203204 EnumSet<QueryFlag> set = EnumSet.noneOf(QueryFlag.class);
204205 QueryFlag[] values = QueryFlag.values();
205- for (int n = 0; n < values.length; n++)
206- {
206+ for (int n = 0; n < values.length; n++) {
207207 if ((flags & (1 << n)) != 0)
208208 set.add(values[n]);
209209 }
@@ -221,12 +221,12 @@
221221 public static class QueryProtocolOptions {
222222
223223 public static final QueryProtocolOptions DEFAULT = new QueryProtocolOptions(ConsistencyLevel.ONE,
224- Collections.<ByteBuffer>emptyList(),
225- false,
226- -1,
227- null,
228- ConsistencyLevel.SERIAL,
229- Long.MIN_VALUE);
224+ Collections.<ByteBuffer>emptyList(),
225+ false,
226+ -1,
227+ null,
228+ ConsistencyLevel.SERIAL,
229+ Long.MIN_VALUE);
230230
231231 private final EnumSet<QueryFlag> flags = EnumSet.noneOf(QueryFlag.class);
232232 public final ConsistencyLevel consistency;
@@ -283,7 +283,7 @@
283283 case V3:
284284 case V4:
285285 CBUtil.writeConsistencyLevel(consistency, dest);
286- dest.writeByte((byte)QueryFlag.serialize(flags));
286+ dest.writeByte((byte) QueryFlag.serialize(flags));
287287 if (flags.contains(QueryFlag.VALUES))
288288 CBUtil.writeValueList(values, dest);
289289 if (flags.contains(QueryFlag.PAGE_SIZE))
@@ -292,7 +292,7 @@
292292 CBUtil.writeValue(pagingState, dest);
293293 if (flags.contains(QueryFlag.SERIAL_CONSISTENCY))
294294 CBUtil.writeConsistencyLevel(serialConsistency, dest);
295- if (version.compareTo(ProtocolVersion.V3) >=0 && flags.contains(QueryFlag.DEFAULT_TIMESTAMP))
295+ if (version.compareTo(ProtocolVersion.V3) >= 0 && flags.contains(QueryFlag.DEFAULT_TIMESTAMP))
296296 dest.writeLong(defaultTimestamp);
297297 break;
298298 default:
@@ -304,7 +304,7 @@
304304 switch (version) {
305305 case V1:
306306 return CBUtil.sizeOfValueList(values)
307- + CBUtil.sizeOfConsistencyLevel(consistency);
307+ + CBUtil.sizeOfConsistencyLevel(consistency);
308308 case V2:
309309 case V3:
310310 case V4:
@@ -345,11 +345,11 @@
345345
346346 for (int i = 0; i < queries; i++) {
347347 Object q = msg.queryOrIdList.get(i);
348- dest.writeByte((byte)(q instanceof String ? 0 : 1));
348+ dest.writeByte((byte) (q instanceof String ? 0 : 1));
349349 if (q instanceof String)
350- CBUtil.writeLongString((String)q, dest);
350+ CBUtil.writeLongString((String) q, dest);
351351 else
352- CBUtil.writeBytes(((MD5Digest)q).bytes, dest);
352+ CBUtil.writeBytes(((MD5Digest) q).bytes, dest);
353353
354354 CBUtil.writeValueList(msg.values.get(i), dest);
355355 }
@@ -362,8 +362,8 @@
362362 for (int i = 0; i < msg.queryOrIdList.size(); i++) {
363363 Object q = msg.queryOrIdList.get(i);
364364 size += 1 + (q instanceof String
365- ? CBUtil.sizeOfLongString((String)q)
366- : CBUtil.sizeOfBytes(((MD5Digest)q).bytes));
365+ ? CBUtil.sizeOfLongString((String) q)
366+ : CBUtil.sizeOfBytes(((MD5Digest) q).bytes));
367367
368368 size += CBUtil.sizeOfValueList(msg.values.get(i));
369369 }
@@ -373,10 +373,14 @@
373373
374374 private byte fromType(BatchStatement.Type type) {
375375 switch (type) {
376- case LOGGED: return 0;
377- case UNLOGGED: return 1;
378- case COUNTER: return 2;
379- default: throw new AssertionError();
376+ case LOGGED:
377+ return 0;
378+ case UNLOGGED:
379+ return 1;
380+ case COUNTER:
381+ return 2;
382+ default:
383+ throw new AssertionError();
380384 }
381385 }
382386 };
@@ -403,6 +407,7 @@
403407 Request copy(ConsistencyLevel newConsistencyLevel) {
404408 return new Batch(type, queryOrIdList, values, options.copy(newConsistencyLevel), isTracingRequested());
405409 }
410+
406411 @Override
407412 public String toString() {
408413 StringBuilder sb = new StringBuilder();
@@ -445,7 +450,7 @@
445450 case V3:
446451 case V4:
447452 CBUtil.writeConsistencyLevel(consistency, dest);
448- dest.writeByte((byte)QueryFlag.serialize(flags));
453+ dest.writeByte((byte) QueryFlag.serialize(flags));
449454 if (flags.contains(QueryFlag.SERIAL_CONSISTENCY))
450455 CBUtil.writeConsistencyLevel(serialConsistency, dest);
451456 if (flags.contains(QueryFlag.DEFAULT_TIMESTAMP))
@@ -478,7 +483,7 @@
478483 @Override
479484 public String toString() {
480485 return String.format("[cl=%s, serialCl=%s, defaultTs=%d]",
481- consistency, serialConsistency, defaultTimestamp);
486+ consistency, serialConsistency, defaultTimestamp);
482487 }
483488 }
484489
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +57 −42
@@ -15,25 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.nio.ByteBuffer;
20-import java.util.*;
21-
22-import io.netty.buffer.ByteBuf;
23-
2418 import com.datastax.driver.core.Responses.Result.Rows.Metadata;
2519 import com.datastax.driver.core.exceptions.*;
2620 import com.datastax.driver.core.utils.Bytes;
21+import io.netty.buffer.ByteBuf;
22+
23+import java.net.InetSocketAddress;
24+import java.nio.ByteBuffer;
25+import java.util.*;
2726
2827 import static com.datastax.driver.core.ProtocolVersion.V4;
29-import static com.datastax.driver.core.SchemaElement.AGGREGATE;
30-import static com.datastax.driver.core.SchemaElement.FUNCTION;
31-import static com.datastax.driver.core.SchemaElement.KEYSPACE;
32-import static com.datastax.driver.core.SchemaElement.TABLE;
28+import static com.datastax.driver.core.SchemaElement.*;
3329
3430 class Responses {
3531
36- private Responses() {}
32+ private Responses() {
33+ }
3734
3835 public static class Error extends Message.Response {
3936
@@ -107,25 +104,44 @@
107104
108105 public DriverException asException(InetSocketAddress host) {
109106 switch (code) {
110- case SERVER_ERROR: return new ServerError(host, message);
111- case PROTOCOL_ERROR: return new ProtocolError(host, message);
112- case BAD_CREDENTIALS: return new AuthenticationException(host, message);
113- case UNAVAILABLE: return ((UnavailableException)infos).copy(host); // We copy to have a nice stack trace
114- case OVERLOADED: return new OverloadedException(host, message);
115- case IS_BOOTSTRAPPING: return new BootstrappingException(host, message);
116- case TRUNCATE_ERROR: return new TruncateException(host, message);
117- case WRITE_TIMEOUT: return ((WriteTimeoutException)infos).copy(host);
118- case READ_TIMEOUT: return ((ReadTimeoutException)infos).copy(host);
119- case WRITE_FAILURE: return ((WriteFailureException)infos).copy(host);
120- case READ_FAILURE: return ((ReadFailureException)infos).copy(host);
121- case FUNCTION_FAILURE: return new FunctionExecutionException(host, message);
122- case SYNTAX_ERROR: return new SyntaxError(host, message);
123- case UNAUTHORIZED: return new UnauthorizedException(host, message);
124- case INVALID: return new InvalidQueryException(host, message);
125- case CONFIG_ERROR: return new InvalidConfigurationInQueryException(host, message);
126- case ALREADY_EXISTS: return ((AlreadyExistsException)infos).copy(host);
127- case UNPREPARED: return new UnpreparedException(host, message);
128- default: return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message));
107+ case SERVER_ERROR:
108+ return new ServerError(host, message);
109+ case PROTOCOL_ERROR:
110+ return new ProtocolError(host, message);
111+ case BAD_CREDENTIALS:
112+ return new AuthenticationException(host, message);
113+ case UNAVAILABLE:
114+ return ((UnavailableException) infos).copy(host); // We copy to have a nice stack trace
115+ case OVERLOADED:
116+ return new OverloadedException(host, message);
117+ case IS_BOOTSTRAPPING:
118+ return new BootstrappingException(host, message);
119+ case TRUNCATE_ERROR:
120+ return new TruncateException(host, message);
121+ case WRITE_TIMEOUT:
122+ return ((WriteTimeoutException) infos).copy(host);
123+ case READ_TIMEOUT:
124+ return ((ReadTimeoutException) infos).copy(host);
125+ case WRITE_FAILURE:
126+ return ((WriteFailureException) infos).copy(host);
127+ case READ_FAILURE:
128+ return ((ReadFailureException) infos).copy(host);
129+ case FUNCTION_FAILURE:
130+ return new FunctionExecutionException(host, message);
131+ case SYNTAX_ERROR:
132+ return new SyntaxError(host, message);
133+ case UNAUTHORIZED:
134+ return new UnauthorizedException(host, message);
135+ case INVALID:
136+ return new InvalidQueryException(host, message);
137+ case CONFIG_ERROR:
138+ return new InvalidConfigurationInQueryException(host, message);
139+ case ALREADY_EXISTS:
140+ return ((AlreadyExistsException) infos).copy(host);
141+ case UNPREPARED:
142+ return new UnpreparedException(host, message);
143+ default:
144+ return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message));
129145 }
130146 }
131147
@@ -223,16 +239,17 @@
223239 };
224240
225241 public enum Kind {
226- VOID (1, Void.subcodec),
227- ROWS (2, Rows.subcodec),
228- SET_KEYSPACE (3, SetKeyspace.subcodec),
229- PREPARED (4, Prepared.subcodec),
242+ VOID(1, Void.subcodec),
243+ ROWS(2, Rows.subcodec),
244+ SET_KEYSPACE(3, SetKeyspace.subcodec),
245+ PREPARED(4, Prepared.subcodec),
230246 SCHEMA_CHANGE(5, SchemaChange.subcodec);
231247
232248 private final int id;
233249 final Message.Decoder<Result> subDecoder;
234250
235251 private static final Kind[] ids;
252+
236253 static {
237254 int maxId = -1;
238255 for (Kind k : Kind.values())
@@ -308,8 +325,7 @@
308325
309326 public static class Metadata {
310327
311- private static enum Flag
312- {
328+ private static enum Flag {
313329 // The order of that enum matters!!
314330 GLOBAL_TABLES_SPEC,
315331 HAS_MORE_PAGES,
@@ -362,7 +378,7 @@
362378 if (withPkIndices && (pkCount = body.readInt()) > 0) {
363379 pkIndices = new int[pkCount];
364380 for (int i = 0; i < pkCount; i++)
365- pkIndices[i] = (int)body.readShort();
381+ pkIndices[i] = (int) body.readShort();
366382 }
367383
368384 ByteBuffer state = null;
@@ -520,7 +536,7 @@
520536
521537 public static class SchemaChange extends Result {
522538
523- public enum Change { CREATED, UPDATED, DROPPED }
539+ public enum Change {CREATED, UPDATED, DROPPED}
524540
525541 public final Change change;
526542 public final SchemaElement targetType;
@@ -529,8 +545,7 @@
529545 public final List<String> targetSignature;
530546
531547 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
532- public Result decode(ByteBuf body, ProtocolVersion version, CodecRegistry codecRegistry)
533- {
548+ public Result decode(ByteBuf body, ProtocolVersion version, CodecRegistry codecRegistry) {
534549 // Note: the CREATE KEYSPACE/TABLE/TYPE SCHEMA_CHANGE response is different from the SCHEMA_CHANGE EVENT type
535550 Change change;
536551 SchemaElement targetType;
@@ -552,8 +567,8 @@
552567 targetKeyspace = CBUtil.readString(body);
553568 targetName = (targetType == KEYSPACE) ? "" : CBUtil.readString(body);
554569 targetSignature = (targetType == FUNCTION || targetType == AGGREGATE)
555- ? CBUtil.readStringList(body)
556- : Collections.<String>emptyList();
570+ ? CBUtil.readStringList(body)
571+ : Collections.<String>emptyList();
557572 return new SchemaChange(change, targetType, targetKeyspace, targetName, targetSignature);
558573 default:
559574 throw version.unsupported();
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 +12 −15
@@ -19,7 +19,7 @@
1919
2020 /**
2121 * A CQL Row returned in a {@link ResultSet}.
22- * <p>
22+ * <p/>
2323 * The values of a CQL Row can be retrieve by either index (index starts at 0)
2424 * or name. When setting them by name, names follow the case insensitivity
2525 * rules explained in {@link ColumnDefinitions}.
@@ -35,38 +35,36 @@
3535
3636 /**
3737 * Returns the {@code i}th value of this row as a {@link Token}.
38- * <p>
38+ * <p/>
3939 * {@link #getPartitionKeyToken()} should generally be preferred to this method (unless the
4040 * token column is aliased).
4141 *
4242 * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
4343 * @return the value of the {@code i}th column in this row as an Token.
44- *
4544 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
46- * @throws InvalidTypeException if column {@code i} is not of the type of token values
47- * for this cluster (this depends on the configured partitioner).
45+ * @throws InvalidTypeException if column {@code i} is not of the type of token values
46+ * for this cluster (this depends on the configured partitioner).
4847 */
4948 public Token getToken(int i);
5049
5150 /**
5251 * Returns the value of column {@code name} as a {@link Token}.
53- * <p>
52+ * <p/>
5453 * {@link #getPartitionKeyToken()} should generally be preferred to this method (unless the
5554 * token column is aliased).
5655 *
5756 * @param name the name of the column to retrieve.
5857 * @return the value of column {@code name} as a Token.
59- *
6058 * @throws IllegalArgumentException if {@code name} is not part of the
61- * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
62- * @throws InvalidTypeException if column {@code name} is not of the type of token values
63- * for this cluster (this depends on the configured partitioner).
59+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
60+ * @throws InvalidTypeException if column {@code name} is not of the type of token values
61+ * for this cluster (this depends on the configured partitioner).
6462 */
6563 public Token getToken(String name);
6664
6765 /**
6866 * Returns the value of the first column containing a {@link Token}.
69- * <p>
67+ * <p/>
7068 * This method is a shorthand for queries returning a single token in an unaliased
7169 * column. It will look for the first name matching {@code token(...)}:
7270 * <pre>
@@ -79,11 +77,10 @@
7977 * {@link #getToken(int)} or {@link #getToken(String)}.
8078 *
8179 * @return the value of column {@code name} as a Token.
82- *
8380 * @throws IllegalStateException if no column named {@code token(...)} exists in this
84- * ResultSet.
85- * @throws InvalidTypeException if the first column named {@code token(...)} is not of
86- * the type of token values for this cluster (this depends on the configured partitioner).
81+ * ResultSet.
82+ * @throws InvalidTypeException if the first column named {@code token(...)} is not of
83+ * the type of token values for this cluster (this depends on the configured partitioner).
8784 */
8885 public Token getPartitionKeyToken();
8986
modified driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java +2 −2
@@ -28,10 +28,10 @@
2828
2929 /**
3030 * Creates a new SSL handler for the given Netty channel.
31- * <p>
31+ * <p/>
3232 * This gets called each time the driver opens a new connection to a Cassandra host. The newly created handler will be added
3333 * to the channel's pipeline to provide SSL support for the connection.
34- * <p>
34+ * <p/>
3535 * You don't necessarily need to implement this method directly; see the provided implementations: {@link JdkSSLOptions} and
3636 * {@link NettySSLOptions}.
3737 *
modified driver-core/src/main/java/com/datastax/driver/core/SanityChecks.java +10 −10
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.reflect.TypeToken;
19+
1820 import java.lang.reflect.ParameterizedType;
1921 import java.lang.reflect.Type;
2022 import java.util.Map;
2123
22-import com.google.common.reflect.TypeToken;
23-
2424 class SanityChecks {
2525
2626 /**
@@ -47,22 +47,22 @@
4747 */
4848 static void checkGuava() {
4949 boolean resolved = false;
50- TypeToken<Map<String,String>> mapOfString = TypeTokens.mapOf(String.class, String.class);
50+ TypeToken<Map<String, String>> mapOfString = TypeTokens.mapOf(String.class, String.class);
5151 Type type = mapOfString.getType();
52- if(type instanceof ParameterizedType) {
53- ParameterizedType pType = (ParameterizedType)type;
52+ if (type instanceof ParameterizedType) {
53+ ParameterizedType pType = (ParameterizedType) type;
5454 Type[] types = pType.getActualTypeArguments();
55- if(types.length == 2) {
55+ if (types.length == 2) {
5656 TypeToken valueType = TypeToken.of(types[1]);
5757 resolved = valueType.getRawType().equals(String.class);
5858 }
5959 }
6060
61- if(!resolved) {
61+ if (!resolved) {
6262 throw new IllegalStateException(
63- "Detected Guava issue #1635 which indicates that a version of Guava less than 16.01 is in use. "
64- + "This introduces codec resolution issues and potentially other incompatibility issues in the driver. "
65- + "Please upgrade to Guava 16.01 or later.");
63+ "Detected Guava issue #1635 which indicates that a version of Guava less than 16.01 is in use. "
64+ + "This introduces codec resolution issues and potentially other incompatibility issues in the driver. "
65+ + "Please upgrade to Guava 16.01 or later.");
6666 }
6767 }
6868
modified driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java +8 −8
@@ -17,10 +17,10 @@
1717
1818 /**
1919 * Interface for objects that are interested in tracking schema change events in the cluster.
20- * <p>
20+ * <p/>
2121 * An implementation of this interface can be registered against a Cluster
2222 * object through the {@link com.datastax.driver.core.Cluster#register(SchemaChangeListener)} method.
23- * <p>
23+ * <p/>
2424 * Note that the methods defined by this interface will be executed by internal driver threads, and are
2525 * therefore expected to have short execution times. If you need to perform long computations or blocking
2626 * calls in response to schema change events, it is strongly recommended to schedule them asynchronously
@@ -45,7 +45,7 @@
4545 /**
4646 * Called when a keyspace has changed.
4747 *
48- * @param current the keyspace that has changed, in its current form (after the change).
48+ * @param current the keyspace that has changed, in its current form (after the change).
4949 * @param previous the keyspace that has changed, in its previous form (before the change).
5050 */
5151 void onKeyspaceChanged(KeyspaceMetadata current, KeyspaceMetadata previous);
@@ -67,7 +67,7 @@
6767 /**
6868 * Called when a table has changed.
6969 *
70- * @param current the table that has changed, in its current form (after the change).
70+ * @param current the table that has changed, in its current form (after the change).
7171 * @param previous the table that has changed, in its previous form (before the change).
7272 */
7373 void onTableChanged(TableMetadata current, TableMetadata previous);
@@ -89,7 +89,7 @@
8989 /**
9090 * Called when a user-defined type has changed.
9191 *
92- * @param current the type that has changed, in its current form (after the change).
92+ * @param current the type that has changed, in its current form (after the change).
9393 * @param previous the type that has changed, in its previous form (before the change).
9494 */
9595 void onUserTypeChanged(UserType current, UserType previous);
@@ -111,7 +111,7 @@
111111 /**
112112 * Called when a user-defined function has changed.
113113 *
114- * @param current the function that has changed, in its current form (after the change).
114+ * @param current the function that has changed, in its current form (after the change).
115115 * @param previous the function that has changed, in its previous form (before the change).
116116 */
117117 void onFunctionChanged(FunctionMetadata current, FunctionMetadata previous);
@@ -133,7 +133,7 @@
133133 /**
134134 * Called when a user-defined aggregate has changed.
135135 *
136- * @param current the aggregate that has changed, in its current form (after the change).
136+ * @param current the aggregate that has changed, in its current form (after the change).
137137 * @param previous the aggregate that has changed, in its previous form (before the change).
138138 */
139139 void onAggregateChanged(AggregateMetadata current, AggregateMetadata previous);
@@ -155,7 +155,7 @@
155155 /**
156156 * Called when a materialized view has changed.
157157 *
158- * @param current the materialized view that has changed, in its current form (after the change).
158+ * @param current the materialized view that has changed, in its current form (after the change).
159159 * @param previous the materialized view that has changed, in its previous form (before the change).
160160 */
161161 void onMaterializedViewChanged(MaterializedViewMetadata current, MaterializedViewMetadata previous);
modified driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +59 −60
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-import java.util.concurrent.ExecutionException;
20-
18+import com.datastax.driver.core.exceptions.BusyConnectionException;
19+import com.datastax.driver.core.exceptions.ConnectionException;
2120 import com.google.common.collect.Lists;
2221 import com.google.common.collect.Maps;
2322 import org.slf4j.Logger;
2423 import org.slf4j.LoggerFactory;
2524
26-import com.datastax.driver.core.exceptions.BusyConnectionException;
27-import com.datastax.driver.core.exceptions.ConnectionException;
25+import java.util.*;
26+import java.util.concurrent.ExecutionException;
2827
2928 import static com.datastax.driver.core.SchemaElement.*;
3029
@@ -38,21 +37,21 @@
3837 private static final SchemaParser V3_PARSER = new V3SchemaParser();
3938
4039 static SchemaParser forVersion(VersionNumber cassandraVersion) {
41- if(cassandraVersion.getMajor() >= 3) return V3_PARSER;
40+ if (cassandraVersion.getMajor() >= 3) return V3_PARSER;
4241 return V2_PARSER;
4342 }
4443
4544 abstract SystemRows fetchSystemRows(Cluster cluster,
4645 SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature,
4746 Connection connection, VersionNumber cassandraVersion)
48- throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException;
47+ throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException;
4948
5049 abstract String tableNameColumn();
5150
5251 void refresh(Cluster cluster,
5352 SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature,
5453 Connection connection, VersionNumber cassandraVersion)
55- throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
54+ throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
5655
5756 SystemRows rows = fetchSystemRows(cluster, targetType, targetKeyspace, targetName, targetSignature, connection, cassandraVersion);
5857
@@ -71,7 +70,7 @@
7170 // wrong. Log an error and schedule a full schema rebuild.
7271 if (keyspace == null) {
7372 logger.info(String.format("Asked to rebuild %s %s.%s but I don't know keyspace %s",
74- targetType, targetKeyspace, targetName, targetKeyspace));
73+ targetType, targetKeyspace, targetName, targetKeyspace));
7574 metadata.cluster.submitSchemaRefresh(null, null, null, null);
7675 } else {
7776 switch (targetType) {
@@ -179,8 +178,8 @@
179178 } catch (RuntimeException e) {
180179 // See #refresh for why we'd rather not propagate this further
181180 logger.error(String.format("Error parsing schema for table %s.%s: "
182- + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
183- keyspace.getName(), cfName, keyspace.getName(), cfName), e);
181+ + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
182+ keyspace.getName(), cfName, keyspace.getName(), cfName), e);
184183 }
185184 }
186185 }
@@ -242,13 +241,13 @@
242241 continue; // we probably raced, we will update the metadata next time
243242
244243 MaterializedViewMetadata view = MaterializedViewMetadata.build(keyspace, viewRow, cols, cassandraVersion, cluster);
245- if(view != null)
244+ if (view != null)
246245 views.put(view.getName(), view);
247246 } catch (RuntimeException e) {
248247 // See #refresh for why we'd rather not propagate this further
249248 logger.error(String.format("Error parsing schema for view %s.%s: "
250- + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\") will be missing or incomplete",
251- keyspace.getName(), viewName, keyspace.getName(), viewName), e);
249+ + "Cluster.getMetadata().getKeyspace(\"%s\").getView(\"%s\") will be missing or incomplete",
250+ keyspace.getName(), viewName, keyspace.getName(), viewName), e);
252251 }
253252 }
254253 }
@@ -438,7 +437,7 @@
438437 return Collections.emptyMap();
439438
440439 Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> result =
441- new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>();
440+ new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>();
442441 for (Row row : rs) {
443442 String ksName = row.getString(KeyspaceMetadata.KS_NAME);
444443 String cfName = row.getString(tableName);
@@ -497,20 +496,20 @@
497496
498497 private static class V2SchemaParser extends SchemaParser {
499498
500- private static final String SELECT_KEYSPACES = "SELECT * FROM system.schema_keyspaces";
499+ private static final String SELECT_KEYSPACES = "SELECT * FROM system.schema_keyspaces";
501500 private static final String SELECT_COLUMN_FAMILIES = "SELECT * FROM system.schema_columnfamilies";
502- private static final String SELECT_COLUMNS = "SELECT * FROM system.schema_columns";
503- private static final String SELECT_USERTYPES = "SELECT * FROM system.schema_usertypes";
504- private static final String SELECT_FUNCTIONS = "SELECT * FROM system.schema_functions";
505- private static final String SELECT_AGGREGATES = "SELECT * FROM system.schema_aggregates";
501+ private static final String SELECT_COLUMNS = "SELECT * FROM system.schema_columns";
502+ private static final String SELECT_USERTYPES = "SELECT * FROM system.schema_usertypes";
503+ private static final String SELECT_FUNCTIONS = "SELECT * FROM system.schema_functions";
504+ private static final String SELECT_AGGREGATES = "SELECT * FROM system.schema_aggregates";
506505
507- private static final String CF_NAME = "columnfamily_name";
506+ private static final String CF_NAME = "columnfamily_name";
508507
509508 @Override
510509 SystemRows fetchSystemRows(Cluster cluster,
511510 SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature,
512511 Connection connection, VersionNumber cassandraVersion)
513- throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
512+ throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
514513
515514 boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE);
516515
@@ -528,11 +527,11 @@
528527 }
529528
530529 ResultSetFuture ksFuture = null,
531- udtFuture = null,
532- cfFuture = null,
533- colsFuture = null,
534- functionsFuture = null,
535- aggregatesFuture = null;
530+ udtFuture = null,
531+ cfFuture = null,
532+ colsFuture = null,
533+ functionsFuture = null,
534+ aggregatesFuture = null;
536535
537536 ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
538537
@@ -554,14 +553,14 @@
554553 aggregatesFuture = queryAsync(SELECT_AGGREGATES + whereClause, connection, protocolVersion);
555554
556555 return new SystemRows(get(ksFuture),
557- groupByKeyspace(get(cfFuture)),
558- groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, CF_NAME),
559- groupByKeyspace(get(udtFuture)),
560- groupByKeyspace(get(functionsFuture)),
561- groupByKeyspace(get(aggregatesFuture)),
562- // No views nor separate indexes table in Cassandra 2:
563- Collections.<String, List<Row>>emptyMap(),
564- Collections.<String, Map<String, List<Row>>>emptyMap());
556+ groupByKeyspace(get(cfFuture)),
557+ groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, CF_NAME),
558+ groupByKeyspace(get(udtFuture)),
559+ groupByKeyspace(get(functionsFuture)),
560+ groupByKeyspace(get(aggregatesFuture)),
561+ // No views nor separate indexes table in Cassandra 2:
562+ Collections.<String, List<Row>>emptyMap(),
563+ Collections.<String, Map<String, List<Row>>>emptyMap());
565564 }
566565
567566 @Override
@@ -581,31 +580,31 @@
581580
582581 private static class V3SchemaParser extends SchemaParser {
583582
584- private static final String SELECT_KEYSPACES = "SELECT * FROM system_schema.keyspaces";
585- private static final String SELECT_TABLES = "SELECT * FROM system_schema.tables";
586- private static final String SELECT_COLUMNS = "SELECT * FROM system_schema.columns";
587- private static final String SELECT_USERTYPES = "SELECT * FROM system_schema.types";
588- private static final String SELECT_FUNCTIONS = "SELECT * FROM system_schema.functions";
589- private static final String SELECT_AGGREGATES = "SELECT * FROM system_schema.aggregates";
590- private static final String SELECT_INDEXES = "SELECT * FROM system_schema.indexes";
591- private static final String SELECT_VIEWS = "SELECT * FROM system_schema.views";
583+ private static final String SELECT_KEYSPACES = "SELECT * FROM system_schema.keyspaces";
584+ private static final String SELECT_TABLES = "SELECT * FROM system_schema.tables";
585+ private static final String SELECT_COLUMNS = "SELECT * FROM system_schema.columns";
586+ private static final String SELECT_USERTYPES = "SELECT * FROM system_schema.types";
587+ private static final String SELECT_FUNCTIONS = "SELECT * FROM system_schema.functions";
588+ private static final String SELECT_AGGREGATES = "SELECT * FROM system_schema.aggregates";
589+ private static final String SELECT_INDEXES = "SELECT * FROM system_schema.indexes";
590+ private static final String SELECT_VIEWS = "SELECT * FROM system_schema.views";
592591
593592 private static final String TABLE_NAME = "table_name";
594593
595594 @Override
596595 SystemRows fetchSystemRows(Cluster cluster, SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature, Connection connection, VersionNumber cassandraVersion)
597- throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
596+ throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
598597
599598 boolean isSchemaOrKeyspace = (targetType == null || targetType == KEYSPACE);
600599
601600 ResultSetFuture ksFuture = null,
602- udtFuture = null,
603- cfFuture = null,
604- colsFuture = null,
605- functionsFuture = null,
606- aggregatesFuture = null,
607- indexesFuture = null,
608- viewsFuture = null;
601+ udtFuture = null,
602+ cfFuture = null,
603+ colsFuture = null,
604+ functionsFuture = null,
605+ aggregatesFuture = null,
606+ indexesFuture = null,
607+ viewsFuture = null;
609608
610609 ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
611610
@@ -629,13 +628,13 @@
629628 aggregatesFuture = queryAsync(SELECT_AGGREGATES + whereClause(targetType, targetKeyspace, targetName, targetSignature), connection, protocolVersion);
630629
631630 return new SystemRows(get(ksFuture),
632- groupByKeyspace(get(cfFuture)),
633- groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, TABLE_NAME),
634- groupByKeyspace(get(udtFuture)),
635- groupByKeyspace(get(functionsFuture)),
636- groupByKeyspace(get(aggregatesFuture)),
637- groupByKeyspace(get(viewsFuture)),
638- groupByKeyspaceAndCf(get(indexesFuture), TABLE_NAME));
631+ groupByKeyspace(get(cfFuture)),
632+ groupByKeyspaceAndCf(get(colsFuture), cassandraVersion, TABLE_NAME),
633+ groupByKeyspace(get(udtFuture)),
634+ groupByKeyspace(get(functionsFuture)),
635+ groupByKeyspace(get(aggregatesFuture)),
636+ groupByKeyspace(get(viewsFuture)),
637+ groupByKeyspaceAndCf(get(indexesFuture), TABLE_NAME));
639638 }
640639
641640 @Override
@@ -692,14 +691,14 @@
692691 }
693692
694693 private boolean references(DataType dataType, String typeName) {
695- if (dataType instanceof UserType.Shallow && ((UserType.Shallow)dataType).typeName.equals(typeName))
694+ if (dataType instanceof UserType.Shallow && ((UserType.Shallow) dataType).typeName.equals(typeName))
696695 return true;
697696 for (DataType arg : dataType.getTypeArguments()) {
698697 if (references(arg, typeName))
699698 return true;
700699 }
701700 if (dataType instanceof TupleType) {
702- for (DataType arg : ((TupleType)dataType).getComponentTypes()) {
701+ for (DataType arg : ((TupleType) dataType).getComponentTypes()) {
703702 if (references(arg, typeName))
704703 return true;
705704 }
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +81 −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,24 +62,23 @@
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 Session init();
8684
@@ -88,57 +86,54 @@
8886 * Initialize this session asynchronously.
8987 *
9088 * @return a future that will complete when the session is fully initialized.
91- *
9289 * @see #init()
9390 */
9491 ListenableFuture<Session> initAsync();
9592
9693 /**
9794 * Executes the provided query.
98- *
95+ * <p/>
9996 * This is a convenience method for {@code execute(new SimpleStatement(query))}.
10097 *
10198 * @param query the CQL query to execute.
10299 * @return the result of the query. That result will never be null but can
103100 * be empty (and will be for any non SELECT query).
104- *
105101 * @throws NoHostAvailableException if no host in the cluster can be
106- * contacted successfully to execute this query.
107- * @throws QueryExecutionException if the query triggered an execution
108- * exception, i.e. an exception thrown by Cassandra when it cannot execute
109- * the query with the requested consistency level successfully.
102+ * contacted successfully to execute this query.
103+ * @throws QueryExecutionException if the query triggered an execution
104+ * exception, i.e. an exception thrown by Cassandra when it cannot execute
105+ * the query with the requested consistency level successfully.
110106 * @throws QueryValidationException if the query if invalid (syntax error,
111- * unauthorized or any other validation problem).
107+ * unauthorized or any other validation problem).
112108 */
113109 ResultSet execute(String query);
114110
115111 /**
116112 * Executes the provided query using the provided value.
117- *
113+ * <p/>
118114 * This is a convenience method for {@code execute(new SimpleStatement(query, values))}.
119115 *
120- * @param query the CQL query to execute.
116+ * @param query the CQL query to execute.
121117 * @param values values required for the execution of {@code query}. See
122- * {@link SimpleStatement(String, Object...)} for more detail.
118+ * {@link SimpleStatement(String, Object...)} for more detail.
123119 * @return the result of the query. That result will never be null but can
124120 * be empty (and will be for any non SELECT query).
125- *
126- * @throws NoHostAvailableException if no host in the cluster can be
127- * contacted successfully to execute this query.
128- * @throws QueryExecutionException if the query triggered an execution
129- * exception, i.e. an exception thrown by Cassandra when it cannot execute
130- * the query with the requested consistency level successfully.
131- * @throws QueryValidationException if the query if invalid (syntax error,
132- * unauthorized or any other validation problem).
121+ * @throws NoHostAvailableException if no host in the cluster can be
122+ * contacted successfully to execute this query.
123+ * @throws QueryExecutionException if the query triggered an execution
124+ * exception, i.e. an exception thrown by Cassandra when it cannot execute
125+ * the query with the requested consistency level successfully.
126+ * @throws QueryValidationException if the query if invalid (syntax error,
127+ * unauthorized or any other validation problem).
133128 * @throws UnsupportedFeatureException if version 1 of the protocol
134- * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
135- * or you use Cassandra 1.2).
129+ * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
130+ * or you use Cassandra 1.2).
136131 */
137132 ResultSet execute(String query, Object... values);
138133
139134 /**
140135 * Executes the provided query.
141- *
136+ * <p/>
142137 * This method blocks until at least some result has been received from the
143138 * database. However, for SELECT queries, it does not guarantee that the
144139 * result has been received in full. But it does guarantee that some
@@ -149,24 +144,23 @@
149144 * @param statement the CQL query to execute (that can be any {@code Statement}).
150145 * @return the result of the query. That result will never be null but can
151146 * be empty (and will be for any non SELECT query).
152- *
153- * @throws NoHostAvailableException if no host in the cluster can be
154- * contacted successfully to execute this query.
155- * @throws QueryExecutionException if the query triggered an execution
156- * exception, i.e. an exception thrown by Cassandra when it cannot execute
157- * the query with the requested consistency level successfully.
158- * @throws QueryValidationException if the query if invalid (syntax error,
159- * unauthorized or any other validation problem).
147+ * @throws NoHostAvailableException if no host in the cluster can be
148+ * contacted successfully to execute this query.
149+ * @throws QueryExecutionException if the query triggered an execution
150+ * exception, i.e. an exception thrown by Cassandra when it cannot execute
151+ * the query with the requested consistency level successfully.
152+ * @throws QueryValidationException if the query if invalid (syntax error,
153+ * unauthorized or any other validation problem).
160154 * @throws UnsupportedFeatureException if the protocol version 1 is in use and
161- * a feature not supported has been used. Features that are not supported by
162- * the version protocol 1 include: BatchStatement, ResultSet paging and binary
163- * values in RegularStatement.
155+ * a feature not supported has been used. Features that are not supported by
156+ * the version protocol 1 include: BatchStatement, ResultSet paging and binary
157+ * values in RegularStatement.
164158 */
165159 ResultSet execute(Statement statement);
166160
167161 /**
168162 * Executes the provided query asynchronously.
169- * <p>
163+ * <p/>
170164 * This is a convenience method for {@code executeAsync(new SimpleStatement(query))}.
171165 *
172166 * @param query the CQL query to execute.
@@ -176,40 +170,38 @@
176170
177171 /**
178172 * Executes the provided query asynchronously using the provided values.
179- *
173+ * <p/>
180174 * This is a convenience method for {@code executeAsync(new SimpleStatement(query, values))}.
181175 *
182- * @param query the CQL query to execute.
176+ * @param query the CQL query to execute.
183177 * @param values values required for the execution of {@code query}. See
184- * {@link SimpleStatement(String, Object...)} for more detail.
178+ * {@link SimpleStatement(String, Object...)} for more detail.
185179 * @return a future on the result of the query.
186- *
187180 * @throws UnsupportedFeatureException if version 1 of the protocol
188- * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
189- * or you use Cassandra 1.2).
181+ * is in use (i.e. if you've force version 1 through {@link Cluster.Builder#withProtocolVersion}
182+ * or you use Cassandra 1.2).
190183 */
191184 ResultSetFuture executeAsync(String query, Object... values);
192185
193186 /**
194187 * Executes the provided query asynchronously.
195- *
188+ * <p/>
196189 * This method does not block. It returns as soon as the query has been
197190 * passed to the underlying network stack. In particular, returning from
198191 * this method does not guarantee that the query is valid or has even been
199192 * submitted to a live node. Any exception pertaining to the failure of the
200193 * query will be thrown when accessing the {@link ResultSetFuture}.
201- * <p>
194+ * <p/>
202195 * Note that for queries that doesn't return a result (INSERT, UPDATE and
203196 * DELETE), you will need to access the ResultSetFuture (that is call one of
204197 * its get method to make sure the query was successful.
205198 *
206199 * @param statement the CQL query to execute (that can be either any {@code Statement}.
207200 * @return a future on the result of the query.
208- *
209201 * @throws UnsupportedFeatureException if the protocol version 1 is in use and
210- * a feature not supported has been used. Features that are not supported by
211- * the version protocol 1 include: BatchStatement, ResultSet paging and binary
212- * values in RegularStatement.
202+ * a feature not supported has been used. Features that are not supported by
203+ * the version protocol 1 include: BatchStatement, ResultSet paging and binary
204+ * values in RegularStatement.
213205 */
214206 ResultSetFuture executeAsync(Statement statement);
215207
@@ -218,15 +210,14 @@
218210 *
219211 * @param query the CQL query string to prepare
220212 * @return the prepared statement corresponding to {@code query}.
221- *
222213 * @throws NoHostAvailableException if no host in the cluster can be
223- * contacted successfully to prepare this query.
214+ * contacted successfully to prepare this query.
224215 */
225216 PreparedStatement prepare(String query);
226217
227218 /**
228219 * Prepares the provided query.
229- * <p>
220+ * <p/>
230221 * This method behaves like {@link #prepare(String)},
231222 * but note that the resulting {@code PreparedStatement} will inherit the query properties
232223 * set on {@code statement}. Concretely, this means that in the following code:
@@ -236,7 +227,7 @@
236227 * session.execute(prepared.bind("someValue"));
237228 * </pre>
238229 * the final execution will be performed with Quorum consistency.
239- * <p>
230+ * <p/>
240231 * Please note that if the same CQL statement is prepared more than once, all
241232 * calls to this method will return the same {@code PreparedStatement} object
242233 * but the method will still apply the properties of the prepared
@@ -244,19 +235,18 @@
244235 *
245236 * @param statement the statement to prepare
246237 * @return the prepared statement corresponding to {@code statement}.
247- *
248238 * @throws NoHostAvailableException if no host in the cluster can be
249- * contacted successfully to prepare this statement.
239+ * contacted successfully to prepare this statement.
250240 * @throws IllegalArgumentException if {@code statement.getValues() != null}
251- * (values for executing a prepared statement should be provided after preparation
252- * though the {@link PreparedStatement#bind} method or through a corresponding
253- * {@link BoundStatement}).
241+ * (values for executing a prepared statement should be provided after preparation
242+ * though the {@link PreparedStatement#bind} method or through a corresponding
243+ * {@link BoundStatement}).
254244 */
255245 PreparedStatement prepare(RegularStatement statement);
256246
257247 /**
258248 * Prepares the provided query string asynchronously.
259- * <p>
249+ * <p/>
260250 * This method is equivalent to {@link #prepare(String)} except that it
261251 * does not block but return a future instead. Any error during preparation will
262252 * be thrown when accessing the future, not by this method itself.
@@ -277,7 +267,7 @@
277267 * session.execute(prepared.bind("someValue"));
278268 * </pre>
279269 * the final execution will be performed with Quorum consistency.
280- * <p>
270+ * <p/>
281271 * Please note that if the same CQL statement is prepared more than once, all
282272 * calls to this method will return the same {@code PreparedStatement} object
283273 * but the method will still apply the properties of the prepared
@@ -285,31 +275,29 @@
285275 *
286276 * @param statement the statement to prepare
287277 * @return a future on the prepared statement corresponding to {@code statement}.
288- *
289- * @see Session#prepare(RegularStatement)
290- *
291278 * @throws IllegalArgumentException if {@code statement.getValues() != null}
292- * (values for executing a prepared statement should be provided after preparation
293- * though the {@link PreparedStatement#bind} method or through a corresponding
294- * {@link BoundStatement}).
279+ * (values for executing a prepared statement should be provided after preparation
280+ * though the {@link PreparedStatement#bind} method or through a corresponding
281+ * {@link BoundStatement}).
282+ * @see Session#prepare(RegularStatement)
295283 */
296284 ListenableFuture<PreparedStatement> prepareAsync(RegularStatement statement);
297285
298286 /**
299287 * Initiates a shutdown of this session instance.
300- * <p>
288+ * <p/>
301289 * This method is asynchronous and return a future on the completion
302290 * of the shutdown process. As soon a the session is shutdown, no
303291 * new request will be accepted, but already submitted queries are
304292 * allowed to complete. This method closes all connections of this
305293 * session and reclaims all resources used by it.
306- * <p>
294+ * <p/>
307295 * If for some reason you wish to expedite this process, the
308296 * {@link CloseFuture#force} can be called on the result future.
309- * <p>
297+ * <p/>
310298 * This method has no particular effect if the session was already closed
311299 * (in which case the returned future will return immediately).
312- * <p>
300+ * <p/>
313301 * Note that this method does not close the corresponding {@code Cluster}
314302 * instance (which holds additional resources, in particular internal
315303 * executors that must be shut down in order for the client program to
@@ -324,9 +312,9 @@
324312 /**
325313 * Initiates a shutdown of this session instance and blocks until
326314 * that shutdown completes.
327- * <p>
315+ * <p/>
328316 * This method is a shortcut for {@code closeAsync().get()}.
329- * <p>
317+ * <p/>
330318 * Note that this method does not close the corresponding {@code Cluster}
331319 * instance (which holds additional resources, in particular internal
332320 * executors that must be shut down in order for the client program to
@@ -339,7 +327,7 @@
339327
340328 /**
341329 * Whether this Session instance has been closed.
342- * <p>
330+ * <p/>
343331 * Note that this method returns true as soon as one closing this Session
344332 * has started but it does not guarantee that the closing is done. If you
345333 * want to guarantee that the closing is done, you can call {@code close()}
@@ -360,7 +348,7 @@
360348
361349 /**
362350 * Return a snapshot of the state of this Session.
363- * <p>
351+ * <p/>
364352 * The returned object provides information on which hosts the session is
365353 * connected to, how many connections are opened to each host, etc...
366354 * The returned object is immutable, it is a snapshot of the Session State
@@ -372,7 +360,7 @@
372360
373361 /**
374362 * The state of a Session.
375- * <p>
363+ * <p/>
376364 * This mostly exposes information on the connections maintained by a Session:
377365 * which host it is connected to, how many connection is has for each host, etc...
378366 */
@@ -387,7 +375,7 @@
387375 /**
388376 * The hosts to which the session is currently connected (more precisely, at the time
389377 * this State has been grabbed).
390- * <p>
378+ * <p/>
391379 * Please note that this method really returns the hosts for which the session currently
392380 * holds a connection pool. A such, it's unlikely but not impossible for a host to be listed
393381 * in the output of this method but to have {@code getOpenConnections} return 0, if the
@@ -399,7 +387,7 @@
399387
400388 /**
401389 * The number of open connections to a given host.
402- * <p>
390+ * <p/>
403391 * Note that this refers to <em>active</em> connections. The actual number of connections also
404392 * includes {@link #getTrashedConnections(Host)}.
405393 *
@@ -411,7 +399,7 @@
411399
412400 /**
413401 * The number of "trashed" connections to a given host.
414- * <p>
402+ * <p/>
415403 * When the load to a host decreases, the driver will reclaim some connections in order to save
416404 * resources. No requests are sent to these connections anymore, but they are kept open for an
417405 * additional amount of time ({@link PoolingOptions#getIdleTimeoutSeconds()}), in case the load
@@ -425,7 +413,7 @@
425413
426414 /**
427415 * The number of queries that are currently being executed though a given host.
428- * <p>
416+ * <p/>
429417 * This correspond to the number of queries that have been sent (by the session this
430418 * is a State of) to the Cassandra Host on one of its connection but haven't yet returned.
431419 * 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 +47 −45
@@ -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;
@@ -37,6 +24,21 @@
3724 import com.datastax.driver.core.policies.ReconnectionPolicy;
3825 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
3926 import com.datastax.driver.core.utils.MoreFutures;
27+import com.google.common.base.Functions;
28+import com.google.common.collect.ImmutableList;
29+import com.google.common.collect.Lists;
30+import com.google.common.util.concurrent.*;
31+import org.slf4j.Logger;
32+import org.slf4j.LoggerFactory;
33+
34+import java.net.InetSocketAddress;
35+import java.nio.ByteBuffer;
36+import java.util.*;
37+import java.util.concurrent.ConcurrentHashMap;
38+import java.util.concurrent.ConcurrentMap;
39+import java.util.concurrent.ExecutionException;
40+import java.util.concurrent.TimeUnit;
41+import java.util.concurrent.atomic.AtomicReference;
4042
4143 /**
4244 * Driver implementation of the Session interface.
@@ -84,14 +86,14 @@
8486 Collection<Host> hosts = cluster.getMetadata().allHosts();
8587 ListenableFuture<?> allPoolsCreatedFuture = createPools(hosts);
8688 ListenableFuture<?> allPoolsUpdatedFuture = Futures.transform(allPoolsCreatedFuture,
87- new AsyncFunction<Object, Object>() {
88- @Override
89- @SuppressWarnings("unchecked")
90- public ListenableFuture<Object> apply(Object input) throws Exception {
91- isInit = true;
92- return (ListenableFuture<Object>)updateCreatedPools();
93- }
94- });
89+ new AsyncFunction<Object, Object>() {
90+ @Override
91+ @SuppressWarnings("unchecked")
92+ public ListenableFuture<Object> apply(Object input) throws Exception {
93+ isInit = true;
94+ return (ListenableFuture<Object>) updateCreatedPools();
95+ }
96+ });
9597
9698 Futures.addCallback(allPoolsUpdatedFuture, new FutureCallback<Object>() {
9799 @Override
@@ -167,8 +169,8 @@
167169 future = new CloseFuture.Forwarding(futures);
168170
169171 return closeFuture.compareAndSet(null, future)
170- ? future
171- : closeFuture.get(); // We raced, it's ok, return the future that was actually set
172+ ? future
173+ : closeFuture.get(); // We raced, it's ok, return the future that was actually set
172174 }
173175
174176 public boolean isClosed() {
@@ -188,10 +190,10 @@
188190 public ListenableFuture<PreparedStatement> apply(Response response) {
189191 switch (response.type) {
190192 case RESULT:
191- Responses.Result rm = (Responses.Result)response;
193+ Responses.Result rm = (Responses.Result) response;
192194 switch (rm.kind) {
193195 case PREPARED:
194- Responses.Result.Prepared pmsg = (Responses.Result.Prepared)rm;
196+ Responses.Result.Prepared pmsg = (Responses.Result.Prepared) rm;
195197 PreparedStatement stmt = DefaultPreparedStatement.fromMessage(pmsg, cluster, query, poolsState.keyspace);
196198 stmt = cluster.manager.addPrepared(stmt);
197199 if (cluster.getConfiguration().getQueryOptions().isPrepareOnAllHosts()) {
@@ -203,14 +205,14 @@
203205 }
204206 default:
205207 return Futures.immediateFailedFuture(
206- new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind)));
208+ new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind)));
207209 }
208210 case ERROR:
209211 return Futures.immediateFailedFuture(
210- ((Responses.Error)response).asException(future.getAddress()));
212+ ((Responses.Error) response).asException(future.getAddress()));
211213 default:
212214 return Futures.immediateFailedFuture(
213- new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type)));
215+ new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type)));
214216 }
215217 }
216218 });
@@ -358,10 +360,10 @@
358360 @Override
359361 public void onFailure(Throwable t) {
360362 if (t instanceof UnsupportedProtocolVersionException) {
361- cluster.manager.logUnsupportedVersionProtocol(host, ((UnsupportedProtocolVersionException)t).getUnsupportedVersion());
363+ cluster.manager.logUnsupportedVersionProtocol(host, ((UnsupportedProtocolVersionException) t).getUnsupportedVersion());
362364 cluster.manager.triggerOnDown(host, false);
363365 } else if (t instanceof ClusterNameMismatchException) {
364- ClusterNameMismatchException e = (ClusterNameMismatchException)t;
366+ ClusterNameMismatchException e = (ClusterNameMismatchException) t;
365367 cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
366368 cluster.manager.triggerOnDown(host, false);
367369 } else {
@@ -378,8 +380,8 @@
378380 CloseFuture removePool(Host host) {
379381 final HostConnectionPool pool = pools.remove(host);
380382 return pool == null
381- ? CloseFuture.immediateFuture()
382- : pool.closeAsync();
383+ ? CloseFuture.immediateFuture()
384+ : pool.closeAsync();
383385 }
384386
385387 /*
@@ -522,18 +524,18 @@
522524 }
523525
524526 if (statement instanceof StatementWrapper)
525- statement = ((StatementWrapper)statement).getWrappedStatement();
527+ statement = ((StatementWrapper) statement).getWrappedStatement();
526528
527529 Message.Request request;
528530
529531 if (statement instanceof RegularStatement) {
530- RegularStatement rs = (RegularStatement)statement;
532+ RegularStatement rs = (RegularStatement) statement;
531533
532534 // It saddens me that we special case for the query builder here, but for now this is simpler.
533535 // We could provide a general API in RegularStatement instead at some point but it's unclear what's
534536 // the cleanest way to do that is right now (and it's probably not really that useful anyway).
535537 if (protocolVersion == ProtocolVersion.V1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement)
536- ((com.datastax.driver.core.querybuilder.BuiltStatement)rs).setForceNoValues(true);
538+ ((com.datastax.driver.core.querybuilder.BuiltStatement) rs).setForceNoValues(true);
537539
538540 ByteBuffer[] rawValues = rs.getValues(protocolVersion, codecRegistry);
539541
@@ -545,19 +547,19 @@
545547 String qString = rs.getQueryString();
546548
547549 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, values, false,
548- fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
549- request = new Requests.Query(qString, options, statement.isTracing());
550+ fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
551+ request = new Requests.Query(qString, options, statement.isTracing());
550552 } else if (statement instanceof BoundStatement) {
551- BoundStatement bs = (BoundStatement)statement;
553+ BoundStatement bs = (BoundStatement) statement;
552554 if (!cluster.manager.preparedQueries.containsKey(bs.statement.getPreparedId().id)) {
553555 throw new InvalidQueryException(String.format("Tried to execute unknown prepared query : %s. "
554- + "You may have used a PreparedStatement that was created with another Cluster instance.", bs.statement.getPreparedId().id));
556+ + "You may have used a PreparedStatement that was created with another Cluster instance.", bs.statement.getPreparedId().id));
555557 }
556558 if (protocolVersion.compareTo(ProtocolVersion.V4) < 0)
557559 bs.ensureAllSet();
558560 boolean skipMetadata = protocolVersion != ProtocolVersion.V1 && bs.statement.getPreparedId().resultSetMetadata != null;
559561 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, Arrays.asList(bs.wrapper.values), skipMetadata,
560- fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
562+ fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
561563 request = new Requests.Execute(bs.statement.getPreparedId().id, options, statement.isTracing());
562564 } else {
563565 assert statement instanceof BatchStatement : statement;
@@ -566,12 +568,12 @@
566568 if (protocolVersion == ProtocolVersion.V1)
567569 throw new UnsupportedFeatureException(protocolVersion, "Protocol level batching is not supported");
568570
569- BatchStatement bs = (BatchStatement)statement;
571+ BatchStatement bs = (BatchStatement) statement;
570572 if (protocolVersion.compareTo(ProtocolVersion.V4) < 0)
571573 bs.ensureAllSet();
572574 BatchStatement.IdAndValues idAndVals = bs.getIdAndValues(protocolVersion, codecRegistry);
573575 Requests.BatchProtocolOptions options = new Requests.BatchProtocolOptions(consistency, serialConsistency, defaultTimestamp);
574- request = new Requests.Batch(bs.batchType, idAndVals.ids, idAndVals.values, options, statement.isTracing());
576+ request = new Requests.Batch(bs.batchType, idAndVals.ids, idAndVals.values, options, statement.isTracing());
575577 }
576578
577579 request.setCustomPayload(statement.getOutgoingPayload());
@@ -580,7 +582,7 @@
580582
581583 /**
582584 * Execute the provided request.
583- *
585+ * <p/>
584586 * This method will find a suitable node to connect to using the
585587 * {@link LoadBalancingPolicy} and handle host failover.
586588 */
@@ -627,8 +629,8 @@
627629 }
628630 // Return the statement when all futures are done
629631 return Futures.transform(
630- Futures.successfulAsList(futures),
631- Functions.constant(statement));
632+ Futures.successfulAsList(futures),
633+ Functions.constant(statement));
632634 }
633635
634636 ResultSetFuture executeQuery(Message.Request msg, Statement statement) {
modified driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java +138 −168
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.CodecNotFoundException;
19+import com.datastax.driver.core.exceptions.InvalidTypeException;
20+import com.google.common.reflect.TypeToken;
21+
1822 import java.math.BigDecimal;
1923 import java.math.BigInteger;
2024 import java.net.InetAddress;
2125 import java.nio.ByteBuffer;
2226 import java.util.*;
2327
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.CodecNotFoundException;
27-import com.datastax.driver.core.exceptions.InvalidTypeException;
28-
2928 /**
3029 * Collection of (typed) CQL values that can set by index (starting a 0).
3130 */
@@ -33,7 +32,7 @@
3332
3433 /**
3534 * Sets the {@code i}th value to the provided boolean.
36- * <p>
35+ * <p/>
3736 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
3837 * to the underlying CQL type (for CQL type {@code boolean}, this will be the built-in codec).
3938 *
@@ -41,16 +40,15 @@
4140 * @param v the value to set. To set the value to NULL, use {@link #setToNull(int)} or
4241 * {@code set(i, v, Boolean.class)}
4342 * @return this object.
44- *
4543 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
46- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
47- * underlying CQL type.
44+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
45+ * underlying CQL type.
4846 */
4947 public T setBool(int i, boolean v);
5048
5149 /**
5250 * Set the {@code i}th value to the provided byte.
53- * <p>
51+ * <p/>
5452 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
5553 * to the underlying CQL type (for CQL type {@code tinyint}, this will be the built-in codec).
5654 *
@@ -58,16 +56,15 @@
5856 * @param v the value to set. To set the value to NULL, use {@link #setToNull(int)} or
5957 * {@code set(i, v, Byte.class)}
6058 * @return this object.
61- *
6259 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
63- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
64- * underlying CQL type.
60+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
61+ * underlying CQL type.
6562 */
6663 public T setByte(int i, byte v);
6764
6865 /**
6966 * Set the {@code i}th value to the provided short.
70- * <p>
67+ * <p/>
7168 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
7269 * to the underlying CQL type (for CQL type {@code smallint}, this will be the built-in codec).
7370 *
@@ -75,16 +72,15 @@
7572 * @param v the value to set. To set the value to NULL, use {@link #setToNull(int)} or
7673 * {@code set(i, v, Short.class)}
7774 * @return this object.
78- *
7975 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
80- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
81- * underlying CQL type.
76+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
77+ * underlying CQL type.
8278 */
8379 public T setShort(int i, short v);
8480
8581 /**
8682 * Set the {@code i}th value to the provided integer.
87- * <p>
83+ * <p/>
8884 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
8985 * to the underlying CQL type (for CQL type {@code int}, this will be the built-in codec).
9086 *
@@ -92,16 +88,15 @@
9288 * @param v the value to set. To set the value to NULL, use {@link #setToNull(int)} or
9389 * {@code set(i, v, Integer.class)}
9490 * @return this object.
95- *
9691 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
97- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
98- * underlying CQL type.
92+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
93+ * underlying CQL type.
9994 */
10095 public T setInt(int i, int v);
10196
10297 /**
10398 * Sets the {@code i}th value to the provided long.
104- * <p>
99+ * <p/>
105100 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
106101 * to the underlying CQL type (for CQL type {@code bigint}, this will be the built-in codec).
107102 *
@@ -109,64 +104,60 @@
109104 * @param v the value to set. To set the value to NULL, use {@link #setToNull(int)} or
110105 * {@code set(i, v, Long.class)}
111106 * @return this object.
112- *
113107 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
114- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
115- * underlying CQL type.
108+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
109+ * underlying CQL type.
116110 */
117111 public T setLong(int i, long v);
118112
119113 /**
120114 * Set the {@code i}th value to the provided date.
121- * <p>
115+ * <p/>
122116 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
123117 * to the underlying CQL type (for CQL type {@code timestamp}, this will be the built-in codec).
124118 *
125119 * @param i the index of the value to set.
126120 * @param v the value to set.
127121 * @return this object.
128- *
129122 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
130- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
131- * underlying CQL type.
123+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
124+ * underlying CQL type.
132125 */
133126 public T setTimestamp(int i, Date v);
134127
135128 /**
136129 * Set the {@code i}th value to the provided date (without time).
137- * <p>
130+ * <p/>
138131 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
139132 * to the underlying CQL type (for CQL type {@code date}, this will be the built-in codec).
140133 *
141134 * @param i the index of the value to set.
142135 * @param v the value to set.
143136 * @return this object.
144- *
145137 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
146- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
147- * underlying CQL type.
138+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
139+ * underlying CQL type.
148140 */
149141 public T setDate(int i, LocalDate v);
150142
151143 /**
152144 * Set the {@code i}th value to the provided time as a long in nanoseconds since midnight.
153- * <p>
145+ * <p/>
154146 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
155147 * to the underlying CQL type (for CQL type {@code time}, this will be the built-in codec).
156148 *
157149 * @param i the index of the value to set.
158150 * @param v the value to set.
159151 * @return this object.
160- *
161152 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
162- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
163- * underlying CQL type.
153+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
154+ * underlying CQL type.
164155 */
165156 public T setTime(int i, long v);
166157
167158 /**
168159 * Sets the {@code i}th value to the provided float.
169- * <p>
160+ * <p/>
170161 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
171162 * to the underlying CQL type (for CQL type {@code float}, this will be the built-in codec).
172163 *
@@ -174,16 +165,15 @@
174165 * @param v the value to set. To set the value to NULL, use {@link #setToNull(int)} or
175166 * {@code set(i, v, Float.class)}
176167 * @return this object.
177- *
178168 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
179- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
180- * underlying CQL type.
169+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
170+ * underlying CQL type.
181171 */
182172 public T setFloat(int i, float v);
183173
184174 /**
185175 * Sets the {@code i}th value to the provided double.
186- * <p>
176+ * <p/>
187177 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
188178 * to the underlying CQL type (for CQL type {@code double}, this will be the built-in codec).
189179 *
@@ -191,16 +181,15 @@
191181 * @param v the value to set. To set the value to NULL, use {@link #setToNull(int)} or
192182 * {@code set(i, v, Double.class)}.
193183 * @return this object.
194- *
195184 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
196- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
197- * underlying CQL type.
185+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
186+ * underlying CQL type.
198187 */
199188 public T setDouble(int i, double v);
200189
201190 /**
202191 * Sets the {@code i}th value to the provided string.
203- * <p>
192+ * <p/>
204193 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
205194 * to the underlying CQL type (for CQL types {@code text}, {@code varchar} and {@code ascii},
206195 * this will be the built-in codec).
@@ -208,32 +197,30 @@
208197 * @param i the index of the value to set.
209198 * @param v the value to set.
210199 * @return this object.
211- *
212200 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
213- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
214- * underlying CQL type.
201+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
202+ * underlying CQL type.
215203 */
216204 public T setString(int i, String v);
217205
218206 /**
219207 * Sets the {@code i}th value to the provided byte buffer.
220- * <p>
208+ * <p/>
221209 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
222210 * to the underlying CQL type (for CQL type {@code blob}, this will be the built-in codec).
223211 *
224212 * @param i the index of the value to set.
225213 * @param v the value to set.
226214 * @return this object.
227- *
228215 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
229- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
230- * underlying CQL type.
216+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
217+ * underlying CQL type.
231218 */
232219 public T setBytes(int i, ByteBuffer v);
233220
234221 /**
235222 * Sets the {@code i}th value to the provided byte buffer.
236- * <p>
223+ * <p/>
237224 * This method does not use any codec; it sets the value in its binary form directly. If you insert
238225 * data that is not compatible with the underlying CQL type, you will get an {@code InvalidQueryException} at
239226 * execute time.
@@ -241,46 +228,43 @@
241228 * @param i the index of the value to set.
242229 * @param v the value to set.
243230 * @return this object.
244- *
245231 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
246232 */
247233 public T setBytesUnsafe(int i, ByteBuffer v);
248234
249235 /**
250236 * Sets the {@code i}th value to the provided big integer.
251- * <p>
237+ * <p/>
252238 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
253239 * to the underlying CQL type (for CQL type {@code varint}, this will be the built-in codec).
254240 *
255241 * @param i the index of the value to set.
256242 * @param v the value to set.
257243 * @return this object.
258- *
259244 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
260- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
261- * underlying CQL type.
245+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
246+ * underlying CQL type.
262247 */
263248 public T setVarint(int i, BigInteger v);
264249
265250 /**
266251 * Sets the {@code i}th value to the provided big decimal.
267- * <p>
252+ * <p/>
268253 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
269254 * to the underlying CQL type (for CQL type {@code decimal}, this will be the built-in codec).
270255 *
271256 * @param i the index of the value to set.
272257 * @param v the value to set.
273258 * @return this object.
274- *
275259 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
276- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
277- * underlying CQL type.
260+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
261+ * underlying CQL type.
278262 */
279263 public T setDecimal(int i, BigDecimal v);
280264
281265 /**
282266 * Sets the {@code i}th value to the provided UUID.
283- * <p>
267+ * <p/>
284268 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
285269 * to the underlying CQL type (for CQL types {@code uuid} and {@code timeuuid}, this will
286270 * be the built-in codec).
@@ -288,32 +272,30 @@
288272 * @param i the index of the value to set.
289273 * @param v the value to set.
290274 * @return this object.
291- *
292275 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
293- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
294- * underlying CQL type.
276+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
277+ * underlying CQL type.
295278 */
296279 public T setUUID(int i, UUID v);
297280
298281 /**
299282 * Sets the {@code i}th value to the provided inet address.
300- * <p>
283+ * <p/>
301284 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
302285 * to the underlying CQL type (for CQL type {@code inet}, this will be the built-in codec).
303286 *
304287 * @param i the index of the value to set.
305288 * @param v the value to set.
306289 * @return this object.
307- *
308290 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
309- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
310- * underlying CQL type.
291+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
292+ * underlying CQL type.
311293 */
312294 public T setInet(int i, InetAddress v);
313295
314296 /**
315297 * Sets the {@code i}th value to the provided list.
316- * <p>
298+ * <p/>
317299 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
318300 * to the underlying CQL type (the type of the elements in the Java list is not considered).
319301 * If two or more codecs target that CQL type, the one that was first registered will be used.
@@ -323,60 +305,57 @@
323305 * @param i the index of the value to set.
324306 * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
325307 * @return this object.
326- *
327308 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
328- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
329- * by CQL.
330- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
331- * underlying CQL type.
309+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
310+ * by CQL.
311+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
312+ * underlying CQL type.
332313 */
333314 public <E> T setList(int i, List<E> v);
334315
335316 /**
336317 * Sets the {@code i}th value to the provided list, which elements are of the provided
337318 * Java class.
338- * <p>
319+ * <p/>
339320 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of lists of the given
340321 * Java type to the underlying CQL type.
341- * <p>
322+ * <p/>
342323 * If the type of the elements is generic, use {@link #setList(int, List, TypeToken)}.
343324 *
344- * @param i the index of the value to set.
345- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
325+ * @param i the index of the value to set.
326+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
346327 * @param elementsClass the class for the elements of the list.
347328 * @return this object.
348- *
349329 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
350- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
351- * by CQL.
352- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
353- * underlying CQL type.
330+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
331+ * by CQL.
332+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
333+ * underlying CQL type.
354334 */
355335 public <E> T setList(int i, List<E> v, Class<E> elementsClass);
356336
357337 /**
358338 * Sets the {@code i}th value to the provided list, which elements are of the provided
359339 * Java type.
360- * <p>
340+ * <p/>
361341 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of lists of the given
362342 * Java type to the underlying CQL type.
363343 *
364- * @param i the index of the value to set.
365- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
344+ * @param i the index of the value to set.
345+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
366346 * @param elementsType the type for the elements of the list.
367347 * @return this object.
368- *
369348 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
370- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
371- * by CQL.
372- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
373- * underlying CQL type.
349+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
350+ * by CQL.
351+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
352+ * underlying CQL type.
374353 */
375354 public <E> T setList(int i, List<E> v, TypeToken<E> elementsType);
376355
377356 /**
378357 * Sets the {@code i}th value to the provided map.
379- * <p>
358+ * <p/>
380359 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
381360 * to the underlying CQL type (the type of the elements in the Java map is not considered).
382361 * If two or more codecs target that CQL type, the one that was first registered will be used.
@@ -386,63 +365,59 @@
386365 * @param i the index of the value to set.
387366 * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
388367 * @return this object.
389- * @return this object.
390- *
391368 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
392- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
393- * by CQL.
394- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
395- * underlying CQL type.
369+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
370+ * by CQL.
371+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
372+ * underlying CQL type.
396373 */
397374 public <K, V> T setMap(int i, Map<K, V> v);
398375
399376 /**
400377 * Sets the {@code i}th value to the provided map, which keys and values are of the provided
401378 * Java classes.
402- * <p>
379+ * <p/>
403380 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of lists of the given
404381 * Java types to the underlying CQL type.
405- * <p>
382+ * <p/>
406383 * If the type of the keys or values is generic, use {@link #setMap(int, Map, TypeToken, TypeToken)}.
407384 *
408- * @param i the index of the value to set.
409- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
410- * @param keysClass the class for the keys of the map.
385+ * @param i the index of the value to set.
386+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
387+ * @param keysClass the class for the keys of the map.
411388 * @param valuesClass the class for the values of the map.
412389 * @return this object.
413- *
414390 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
415- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
416- * by CQL.
417- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
418- * underlying CQL type.
391+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
392+ * by CQL.
393+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
394+ * underlying CQL type.
419395 */
420396 public <K, V> T setMap(int i, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass);
421397
422398 /**
423399 * Sets the {@code i}th value to the provided map, which keys and values are of the provided
424400 * Java types.
425- * <p>
401+ * <p/>
426402 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of lists of the given
427403 * Java types to the underlying CQL type.
428404 *
429- * @param i the index of the value to set.
430- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
431- * @param keysType the type for the keys of the map.
405+ * @param i the index of the value to set.
406+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
407+ * @param keysType the type for the keys of the map.
432408 * @param valuesType the type for the values of the map.
433409 * @return this object.
434- *
435410 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
436- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
437- * by CQL.
438- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
439- * underlying CQL type.
411+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
412+ * by CQL.
413+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
414+ * underlying CQL type.
440415 */
441416 public <K, V> T setMap(int i, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType);
442417
443418 /**
444419 * Sets the {@code i}th value to the provided set.
445- * <p>
420+ * <p/>
446421 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
447422 * to the underlying CQL type (the type of the elements in the Java set is not considered).
448423 * If two or more codecs target that CQL type, the one that was first registered will be used.
@@ -452,92 +427,87 @@
452427 * @param i the index of the value to set.
453428 * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
454429 * @return this object.
455- *
456430 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
457- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
458- * by CQL.
459- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
460- * underlying CQL type.
431+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
432+ * by CQL.
433+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
434+ * underlying CQL type.
461435 */
462436 public <E> T setSet(int i, Set<E> v);
463437
464438 /**
465439 * Sets the {@code i}th value to the provided set, which elements are of the provided
466440 * Java class.
467- * <p>
441+ * <p/>
468442 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of sets of the given
469443 * Java type to the underlying CQL type.
470- * <p>
444+ * <p/>
471445 * If the type of the elements is generic, use {@link #setSet(int, Set, TypeToken)}.
472446 *
473- * @param i the index of the value to set.
474- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
447+ * @param i the index of the value to set.
448+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
475449 * @param elementsClass the class for the elements of the set.
476450 * @return this object.
477- *
478451 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
479- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
480- * by CQL.
481- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
482- * underlying CQL type.
452+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
453+ * by CQL.
454+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
455+ * underlying CQL type.
483456 */
484457 public <E> T setSet(int i, Set<E> v, Class<E> elementsClass);
485458
486459 /**
487460 * Sets the {@code i}th value to the provided set, which elements are of the provided
488461 * Java type.
489- * <p>
462+ * <p/>
490463 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of sets of the given
491464 * Java type to the underlying CQL type.
492465 *
493- * @param i the index of the value to set.
494- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
466+ * @param i the index of the value to set.
467+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
495468 * @param elementsType the type for the elements of the set.
496469 * @return this object.
497- *
498470 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
499- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
500- * by CQL.
501- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
502- * underlying CQL type.
471+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
472+ * by CQL.
473+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
474+ * underlying CQL type.
503475 */
504476 public <E> T setSet(int i, Set<E> v, TypeToken<E> elementsType);
505477
506478 /**
507479 * Sets the {@code i}th value to the provided UDT value.
508- * <p>
480+ * <p/>
509481 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of {@code UDTValue}
510482 * to the underlying CQL type.
511483 *
512484 * @param i the index of the value to set.
513485 * @param v the value to set.
514486 * @return this object.
515- *
516487 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
517- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
518- * underlying CQL type.
488+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
489+ * underlying CQL type.
519490 */
520491 public T setUDTValue(int i, UDTValue v);
521492
522493 /**
523494 * Sets the {@code i}th value to the provided tuple value.
524- * <p>
495+ * <p/>
525496 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of {@code TupleValue}
526497 * to the underlying CQL type.
527498 *
528499 * @param i the index of the value to set.
529500 * @param v the value to set.
530501 * @return this object.
531- *
532502 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
533- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
534- * underlying CQL type.
503+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
504+ * underlying CQL type.
535505 */
536506 public T setTupleValue(int i, TupleValue v);
537507
538508 /**
539509 * Sets the {@code i}th value to {@code null}.
540- * <p>
510+ * <p/>
541511 * This is mainly intended for CQL types which map to native Java types.
542512 *
543513 * @param i the index of the value to set.
@@ -548,53 +518,53 @@
548518
549519 /**
550520 * Sets the {@code i}th value to the provided value of the provided Java class.
551- * <p>
521+ * <p/>
552522 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of the provided Java class
553523 * to the underlying CQL type.
554- * <p>
524+ * <p/>
555525 * If the Java type is generic, use {@link #set(int, Object, TypeToken)} instead.
556526 *
557- * @param i the index of the value to set.
558- * @param v the value to set; may be {@code null}.
527+ * @param i the index of the value to set.
528+ * @param v the value to set; may be {@code null}.
559529 * @param targetClass The Java class to convert to; must not be {@code null};
560530 * @return this object.
561531 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
562- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
563- * underlying CQL type.
532+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
533+ * underlying CQL type.
564534 */
565535 <V> T set(int i, V v, Class<V> targetClass);
566536
567537 /**
568538 * Sets the {@code i}th value to the provided value of the provided Java type.
569- * <p>
539+ * <p/>
570540 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of the provided Java type
571541 * to the underlying CQL type.
572542 *
573- * @param i the index of the value to set.
574- * @param v the value to set; may be {@code null}.
543+ * @param i the index of the value to set.
544+ * @param v the value to set; may be {@code null}.
575545 * @param targetType The Java type to convert to; must not be {@code null};
576546 * @return this object.
577547 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
578- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
579- * underlying CQL type.
548+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
549+ * underlying CQL type.
580550 */
581551 <V> T set(int i, V v, TypeToken<V> targetType);
582552
583553 /**
584554 * Sets the {@code i}th value to the provided value, converted using the given {@link TypeCodec}.
585- * <p>
555+ * <p/>
586556 * This method entirely bypasses the {@link CodecRegistry} and forces the driver to use the given codec instead.
587557 * This can be useful if the codec would collide with a previously registered one, or if you want to use the
588558 * codec just once without registering it.
589- * <p>
559+ * <p/>
590560 * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
591561 * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
592562 *
593- * @param i the index of the value to set.
594- * @param v the value to set; may be {@code null}.
563+ * @param i the index of the value to set.
564+ * @param v the value to set; may be {@code null}.
595565 * @param codec The {@link TypeCodec} to use to serialize the value; may not be {@code null}.
596566 * @return this object.
597- * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
567+ * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
598568 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
599569 */
600570 <V> T set(int i, V v, TypeCodec<V> codec);
modified driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java +195 −224
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.CodecNotFoundException;
19+import com.datastax.driver.core.exceptions.InvalidTypeException;
20+import com.google.common.reflect.TypeToken;
21+
1822 import java.math.BigDecimal;
1923 import java.math.BigInteger;
2024 import java.net.InetAddress;
2125 import java.nio.ByteBuffer;
2226 import java.util.*;
2327
24-import com.google.common.reflect.TypeToken;
25-
26-import com.datastax.driver.core.exceptions.CodecNotFoundException;
27-import com.datastax.driver.core.exceptions.InvalidTypeException;
28-
2928 /**
3029 * Collection of (typed) CQL values that can set by name.
3130 */
@@ -34,240 +33,227 @@
3433 /**
3534 * Sets the value for (all occurrences of) variable {@code name} to the
3635 * provided boolean.
37- * <p>
36+ * <p/>
3837 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
3938 * to the underlying CQL type (for CQL type {@code boolean}, this will be the built-in codec).
4039 *
4140 * @param name the name of the value to set; if {@code name} is present multiple
42- * times, all its values are set.
43- * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
44- * {@code set(name, v, Boolean.class)}.
41+ * times, all its values are set.
42+ * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
43+ * {@code set(name, v, Boolean.class)}.
4544 * @return this object.
46- *
4745 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
48- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
49- * underlying CQL type.
46+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
47+ * underlying CQL type.
5048 */
5149 public T setBool(String name, boolean v);
5250
5351 /**
5452 * Sets the value for (all occurrences of) variable {@code name} to the
5553 * provided byte.
56- * <p>
54+ * <p/>
5755 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
5856 * to the underlying CQL type (for CQL type {@code tinyint}, this will be the built-in codec).
5957 *
6058 * @param name the name of the value to set; if {@code name} is present multiple
61- * times, all its values are set.
62- * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
63- * {@code set(name, v, Byte.class)}.
59+ * times, all its values are set.
60+ * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
61+ * {@code set(name, v, Byte.class)}.
6462 * @return this object.
65- *
6663 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
67- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
68- * underlying CQL type.
64+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
65+ * underlying CQL type.
6966 */
7067 public T setByte(String name, byte v);
7168
7269 /**
7370 * Sets the value for (all occurrences of) variable {@code name} to the
7471 * provided short.
75- * <p>
72+ * <p/>
7673 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
7774 * to the underlying CQL type (for CQL type {@code smallint}, this will be the built-in codec).
7875 *
7976 * @param name the name of the value to set; if {@code name} is present multiple
80- * times, all its values are set.
81- * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
82- * {@code set(name, v, Short.class)}.
77+ * times, all its values are set.
78+ * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
79+ * {@code set(name, v, Short.class)}.
8380 * @return this object.
84- *
8581 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
86- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
87- * underlying CQL type.
82+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
83+ * underlying CQL type.
8884 */
8985 public T setShort(String name, short v);
9086
9187 /**
9288 * Sets the value for (all occurrences of) variable {@code name} to the
9389 * provided integer.
94- * <p>
90+ * <p/>
9591 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
9692 * to the underlying CQL type (for CQL type {@code int}, this will be the built-in codec).
9793 *
9894 * @param name the name of the value to set; if {@code name} is present multiple
99- * times, all its values are set.
100- * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
101- * {@code set(name, v, Integer.class)}.
95+ * times, all its values are set.
96+ * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
97+ * {@code set(name, v, Integer.class)}.
10298 * @return this object.
103- *
10499 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
105- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
106- * underlying CQL type.
100+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
101+ * underlying CQL type.
107102 */
108103 public T setInt(String name, int v);
109104
110105 /**
111106 * Sets the value for (all occurrences of) variable {@code name} to the
112107 * provided long.
113- * <p>
108+ * <p/>
114109 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
115110 * to the underlying CQL type (for CQL type {@code bigint}, this will be the built-in codec).
116111 *
117112 * @param name the name of the value to set; if {@code name} is present multiple
118- * times, all its values are set.
119- * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
120- * {@code set(name, v, Long.class)}.
113+ * times, all its values are set.
114+ * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
115+ * {@code set(name, v, Long.class)}.
121116 * @return this object.
122- *
123117 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
124- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
125- * underlying CQL type.
118+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
119+ * underlying CQL type.
126120 */
127121 public T setLong(String name, long v);
128122
129123 /**
130124 * Sets the value for (all occurrences of) variable {@code name} to the
131125 * provided date.
132- * <p>
126+ * <p/>
133127 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
134128 * to the underlying CQL type (for CQL type {@code timestamp}, this will be the built-in codec).
135129 *
136130 * @param name the name of the value to set; if {@code name} is present multiple
137- * times, all its values are set.
138- * @param v the value to set.
131+ * times, all its values are set.
132+ * @param v the value to set.
139133 * @return this object.
140- *
141134 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
142- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
143- * underlying CQL type.
135+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
136+ * underlying CQL type.
144137 */
145138 public T setTimestamp(String name, Date v);
146139
147140 /**
148141 * Sets the value for (all occurrences of) variable {@code name} to the
149142 * provided date (without time).
150- * <p>
143+ * <p/>
151144 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
152145 * to the underlying CQL type (for CQL type {@code date}, this will be the built-in codec).
153146 *
154147 * @param name the name of the value to set; if {@code name} is present multiple
155- * times, all its values are set.
156- * @param v the value to set.
148+ * times, all its values are set.
149+ * @param v the value to set.
157150 * @return this object.
158- *
159151 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
160- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
161- * underlying CQL type.
152+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
153+ * underlying CQL type.
162154 */
163155 public T setDate(String name, LocalDate v);
164156
165157 /**
166158 * Sets the value for (all occurrences of) variable {@code name} to the
167159 * provided time as a long in nanoseconds since midnight.
168- * <p>
160+ * <p/>
169161 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
170162 * to the underlying CQL type (for CQL type {@code time}, this will be the built-in codec).
171163 *
172164 * @param name the name of the value to set; if {@code name} is present multiple
173- * times, all its values are set.
174- * @param v the value to set.
165+ * times, all its values are set.
166+ * @param v the value to set.
175167 * @return this object.
176- *
177168 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
178- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
179- * underlying CQL type.
169+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
170+ * underlying CQL type.
180171 */
181172 public T setTime(String name, long v);
182173
183174 /**
184175 * Sets the value for (all occurrences of) variable {@code name} to the
185176 * provided float.
186- * <p>
177+ * <p/>
187178 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
188179 * to the underlying CQL type (for CQL type {@code float}, this will be the built-in codec).
189180 *
190181 * @param name the name of the value to set; if {@code name} is present multiple
191- * times, all its values are set.
192- * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
193- * {@code set(name, v, Float.class)}.
182+ * times, all its values are set.
183+ * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
184+ * {@code set(name, v, Float.class)}.
194185 * @return this object.
195- *
196186 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
197- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
198- * underlying CQL type.
187+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
188+ * underlying CQL type.
199189 */
200190 public T setFloat(String name, float v);
201191
202192 /**
203193 * Sets the value for (all occurrences of) variable {@code name} to the
204194 * provided double.
205- * <p>
195+ * <p/>
206196 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
207197 * to the underlying CQL type (for CQL type {@code double}, this will be the built-in codec).
208198 *
209199 * @param name the name of the value to set; if {@code name} is present multiple
210- * times, all its values are set.
211- * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
212- * {@code set(name, v, Double.class)}.
200+ * times, all its values are set.
201+ * @param v the value to set. To set the value to NULL, use {@link #setToNull(String)} or
202+ * {@code set(name, v, Double.class)}.
213203 * @return this object.
214- *
215204 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
216- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
217- * underlying CQL type.
205+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
206+ * underlying CQL type.
218207 */
219208 public T setDouble(String name, double v);
220209
221210 /**
222211 * Sets the value for (all occurrences of) variable {@code name} to the
223212 * provided string.
224- * <p>
213+ * <p/>
225214 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
226215 * to the underlying CQL type (for CQL types {@code text}, {@code varchar} and {@code ascii},
227216 * this will be the built-in codec).
228217 *
229218 * @param name the name of the value to set; if {@code name} is present multiple
230- * times, all its values are set.
231- * @param v the value to set.
219+ * times, all its values are set.
220+ * @param v the value to set.
232221 * @return this object.
233- *
234222 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
235- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
236- * underlying CQL type.
223+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
224+ * underlying CQL type.
237225 */
238226 public T setString(String name, String v);
239227
240228 /**
241229 * Sets the value for (all occurrences of) variable {@code name} to the
242230 * provided byte buffer.
243- * <p>
231+ * <p/>
244232 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
245233 * to the underlying CQL type (for CQL type {@code blob}, this will be the built-in codec).
246234 *
247235 * @param name the name of the value to set; if {@code name} is present multiple
248- * times, all its values are set.
249- * @param v the value to set.
236+ * times, all its values are set.
237+ * @param v the value to set.
250238 * @return this object.
251- *
252239 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
253- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
254- * underlying CQL type.
240+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
241+ * underlying CQL type.
255242 */
256243 public T setBytes(String name, ByteBuffer v);
257244
258245 /**
259246 * Sets the value for (all occurrences of) variable {@code name} to the
260247 * provided byte buffer.
261- * <p>
248+ * <p/>
262249 * This method does not use any codec; it sets the value in its binary form directly. If you insert
263250 * data that is not compatible with the underlying CQL type, you will get an {@code InvalidQueryException} at
264251 * execute time.
265252 *
266253 * @param name the name of the value to set; if {@code name} is present multiple
267- * times, all its values are set.
268- * @param v the value to set.
254+ * times, all its values are set.
255+ * @param v the value to set.
269256 * @return this object.
270- *
271257 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
272258 */
273259 public T setBytesUnsafe(String name, ByteBuffer v);
@@ -275,80 +261,76 @@
275261 /**
276262 * Sets the value for (all occurrences of) variable {@code name} to the
277263 * provided big integer.
278- * <p>
264+ * <p/>
279265 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
280266 * to the underlying CQL type (for CQL type {@code varint}, this will be the built-in codec).
281267 *
282268 * @param name the name of the value to set; if {@code name} is present multiple
283- * times, all its values are set.
284- * @param v the value to set.
269+ * times, all its values are set.
270+ * @param v the value to set.
285271 * @return this object.
286- *
287272 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
288- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
289- * underlying CQL type.
273+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
274+ * underlying CQL type.
290275 */
291276 public T setVarint(String name, BigInteger v);
292277
293278 /**
294279 * Sets the value for (all occurrences of) variable {@code name} to the
295280 * provided big decimal.
296- * <p>
281+ * <p/>
297282 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
298283 * to the underlying CQL type (for CQL type {@code decimal}, this will be the built-in codec).
299284 *
300285 * @param name the name of the value to set; if {@code name} is present multiple
301- * times, all its values are set.
302- * @param v the value to set.
286+ * times, all its values are set.
287+ * @param v the value to set.
303288 * @return this object.
304- *
305289 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
306- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
307- * underlying CQL type.
290+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
291+ * underlying CQL type.
308292 */
309293 public T setDecimal(String name, BigDecimal v);
310294
311295 /**
312296 * Sets the value for (all occurrences of) variable {@code name} to the
313297 * provided UUID.
314- * <p>
298+ * <p/>
315299 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
316300 * to the underlying CQL type (for CQL types {@code uuid} and {@code timeuuid}, this will
317301 * be the built-in codec).
318302 *
319303 * @param name the name of the value to set; if {@code name} is present multiple
320- * times, all its values are set.
321- * @param v the value to set.
304+ * times, all its values are set.
305+ * @param v the value to set.
322306 * @return this object.
323- *
324307 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
325- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
326- * underlying CQL type.
308+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
309+ * underlying CQL type.
327310 */
328311 public T setUUID(String name, UUID v);
329312
330313 /**
331314 * Sets the value for (all occurrences of) variable {@code name} to the
332315 * provided inet address.
333- * <p>
316+ * <p/>
334317 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
335318 * to the underlying CQL type (for CQL type {@code inet}, this will be the built-in codec).
336319 *
337320 * @param name the name of the value to set; if {@code name} is present multiple
338- * times, all its values are set.
339- * @param v the value to set.
321+ * times, all its values are set.
322+ * @param v the value to set.
340323 * @return this object.
341- *
342324 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
343- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
344- * underlying CQL type.
325+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
326+ * underlying CQL type.
345327 */
346328 public T setInet(String name, InetAddress v);
347329
348330 /**
349331 * Sets the value for (all occurrences of) variable {@code name} to the
350332 * provided list.
351- * <p>
333+ * <p/>
352334 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
353335 * to the underlying CQL type (the type of the elements in the Java list is not considered).
354336 * If two or more codecs target that CQL type, the one that was first registered will be used.
@@ -356,64 +338,61 @@
356338 * {@link #setList(String, List, Class)} or {@link #setList(String, List, TypeToken)}.
357339 *
358340 * @param name the name of the value to set; if {@code name} is present multiple
359- * times, all its values are set.
360- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
341+ * times, all its values are set.
342+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
361343 * @return this object.
362- *
363344 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
364- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
365- * by CQL.
366- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
367- * underlying CQL type.
345+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
346+ * by CQL.
347+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
348+ * underlying CQL type.
368349 */
369350 public <E> T setList(String name, List<E> v);
370351
371352 /**
372353 * Sets the value for (all occurrences of) variable {@code name} to the provided list,
373354 * which elements are of the provided Java class.
374- * <p>
355+ * <p/>
375356 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of lists of the given
376357 * Java type to the underlying CQL type.
377- * <p>
358+ * <p/>
378359 * If the type of the elements is generic, use {@link #setList(String, List, TypeToken)}.
379360 *
380- * @param name the name of the value to set; if {@code name} is present multiple
381- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
361+ * @param name the name of the value to set; if {@code name} is present multiple
362+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
382363 * @param elementsClass the class for the elements of the list.
383364 * @return this object.
384- *
385365 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
386- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
387- * by CQL.
388- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
389- * underlying CQL type.
366+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
367+ * by CQL.
368+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
369+ * underlying CQL type.
390370 */
391371 public <E> T setList(String name, List<E> v, Class<E> elementsClass);
392372
393373 /**
394374 * Sets the value for (all occurrences of) variable {@code name} to the provided list,
395375 * which elements are of the provided Java type.
396- * <p>
376+ * <p/>
397377 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of lists of the given
398378 * Java type to the underlying CQL type.
399379 *
400- * @param name the name of the value to set; if {@code name} is present multiple
401- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
380+ * @param name the name of the value to set; if {@code name} is present multiple
381+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
402382 * @param elementsType the type for the elements of the list.
403383 * @return this object.
404- *
405384 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
406- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
407- * by CQL.
408- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
409- * underlying CQL type.
385+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
386+ * by CQL.
387+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
388+ * underlying CQL type.
410389 */
411390 public <E> T setList(String name, List<E> v, TypeToken<E> elementsType);
412391
413392 /**
414393 * Sets the value for (all occurrences of) variable {@code name} to the
415394 * provided map.
416- * <p>
395+ * <p/>
417396 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
418397 * to the underlying CQL type (the type of the elements in the Java map is not considered).
419398 * If two or more codecs target that CQL type, the one that was first registered will be used.
@@ -421,68 +400,65 @@
421400 * {@link #setMap(String, Map, Class, Class)} or {@link #setMap(String, Map, TypeToken, TypeToken)}.
422401 *
423402 * @param name the name of the value to set; if {@code name} is present multiple
424- * times, all its values are set.
425- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
403+ * times, all its values are set.
404+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
426405 * @return this object.
427- *
428406 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
429- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
430- * by CQL.
431- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
432- * underlying CQL type.
407+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
408+ * by CQL.
409+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
410+ * underlying CQL type.
433411 */
434412 public <K, V> T setMap(String name, Map<K, V> v);
435413
436414 /**
437415 * Sets the value for (all occurrences of) variable {@code name} to the provided map,
438416 * which keys and values are of the provided Java classes.
439- * <p>
417+ * <p/>
440418 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of lists of the given
441419 * Java types to the underlying CQL type.
442- * <p>
420+ * <p/>
443421 * If the type of the keys or values is generic, use {@link #setMap(String, Map, TypeToken, TypeToken)}.
444422 *
445- * @param name the name of the value to set; if {@code name} is present multiple
446- * times, all its values are set.
447- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
448- * @param keysClass the class for the keys of the map.
423+ * @param name the name of the value to set; if {@code name} is present multiple
424+ * times, all its values are set.
425+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
426+ * @param keysClass the class for the keys of the map.
449427 * @param valuesClass the class for the values of the map.
450428 * @return this object.
451- *
452429 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
453- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
454- * by CQL.
455- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
456- * underlying CQL type.
430+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
431+ * by CQL.
432+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
433+ * underlying CQL type.
457434 */
458435 public <K, V> T setMap(String name, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass);
459436
460437 /**
461438 * Sets the value for (all occurrences of) variable {@code name} to the provided map,
462439 * which keys and values are of the provided Java types.
463- * <p>
440+ * <p/>
464441 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of lists of the given
465442 * Java types to the underlying CQL type.
466443 *
467- * @param name the name of the value to set; if {@code name} is present multiple
468- * times, all its values are set.
469- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
470- * @param keysType the type for the keys of the map.
444+ * @param name the name of the value to set; if {@code name} is present multiple
445+ * times, all its values are set.
446+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
447+ * @param keysType the type for the keys of the map.
471448 * @param valuesType the type for the values of the map.
472449 * @return this object.
473- *
474450 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
475- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
476- * by CQL.
477- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
478- * underlying CQL type.
451+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
452+ * by CQL.
453+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
454+ * underlying CQL type.
479455 */
480456 public <K, V> T setMap(String name, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType);
481457
482458 /**
483459 * Sets the value for (all occurrences of) variable {@code name} to the
484460 * provided set.
485- * <p>
461+ * <p/>
486462 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion
487463 * to the underlying CQL type (the type of the elements in the Java set is not considered).
488464 * If two or more codecs target that CQL type, the one that was first registered will be used.
@@ -490,103 +466,98 @@
490466 * {@link #setSet(String, Set, Class)} or {@link #setSet(String, Set, TypeToken)}.
491467 *
492468 * @param name the name of the value to set; if {@code name} is present multiple
493- * times, all its values are set.
494- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
469+ * times, all its values are set.
470+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
495471 * @return this object.
496- *
497472 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
498- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
499- * by CQL.
500- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
501- * underlying CQL type.
473+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
474+ * by CQL.
475+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
476+ * underlying CQL type.
502477 */
503478 public <E> T setSet(String name, Set<E> v);
504479
505480 /**
506481 * Sets the value for (all occurrences of) variable {@code name} to the provided set,
507482 * which elements are of the provided Java class.
508- * <p>
483+ * <p/>
509484 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of sets of the given
510485 * Java type to the underlying CQL type.
511- * <p>
486+ * <p/>
512487 * If the type of the elements is generic, use {@link #setSet(String, Set, TypeToken)}.
513488 *
514- * @param name the name of the value to set; if {@code name} is present multiple
515- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
489+ * @param name the name of the value to set; if {@code name} is present multiple
490+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
516491 * @param elementsClass the class for the elements of the set.
517492 * @return this object.
518- *
519493 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
520- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
521- * by CQL.
522- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
523- * underlying CQL type.
494+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
495+ * by CQL.
496+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
497+ * underlying CQL type.
524498 */
525499 public <E> T setSet(String name, Set<E> v, Class<E> elementsClass);
526500
527501 /**
528502 * Sets the value for (all occurrences of) variable {@code name} to the provided set,
529503 * which elements are of the provided Java type.
530- * <p>
504+ * <p/>
531505 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of sets of the given
532506 * Java type to the underlying CQL type.
533507 *
534- * @param name the name of the value to set; if {@code name} is present multiple
535- * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
508+ * @param name the name of the value to set; if {@code name} is present multiple
509+ * @param v the value to set. Note that {@code null} values inside collections are not supported by CQL.
536510 * @param elementsType the type for the elements of the set.
537511 * @return this object.
538- *
539512 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
540- * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
541- * by CQL.
542- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
543- * underlying CQL type.
513+ * @throws NullPointerException if {@code v} contains null values. Nulls are not supported in collections
514+ * by CQL.
515+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
516+ * underlying CQL type.
544517 */
545518 public <E> T setSet(String name, Set<E> v, TypeToken<E> elementsType);
546519
547520 /**
548521 * Sets the value for (all occurrences of) variable {@code name} to the
549522 * provided UDT value.
550- * <p>
523+ * <p/>
551524 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of {@code UDTValue}
552525 * to the underlying CQL type.
553526 *
554527 * @param name the name of the value to set; if {@code name} is present multiple
555- * times, all its values are set.
556- * @param v the value to set.
528+ * times, all its values are set.
529+ * @param v the value to set.
557530 * @return this object.
558- *
559531 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
560- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
561- * underlying CQL type.
532+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
533+ * underlying CQL type.
562534 */
563535 public T setUDTValue(String name, UDTValue v);
564536
565537 /**
566538 * Sets the value for (all occurrences of) variable {@code name} to the
567539 * provided tuple value.
568- * <p>
540+ * <p/>
569541 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of {@code TupleValue}
570542 * to the underlying CQL type.
571543 *
572544 * @param name the name of the value to set; if {@code name} is present multiple
573- * times, all its values are set.
574- * @param v the value to set.
545+ * times, all its values are set.
546+ * @param v the value to set.
575547 * @return this object.
576- *
577548 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
578- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
579- * underlying CQL type.
549+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
550+ * underlying CQL type.
580551 */
581552 public T setTupleValue(String name, TupleValue v);
582553
583554 /**
584555 * Sets the value for (all occurrences of) variable {@code name} to {@code null}.
585- * <p>
556+ * <p/>
586557 * This is mainly intended for CQL types which map to native Java types.
587558 *
588559 * @param name the name of the value to set; if {@code name} is present multiple
589- * times, all its values are set.
560+ * times, all its values are set.
590561 * @return this object.
591562 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
592563 */
@@ -594,57 +565,57 @@
594565
595566 /**
596567 * Sets the value for (all occurrences of) variable {@code name} to the provided value of the provided Java class.
597- * <p>
568+ * <p/>
598569 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of the provided Java class
599570 * to the underlying CQL type.
600- * <p>
571+ * <p/>
601572 * If the Java type is generic, use {@link #set(String, Object, TypeToken)} instead.
602573 *
603- * @param name the name of the value to set; if {@code name} is present multiple
604- * times, all its values are set.
605- * @param v the value to set; may be {@code null}.
574+ * @param name the name of the value to set; if {@code name} is present multiple
575+ * times, all its values are set.
576+ * @param v the value to set; may be {@code null}.
606577 * @param targetClass The Java class to convert to; must not be {@code null};
607578 * @return this object.
608579 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
609- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
610- * underlying CQL type.
580+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
581+ * underlying CQL type.
611582 */
612583 <V> T set(String name, V v, Class<V> targetClass);
613584
614585 /**
615586 * Sets the value for (all occurrences of) variable {@code name} to the provided value of the provided Java type.
616- * <p>
587+ * <p/>
617588 * This method uses the {@link CodecRegistry} to find a codec to handle the conversion of the provided Java type
618589 * to the underlying CQL type.
619590 *
620- * @param name the name of the value to set; if {@code name} is present multiple
621- * times, all its values are set.
622- * @param v the value to set; may be {@code null}.
591+ * @param name the name of the value to set; if {@code name} is present multiple
592+ * times, all its values are set.
593+ * @param v the value to set; may be {@code null}.
623594 * @param targetType The Java type to convert to; must not be {@code null};
624595 * @return this object.
625596 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
626- * @throws CodecNotFoundException if there is no registered codec to convert the value to the
627- * underlying CQL type.
597+ * @throws CodecNotFoundException if there is no registered codec to convert the value to the
598+ * underlying CQL type.
628599 */
629600 <V> T set(String name, V v, TypeToken<V> targetType);
630601
631602 /**
632603 * Sets the value for (all occurrences of) variable {@code name} to the provided value,
633604 * converted using the given {@link TypeCodec}.
634- * <p>
605+ * <p/>
635606 * This method entirely bypasses the {@link CodecRegistry} and forces the driver to use the given codec instead.
636607 * This can be useful if the codec would collide with a previously registered one, or if you want to use the
637608 * codec just once without registering it.
638- * <p>
609+ * <p/>
639610 * It is the caller's responsibility to ensure that the given codec {@link TypeCodec#accepts(DataType) accepts}
640611 * the underlying CQL type; failing to do so may result in {@link InvalidTypeException}s being thrown.
641612 *
642- * @param name the name of the value to set; if {@code name} is present multiple
643- * times, all its values are set.
644- * @param v the value to set; may be {@code null}.
613+ * @param name the name of the value to set; if {@code name} is present multiple
614+ * times, all its values are set.
615+ * @param v the value to set; may be {@code null}.
645616 * @param codec The {@link TypeCodec} to use to serialize the value; may not be {@code null}.
646617 * @return this object.
647- * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
618+ * @throws InvalidTypeException if the given codec does not {@link TypeCodec#accepts(DataType) accept} the underlying CQL type.
648619 * @throws IllegalArgumentException if {@code name} is not a valid name for this object.
649620 */
650621 <V> T set(String name, V v, TypeCodec<V> codec);
modified driver-core/src/main/java/com/datastax/driver/core/SettableData.java +0 −1
@@ -14,7 +14,6 @@
1414 * limitations under the License.
1515 */
1616 package com.datastax.driver.core;
17-import java.util.*;
1817
1918 /**
2019 * Collection of (typed) CQL values that can set either by index (starting a 0) or by name.
modified driver-core/src/main/java/com/datastax/driver/core/SimpleJSONParser.java +10 −10
@@ -22,15 +22,15 @@
2222 * The only reason we need to read json in the driver is because for
2323 * historical reason Cassandra encodes a few properties using json in
2424 * the schema and we need to decode them.
25- *
25+ * <p/>
2626 * We however don't need a full-blown JSON library because:
27- * 1) we know we only need to decode string lists and string maps
28- * 2) we can basically assume the input is valid, we don't particularly
29- * have to bother about decoding exactly JSON as long as we at least
30- * decode what we need.
31- * 3) we don't really care much about performance, none of this is done
32- * in performance sensitive parts.
33- *
27+ * 1) we know we only need to decode string lists and string maps
28+ * 2) we can basically assume the input is valid, we don't particularly
29+ * have to bother about decoding exactly JSON as long as we at least
30+ * decode what we need.
31+ * 3) we don't really care much about performance, none of this is done
32+ * in performance sensitive parts.
33+ * <p/>
3434 * So instead of pulling a new dependency, we roll out our own very dumb
3535 * parser. We should obviously not expose this publicly.
3636 */
@@ -123,7 +123,7 @@
123123 * the closing double-quote.
124124 */
125125 private String nextString() {
126- assert input.charAt(idx-1) == '"' : "Char is '" + input.charAt(idx-1) + '\'';
126+ assert input.charAt(idx - 1) == '"' : "Char is '" + input.charAt(idx - 1) + '\'';
127127 StringBuilder sb = new StringBuilder();
128128 while (true) {
129129 char c = nextChar();
@@ -150,7 +150,7 @@
150150 sb.append('\r');
151151 break;
152152 case 'u':
153- sb.append((char)Integer.parseInt(input.substring(idx, idx+4), 16));
153+ sb.append((char) Integer.parseInt(input.substring(idx, idx + 4), 16));
154154 idx += 4;
155155 break;
156156 case '"':
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +30 −37
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.exceptions.InvalidTypeException;
2119
20+import java.nio.ByteBuffer;
21+
2222 /**
2323 * A simple {@code RegularStatement} implementation built directly from a query
2424 * string.
@@ -42,7 +42,7 @@
4242
4343 /**
4444 * Creates a new {@code SimpleStatement} with the provided query string and values.
45- * <p>
45+ * <p/>
4646 * This version of SimpleStatement is useful when you want to execute a
4747 * query only once (and thus do not want to resort to prepared statement), but
4848 * do not want to convert all column values to string (typically, if you have blob
@@ -61,11 +61,11 @@
6161 * </pre>
6262 * except that the former version:
6363 * <ul>
64- * <li>Requires only one round-trip to a Cassandra node.</li>
65- * <li>Does not left any prepared statement stored in memory (neither client or
66- * server side) once it has been executed.</li>
64+ * <li>Requires only one round-trip to a Cassandra node.</li>
65+ * <li>Does not left any prepared statement stored in memory (neither client or
66+ * server side) once it has been executed.</li>
6767 * </ul>
68- * <p>
68+ * <p/>
6969 * Note that the type of the {@code values} provided to this method will
7070 * not be validated by the driver as is done by {@link BoundStatement#bind} since
7171 * {@code query} is not parsed (and hence the driver cannot know what those value
@@ -79,7 +79,7 @@
7979 * thrown by this constructor however, if the codec registry does not know how to
8080 * handle one of the values.
8181 *
82- * @param query the query string.
82+ * @param query the query string.
8383 * @param values values required for the execution of {@code query}.
8484 * @throws IllegalArgumentException if the number of values is greater than 65535.
8585 */
@@ -97,7 +97,7 @@
9797
9898 @Override
9999 public ByteBuffer[] getValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
100- if(values == null)
100+ if (values == null)
101101 return null;
102102 return convert(values, protocolVersion, codecRegistry);
103103 }
@@ -116,14 +116,13 @@
116116 public boolean hasValues(CodecRegistry codecRegistry) {
117117 return values != null && values.length > 0;
118118 }
119-
119+
120120 /**
121121 * Returns the {@code i}th value as the Java type matching its CQL type.
122122 *
123123 * @param i the index to retrieve.
124124 * @return the value of the {@code i}th value of this statement.
125- *
126- * @throws IllegalStateException if this statement does not have values.
125+ * @throws IllegalStateException if this statement does not have values.
127126 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
128127 */
129128 public Object getObject(int i) {
@@ -136,17 +135,15 @@
136135
137136 /**
138137 * Returns the routing key for the query.
139- * <p>
138+ * <p/>
140139 * Unless the routing key has been explicitly set through
141140 * {@link #setRoutingKey}, this method will return {@code null} to
142141 * avoid having to parse the query string to retrieve the partition key.
143142 *
144143 * @param protocolVersion unused by this implementation (no internal serialization is required to compute the key).
145- * @param codecRegistry unused by this implementation (no internal serialization is required to compute the key).
146- *
144+ * @param codecRegistry unused by this implementation (no internal serialization is required to compute the key).
147145 * @return the routing key set through {@link #setRoutingKey} if such a key
148146 * was set, {@code null} otherwise.
149- *
150147 * @see Statement#getRoutingKey
151148 */
152149 @Override
@@ -156,18 +153,17 @@
156153
157154 /**
158155 * Sets the routing key for this query.
159- * <p>
156+ * <p/>
160157 * This method allows you to manually provide a routing key for this query. It
161158 * is thus optional since the routing key is only an hint for token aware
162159 * load balancing policy but is never mandatory.
163- * <p>
160+ * <p/>
164161 * If the partition key for the query is composite, use the
165162 * {@link #setRoutingKey(ByteBuffer...)} method instead to build the
166163 * routing key.
167164 *
168165 * @param routingKey the raw (binary) value to use as routing key.
169166 * @return this {@code SimpleStatement} object.
170- *
171167 * @see Statement#getRoutingKey
172168 */
173169 public SimpleStatement setRoutingKey(ByteBuffer routingKey) {
@@ -177,14 +173,13 @@
177173
178174 /**
179175 * Returns the keyspace this query operates on.
180- * <p>
176+ * <p/>
181177 * Unless the keyspace has been explicitly set through {@link #setKeyspace},
182178 * this method will return {@code null} to avoid having to parse the query
183179 * string.
184180 *
185181 * @return the keyspace set through {@link #setKeyspace} if such keyspace was
186182 * set, {@code null} otherwise.
187- *
188183 * @see Statement#getKeyspace
189184 */
190185 @Override
@@ -194,18 +189,17 @@
194189
195190 /**
196191 * Sets the keyspace this query operates on.
197- * <p>
192+ * <p/>
198193 * This method allows you to manually provide a keyspace for this query. It
199194 * is thus optional since the value returned by this method is only an hint
200195 * for token aware load balancing policy but is never mandatory.
201- * <p>
196+ * <p/>
202197 * Do note that if the query does not use a fully qualified keyspace, then
203198 * you do not need to set the keyspace through that method as the
204199 * currently logged in keyspace will be used.
205200 *
206201 * @param keyspace the name of the keyspace this query operates on.
207202 * @return this {@code SimpleStatement} object.
208- *
209203 * @see Statement#getKeyspace
210204 */
211205 public SimpleStatement setKeyspace(String keyspace) {
@@ -215,15 +209,14 @@
215209
216210 /**
217211 * Sets the routing key for this query.
218- * <p>
212+ * <p/>
219213 * See {@link #setRoutingKey(ByteBuffer)} for more information. This
220214 * method is a variant for when the query partition key is composite and
221215 * thus the routing key must be built from multiple values.
222216 *
223217 * @param routingKeyComponents the raw (binary) values to compose to obtain
224- * the routing key.
218+ * the routing key.
225219 * @return this {@code SimpleStatement} object.
226- *
227220 * @see Statement#getRoutingKey
228221 */
229222 public SimpleStatement setRoutingKey(ByteBuffer... routingKeyComponents) {
@@ -232,23 +225,23 @@
232225 }
233226
234227 /**
235- * <p>
228+ * <p/>
236229 * Utility method to serialize user-provided values.
237- * <p>
230+ * <p/>
238231 * This method is useful in situations where there is no metadata available and the underlying CQL
239232 * type for the values is not known.
240- * <p>
233+ * <p/>
241234 * This situation happens when a {@link SimpleStatement}
242235 * or a {@link com.datastax.driver.core.querybuilder.BuiltStatement} (Query Builder) contain values;
243236 * in these places, the driver has no way to determine the right CQL type to use.
244- * <p>
237+ * <p/>
245238 * This method performs a best-effort heuristic to guess which codec to use.
246239 * Note that this is not particularly efficient as the codec registry needs to iterate over
247240 * the registered codecs until it finds a suitable one.
248241 *
249- * @param values The values to convert.
242+ * @param values The values to convert.
250243 * @param protocolVersion The protocol version to use.
251- * @param codecRegistry The {@link CodecRegistry} to use.
244+ * @param codecRegistry The {@link CodecRegistry} to use.
252245 * @return The converted values.
253246 */
254247 public static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
@@ -262,7 +255,7 @@
262255 } else {
263256 if (value instanceof Token) {
264257 // bypass CodecRegistry for Token instances
265- serializedValues[i] = ((Token)value).serialize(protocolVersion);
258+ serializedValues[i] = ((Token) value).serialize(protocolVersion);
266259 } else {
267260 try {
268261 TypeCodec<Object> codec = codecRegistry.codecFor(value);
@@ -297,15 +290,15 @@
297290 ByteBuffer bb = buffer.duplicate();
298291 putShortLength(out, bb.remaining());
299292 out.put(bb);
300- out.put((byte)0);
293+ out.put((byte) 0);
301294 }
302295 out.flip();
303296 return out;
304297 }
305298
306299 static void putShortLength(ByteBuffer bb, int length) {
307- bb.put((byte)((length >> 8) & 0xFF));
308- bb.put((byte)(length & 0xFF));
300+ bb.put((byte) ((length >> 8) & 0xFF));
301+ bb.put((byte) (length & 0xFF));
309302 }
310303
311304 }
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +27 −36
@@ -24,7 +24,7 @@
2424 /**
2525 * The default connection timeout in milliseconds if none is set explicitly
2626 * using {@link #setConnectTimeoutMillis}.
27- * <p>
27+ * <p/>
2828 * That default is of 5 seconds.
2929 */
3030 public static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 5000;
@@ -32,7 +32,7 @@
3232 /**
3333 * The default read timeout in milliseconds if none is set explicitly
3434 * using {@link #setReadTimeoutMillis}.
35- * <p>
35+ * <p/>
3636 * That default is of 12 seconds so as to be slightly bigger that the
3737 * default Cassandra timeout.
3838 *
@@ -52,11 +52,12 @@
5252 /**
5353 * Creates a new {@code SocketOptions} instance with default values.
5454 */
55- public SocketOptions() {}
55+ public SocketOptions() {
56+ }
5657
5758 /**
5859 * The connection timeout in milliseconds.
59- * <p>
60+ * <p/>
6061 * As the name implies, the connection timeout defines how long the driver
6162 * waits to establish a new connection to a Cassandra node before giving up.
6263 *
@@ -68,7 +69,7 @@
6869
6970 /**
7071 * Sets the connection timeout in milliseconds.
71- * <p>
72+ * <p/>
7273 * The default value is {@link #DEFAULT_CONNECT_TIMEOUT_MILLIS}.
7374 *
7475 * @param connectTimeoutMillis the timeout to set.
@@ -81,10 +82,10 @@
8182
8283 /**
8384 * The per-host read timeout in milliseconds.
84- * <p>
85+ * <p/>
8586 * This defines how long the driver will wait for a given Cassandra node to
8687 * answer a query.
87- * <p>
88+ * <p/>
8889 * Please note that this is not the maximum time a call to {@link Session#execute} may block;
8990 * this is the maximum time that a call will wait for one particular
9091 * Cassandra host, but other hosts could be tried if one of them times out, depending
@@ -95,12 +96,12 @@
9596 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy} in use).
9697 * If you want to control how long to wait for a query, use {@link Session#executeAsync}
9798 * and the {@code ResultSetFuture#get(long, TimeUnit)} method.
98- * <p>
99+ * <p/>
99100 * Also note that for efficiency reasons, this read timeout is approximate: it
100101 * has an accuracy of up to 100 milliseconds (i.e. it may fire up to 100 milliseconds late).
101102 * It is not meant to be used for precise timeout, but rather as a protection
102103 * against misbehaving Cassandra nodes.
103- * <p>
104+ * <p/>
104105 *
105106 * @return the read timeout in milliseconds.
106107 */
@@ -110,20 +111,20 @@
110111
111112 /**
112113 * Sets the per-host read timeout in milliseconds.
113- * <p>
114+ * <p/>
114115 * When setting this value, keep in mind the following:
115116 * <ul>
116- * <li>it should be higher than the timeout settings used on the Cassandra side
117- * ({@code *_request_timeout_in_ms} in {@code cassandra.yaml}).</li>
118- * <li>the read timeout is only approximate and only control the timeout to one Cassandra
119- * host, not the full query (see {@link #getReadTimeoutMillis} for more details). If a
120- * high level of precision on the timeout to a request is required, you should use
121- * the {@link ResultSetFuture#get(long, java.util.concurrent.TimeUnit)} method.
122- * </li>
117+ * <li>it should be higher than the timeout settings used on the Cassandra side
118+ * ({@code *_request_timeout_in_ms} in {@code cassandra.yaml}).</li>
119+ * <li>the read timeout is only approximate and only control the timeout to one Cassandra
120+ * host, not the full query (see {@link #getReadTimeoutMillis} for more details). If a
121+ * high level of precision on the timeout to a request is required, you should use
122+ * the {@link ResultSetFuture#get(long, java.util.concurrent.TimeUnit)} method.
123+ * </li>
123124 * </ul>
124- * <p>
125+ * <p/>
125126 * Setting a value of 0 disables read timeouts.
126- * <p>
127+ * <p/>
127128 * The default value is {@link #DEFAULT_READ_TIMEOUT_MILLIS}.
128129 *
129130 * @param readTimeoutMillis the timeout to set.
@@ -146,13 +147,12 @@
146147
147148 /**
148149 * Sets whether to enable TCP keepalive.
149- * <p>
150+ * <p/>
150151 * By default, this option is not set by the driver. The actual value will be the default
151152 * from the underlying Netty transport (Java NIO or native epoll).
152153 *
153154 * @param keepAlive whether to enable or disable the option.
154155 * @return this {@code SocketOptions}.
155- *
156156 * @see java.net.SocketOptions#TCP_NODELAY
157157 */
158158 public SocketOptions setKeepAlive(boolean keepAlive) {
@@ -172,13 +172,12 @@
172172
173173 /**
174174 * Sets whether to enable reuse-address.
175- * <p>
175+ * <p/>
176176 * By default, this option is not set by the driver. The actual value will be the default
177177 * from the underlying Netty transport (Java NIO or native epoll).
178178 *
179179 * @param reuseAddress whether to enable or disable the option.
180180 * @return this {@code SocketOptions}.
181- *
182181 * @see java.net.SocketOptions#SO_REUSEADDR
183182 */
184183 public SocketOptions setReuseAddress(boolean reuseAddress) {
@@ -190,7 +189,6 @@
190189 * Returns the linger-on-close timeout.
191190 *
192191 * @return the value of the option, or {@code null} if it is not set.
193- *
194192 * @see #setSoLinger(int)
195193 */
196194 public Integer getSoLinger() {
@@ -199,13 +197,12 @@
199197
200198 /**
201199 * Sets the linger-on-close timeout.
202- * <p>
200+ * <p/>
203201 * By default, this option is not set by the driver. The actual value will be the default
204202 * from the underlying Netty transport (Java NIO or native epoll).
205-
203+ *
206204 * @param soLinger the new value.
207205 * @return this {@code SocketOptions}.
208- *
209206 * @see java.net.SocketOptions#SO_LINGER
210207 */
211208 public SocketOptions setSoLinger(int soLinger) {
@@ -217,7 +214,6 @@
217214 * Returns whether Nagle's algorithm is disabled.
218215 *
219216 * @return the value of the option ({@code true} means Nagle is disabled), or {@code null} if it is not set.
220- *
221217 * @see #setTcpNoDelay(boolean)
222218 */
223219 public Boolean getTcpNoDelay() {
@@ -226,12 +222,11 @@
226222
227223 /**
228224 * Sets whether to disable Nagle's algorithm.
229- * <p>
225+ * <p/>
230226 * By default, this option is set to {@code true} (Nagle disabled).
231227 *
232228 * @param tcpNoDelay whether to enable or disable the option.
233229 * @return this {@code SocketOptions}.
234- *
235230 * @see java.net.SocketOptions#TCP_NODELAY
236231 */
237232 public SocketOptions setTcpNoDelay(boolean tcpNoDelay) {
@@ -243,7 +238,6 @@
243238 * Returns the hint to the size of the underlying buffers for incoming network I/O.
244239 *
245240 * @return the value of the option, or {@code null} if it is not set.
246- *
247241 * @see #setReceiveBufferSize(int)
248242 */
249243 public Integer getReceiveBufferSize() {
@@ -252,13 +246,12 @@
252246
253247 /**
254248 * Sets a hint to the size of the underlying buffers for incoming network I/O.
255- * <p>
249+ * <p/>
256250 * By default, this option is not set by the driver. The actual value will be the default
257251 * from the underlying Netty transport (Java NIO or native epoll).
258252 *
259253 * @param receiveBufferSize the new value.
260254 * @return this {@code SocketOptions}.
261- *
262255 * @see java.net.SocketOptions#SO_RCVBUF
263256 */
264257 public SocketOptions setReceiveBufferSize(int receiveBufferSize) {
@@ -270,7 +263,6 @@
270263 * Returns the hint to the size of the underlying buffers for outgoing network I/O.
271264 *
272265 * @return the value of the option, or {@code null} if it is not set.
273- *
274266 * @see #setSendBufferSize(int)
275267 */
276268 public Integer getSendBufferSize() {
@@ -279,13 +271,12 @@
279271
280272 /**
281273 * Sets a hint to the size of the underlying buffers for outgoing network I/O.
282- * <p>
274+ * <p/>
283275 * By default, this option is not set by the driver. The actual value will be the default
284276 * from the underlying Netty transport (Java NIO or native epoll).
285277 *
286278 * @param sendBufferSize the new value.
287279 * @return this {@code SocketOptions}.
288- *
289280 * @see java.net.SocketOptions#SO_SNDBUF
290281 */
291282 public SocketOptions setSendBufferSize(int sendBufferSize) {
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +47 −52
@@ -15,19 +15,18 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Map;
20-
21-import com.google.common.collect.ImmutableMap;
22-
2318 import com.datastax.driver.core.exceptions.PagingStateException;
2419 import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
2520 import com.datastax.driver.core.policies.RetryPolicy;
2621 import com.datastax.driver.core.querybuilder.BuiltStatement;
22+import com.google.common.collect.ImmutableMap;
23+
24+import java.nio.ByteBuffer;
25+import java.util.Map;
2726
2827 /**
2928 * An executable query.
30- * <p>
29+ * <p/>
3130 * This represents either a {@link RegularStatement}, a {@link BoundStatement} or a
3231 * {@link BatchStatement} along with the querying options (consistency level,
3332 * whether to trace the query, ...).
@@ -97,7 +96,7 @@
9796
9897 /**
9998 * Sets the serial consistency level for the query.
100- *
99+ * <p/>
101100 * The serial consistency level is only used by conditional updates (so INSERT, UPDATE
102101 * and DELETE with an IF condition). For those, the serial consistency level defines
103102 * the consistency level of the serial phase (or "paxos" phase) while the
@@ -107,20 +106,19 @@
107106 * QUORUM read is guaranteed to see that write. But if the regular consistency of that
108107 * write is ANY, then only a read with a consistency of SERIAL is guaranteed to see it
109108 * (even a read with consistency ALL is not guaranteed to be enough).
110- * <p>
109+ * <p/>
111110 * The serial consistency can only be one of {@code ConsistencyLevel.SERIAL} or
112111 * {@code ConsistencyLevel.LOCAL_SERIAL}. While {@code ConsistencyLevel.SERIAL} guarantees full
113112 * linearizability (with other SERIAL updates), {@code ConsistencyLevel.LOCAL_SERIAL} only
114113 * guarantees it in the local data center.
115- * <p>
114+ * <p/>
116115 * The serial consistency level is ignored for any query that is not a conditional
117116 * update (serial reads should use the regular consistency level for instance).
118117 *
119118 * @param serialConsistency the serial consistency level to set.
120119 * @return this {@code Statement} object.
121- *
122120 * @throws IllegalArgumentException if {@code serialConsistency} is not one of
123- * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
121+ * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}.
124122 */
125123 public Statement setSerialConsistencyLevel(ConsistencyLevel serialConsistency) {
126124 if (serialConsistency != ConsistencyLevel.SERIAL && serialConsistency != ConsistencyLevel.LOCAL_SERIAL)
@@ -131,7 +129,7 @@
131129
132130 /**
133131 * The serial consistency level for this query.
134- * <p>
132+ * <p/>
135133 * See {@link #setSerialConsistencyLevel} for more detail on the serial consistency level.
136134 *
137135 * @return the consistency level for this query, or {@code null} if no serial
@@ -144,7 +142,7 @@
144142
145143 /**
146144 * Enables tracing for this query.
147- *
145+ * <p/>
148146 * By default (that is unless you call this method), tracing is not enabled.
149147 *
150148 * @return this {@code Statement} object.
@@ -177,7 +175,7 @@
177175 /**
178176 * Returns the routing key (in binary raw form) to use for token aware
179177 * routing of this query.
180- * <p>
178+ * <p/>
181179 * The routing key is optional in that implementers are free to
182180 * return {@code null}. The routing key is an hint used for token-aware routing (see
183181 * {@link com.datastax.driver.core.policies.TokenAwarePolicy}), and
@@ -189,16 +187,16 @@
189187 * @param protocolVersion the protocol version that will be used if the actual
190188 * implementation needs to serialize something to compute
191189 * the key.
192- * @param codecRegistry the codec registry that will be used if the actual
193- * implementation needs to serialize something to compute
194- * this key.
190+ * @param codecRegistry the codec registry that will be used if the actual
191+ * implementation needs to serialize something to compute
192+ * this key.
195193 * @return the routing key for this query or {@code null}.
196194 */
197195 public abstract ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry);
198196
199197 /**
200198 * Returns the keyspace this query operates on.
201- * <p>
199+ * <p/>
202200 * Note that not all query specify on which keyspace they operate on, and
203201 * so this method can always return {@code null}. Firstly, some queries do
204202 * not operate inside a keyspace: keyspace creation, {@code USE} queries,
@@ -218,7 +216,7 @@
218216
219217 /**
220218 * Sets the retry policy to use for this query.
221- * <p>
219+ * <p/>
222220 * The default retry policy, if this method is not called, is the one returned by
223221 * {@link com.datastax.driver.core.policies.Policies#getRetryPolicy} in the
224222 * cluster configuration. This method is thus only useful in case you want
@@ -245,7 +243,7 @@
245243
246244 /**
247245 * Sets the query fetch size.
248- * <p>
246+ * <p/>
249247 * The fetch size controls how much resulting rows will be retrieved
250248 * simultaneously (the goal being to avoid loading too much results
251249 * in memory for queries yielding large results). Please note that
@@ -253,9 +251,9 @@
253251 * use such a low value in practice as it will yield very poor
254252 * performance. If in doubt, leaving the default is probably a good
255253 * idea.
256- * <p>
254+ * <p/>
257255 * Only {@code SELECT} queries only ever make use of that setting.
258- * <p>
256+ * <p/>
259257 * Note: Paging is not supported with the native protocol version 1. If
260258 * you call this method with {@code fetchSize &gt; 0} and
261259 * {@code fetchSize != Integer.MAX_VALUE} and the protocol version is in
@@ -264,8 +262,8 @@
264262 * when submitting this statement for execution.
265263 *
266264 * @param fetchSize the fetch size to use. If {@code fetchSize &lte; 0},
267- * the default fetch size will be used. To disable paging of the
268- * result set, use {@code fetchSize == Integer.MAX_VALUE}.
265+ * the default fetch size will be used. To disable paging of the
266+ * result set, use {@code fetchSize == Integer.MAX_VALUE}.
269267 * @return this {@code Statement} object.
270268 */
271269 public Statement setFetchSize(int fetchSize) {
@@ -286,11 +284,11 @@
286284
287285 /**
288286 * Sets the default timestamp for this query (in microseconds since the epoch).
289- * <p>
287+ * <p/>
290288 * This feature is only available when version {@link ProtocolVersion#V3 V3} or
291289 * higher of the native protocol is in use. With earlier versions, calling this
292290 * method has no effect.
293- * <p>
291+ * <p/>
294292 * The actual timestamp that will be used for this query is, in order of
295293 * preference:
296294 * <ul>
@@ -305,9 +303,8 @@
305303 * will generate a server-side one (similar to the pre-V3 behavior).
306304 *
307305 * @param defaultTimestamp the default timestamp for this query (must be strictly
308- * positive).
306+ * positive).
309307 * @return this {@code Statement} object.
310- *
311308 * @see Cluster.Builder#withTimestampGenerator(TimestampGenerator)
312309 */
313310 public Statement setDefaultTimestamp(long defaultTimestamp) {
@@ -326,10 +323,10 @@
326323
327324 /**
328325 * Sets the paging state.
329- * <p>
326+ * <p/>
330327 * This will cause the next execution of this statement to fetch results from a given
331328 * page, rather than restarting from the beginning.
332- * <p>
329+ * <p/>
333330 * You get the paging state from a previous execution of the statement (see
334331 * {@link ExecutionInfo#getPagingState()}.
335332 * This is typically used to iterate in a "stateless" manner (e.g. across HTTP requests):
@@ -359,11 +356,11 @@
359356 * }
360357 * }
361358 * </pre>
362- * <p>
359+ * <p/>
363360 * The paging state can only be reused between perfectly identical statements
364361 * (same query string, same bound parameters). Altering the contents of the paging state
365362 * or trying to set it on a different statement will cause this method to fail.
366- * <p>
363+ * <p/>
367364 * Note that, due to internal implementation details, the paging state is not portable
368365 * across native protocol versions (see the
369366 * <a href="http://datastax.github.io/java-driver/features/native_protocol">online documentation</a>
@@ -372,14 +369,12 @@
372369 * with a higher version. If that is a problem for you, consider using the "unsafe" API (see
373370 * {@link #setPagingStateUnsafe(byte[])}).
374371 *
375- * @param pagingState the paging state to set, or {@code null} to remove any state that was
376- * previously set on this statement.
372+ * @param pagingState the paging state to set, or {@code null} to remove any state that was
373+ * previously set on this statement.
377374 * @param codecRegistry the codec registry that will be used if this method needs to serialize the
378375 * statement's values in order to check that the paging state matches.
379376 * @return this {@code Statement} object.
380- *
381377 * @throws PagingStateException if the paging state does not match this statement.
382- *
383378 * @see #setPagingState(PagingState)
384379 */
385380 public Statement setPagingState(PagingState pagingState, CodecRegistry codecRegistry) {
@@ -392,8 +387,8 @@
392387 this.pagingState = pagingState.getRawState();
393388 } else {
394389 throw new PagingStateException("Paging state mismatch, "
395- + "this means that either the paging state contents were altered, "
396- + "or you're trying to apply it to a different statement");
390+ + "this means that either the paging state contents were altered, "
391+ + "or you're trying to apply it to a different statement");
397392 }
398393 }
399394 return this;
@@ -401,16 +396,16 @@
401396
402397 /**
403398 * Sets the paging state.
404- * <p>
399+ * <p/>
405400 * This method calls {@link #setPagingState(PagingState, CodecRegistry)} with {@link CodecRegistry#DEFAULT_INSTANCE}.
406401 * Whether you should use this or the other variant depends on the type of statement this is
407402 * called on:
408403 * <ul>
409- * <li>for a {@link BoundStatement}, the codec registry isn't actually needed, so it's always safe to
410- * use this method;</li>
411- * <li>for a {@link SimpleStatement} or {@link BuiltStatement}, you can use this method if you use no
412- * custom codecs, or if your custom codecs are registered with the default registry. Otherwise, use
413- * the other method and provide the registry that contains your codecs.</li>
404+ * <li>for a {@link BoundStatement}, the codec registry isn't actually needed, so it's always safe to
405+ * use this method;</li>
406+ * <li>for a {@link SimpleStatement} or {@link BuiltStatement}, you can use this method if you use no
407+ * custom codecs, or if your custom codecs are registered with the default registry. Otherwise, use
408+ * the other method and provide the registry that contains your codecs.</li>
414409 * </ul>
415410 *
416411 * @param pagingState the paging state to set, or {@code null} to remove any state that was
@@ -422,7 +417,7 @@
422417
423418 /**
424419 * Sets the paging state.
425- * <p>
420+ * <p/>
426421 * Contrary to {@link #setPagingState(PagingState)}, this method takes the "raw" form of the
427422 * paging state (previously extracted with {@link ExecutionInfo#getPagingStateUnsafe()}.
428423 * It won't validate that this statement matches the one that the paging state was extracted from.
@@ -450,7 +445,7 @@
450445
451446 /**
452447 * Sets whether this statement is idempotent.
453- * <p>
448+ * <p/>
454449 * See {@link #isIdempotent()} for more explanations about this property.
455450 *
456451 * @param idempotent the new value.
@@ -464,21 +459,21 @@
464459 /**
465460 * Whether this statement is idempotent, i.e. whether it can be applied multiple times
466461 * without changing the result beyond the initial application.
467- * <p>
462+ * <p/>
468463 * Idempotence plays a role in {@link com.datastax.driver.core.policies.SpeculativeExecutionPolicy speculative executions}.
469464 * If a statement is <em>not idempotent</em>, the driver will not schedule speculative
470465 * executions for it.
471- * <p>
466+ * <p/>
472467 * Note that this method can return {@code null}, in which case the driver will default to
473468 * {@link QueryOptions#getDefaultIdempotence()}.
474- * <p>
469+ * <p/>
475470 * By default, this method returns {@code null} for all statements, except for
476471 * {@link BuiltStatement}s, where the value will be inferred from the query: if it updates
477472 * counters, prepends/appends to a list, or uses a function call or
478473 * {@link com.datastax.driver.core.querybuilder.QueryBuilder#raw(String)} anywhere in an inserted value,
479474 * the result will be {@code false}; otherwise it will be {@code true}.
480475 * In all cases, calling {@link #setIdempotent(boolean)} forces a value that overrides every other mechanism.
481- * <p>
476+ * <p/>
482477 * Note that when a statement is prepared ({@link Session#prepare(String)}), its idempotence flag will be propagated
483478 * to all {@link PreparedStatement}s created from it.
484479 *
@@ -504,11 +499,11 @@
504499 /**
505500 * Set the given outgoing payload on this statement.
506501 * Each time this statement is executed, this payload will be included in the query request.
507- * <p>
502+ * <p/>
508503 * This method makes a defensive copy of the given map, but its values
509504 * remain inherently mutable. Care should be taken not to modify the original map
510505 * once it is passed to this method.
511- * <p>
506+ * <p/>
512507 * This feature is only available with {@link ProtocolVersion#V4} or above.
513508 * Trying to include custom payloads in requests sent by the driver
514509 * under lower protocol versions will result in an
modified driver-core/src/main/java/com/datastax/driver/core/StatementWrapper.java +6 −6
@@ -15,19 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-
2018 import com.datastax.driver.core.policies.LoadBalancingPolicy;
2119 import com.datastax.driver.core.policies.RetryPolicy;
2220 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2321
22+import java.nio.ByteBuffer;
23+
2424 /**
2525 * Base class for custom {@link Statement} implementations that wrap another statement.
26- * <p>
26+ * <p/>
2727 * This is intended for use with a custom {@link RetryPolicy}, {@link LoadBalancingPolicy} or
2828 * {@link SpeculativeExecutionPolicy}. The client code can wrap a statement to "mark" it, or
2929 * add information that will lead to special handling in the policy.
30- * <p>
30+ * <p/>
3131 * Example:
3232 * <pre>
3333 * {@code
@@ -71,8 +71,8 @@
7171 Statement getWrappedStatement() {
7272 // Protect against multiple levels of wrapping (even though there is no practical reason for that)
7373 return (wrapped instanceof StatementWrapper)
74- ? ((StatementWrapper)wrapped).getWrappedStatement()
75- : wrapped;
74+ ? ((StatementWrapper) wrapped).getWrappedStatement()
75+ : wrapped;
7676 }
7777
7878 @Override
modified driver-core/src/main/java/com/datastax/driver/core/StreamIdGenerator.java +2 −2
@@ -20,11 +20,11 @@
2020
2121 /**
2222 * Manages a set of integer identifiers.
23- * <p>
23+ * <p/>
2424 * Clients can borrow an id with {@link #next()}, and return it to the set with {@link #release(int)}.
2525 * It is guaranteed that a given id can't be borrowed by two clients at the same time.
2626 * This class is thread-safe and non-blocking.
27- * <p>
27+ * <p/>
2828 * Implementation notes: we use an atomic long array where each bit represents an id. It is set to 1 if
2929 * the id is available, 0 otherwise. When looking for an id, we find a long that has remaining 1's and
3030 * pick the rightmost one.
modified driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java +1 −1
@@ -20,7 +20,7 @@
2020
2121 /**
2222 * Allows overriding internal settings via system properties.
23- * <p>
23+ * <p/>
2424 * Warning: this is meant for integration tests only, NOT FOR PRODUCTION USE.
2525 */
2626 class SystemProperties {
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +49 −49
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import com.google.common.base.Objects;
2119 import org.slf4j.Logger;
2220 import org.slf4j.LoggerFactory;
2321
22+import java.util.*;
23+
2424 /**
2525 * Describes a Table.
2626 */
@@ -28,27 +28,27 @@
2828
2929 private static final Logger logger = LoggerFactory.getLogger(TableMetadata.class);
3030
31- private static final String CF_ID_V2 = "cf_id";
32- private static final String CF_ID_V3 = "id";
31+ private static final String CF_ID_V2 = "cf_id";
32+ private static final String CF_ID_V3 = "id";
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
46- private static final String FLAGS = "flags";
47- private static final String DENSE = "dense";
48- private static final String SUPER = "super";
49- private static final String COMPOUND = "compound";
46+ private static final String FLAGS = "flags";
47+ private static final String DENSE = "dense";
48+ private static final String SUPER = "super";
49+ private static final String COMPOUND = "compound";
5050
51- private static final String EMPTY_TYPE = "empty";
51+ private static final String EMPTY_TYPE = "empty";
5252
5353 private final Map<String, IndexMetadata> indexes;
5454
@@ -91,8 +91,8 @@
9191 comparator = DataTypeClassNameParser.parseWithComposite(row.getString(COMPARATOR), protocolVersion, codecRegistry);
9292 keyValidator = DataTypeClassNameParser.parseWithComposite(row.getString(KEY_VALIDATOR), protocolVersion, codecRegistry);
9393 columnAliases = cassandraVersion.getMajor() >= 2 || row.getString(COLUMN_ALIASES) == null
94- ? Collections.<String>emptyList()
95- : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
94+ ? Collections.<String>emptyList()
95+ : SimpleJSONParser.parseStringList(row.getString(COLUMN_ALIASES));
9696 }
9797
9898 int partitionKeySize = findPartitionKeySize(rawCols.values(), keyValidator);
@@ -139,8 +139,8 @@
139139 // See ControlConnection#refreshSchema for why we'd rather not probably this further. Since table options is one thing
140140 // that tends to change often in Cassandra, it's worth special casing this.
141141 logger.error(String.format("Error parsing schema options for table %s.%s: "
142- + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\").getOptions() will return null",
143- ksm.getName(), name, ksm.getName(), name), e);
142+ + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\").getOptions() will return null",
143+ ksm.getName(), name, ksm.getName(), name), e);
144144 }
145145
146146 TableMetadata tm = new TableMetadata(ksm, name, id, partitionKey, clusteringColumns, columns, indexes, options, clusteringOrder, cassandraVersion);
@@ -158,8 +158,8 @@
158158 // In C* 1.2, only the REGULAR columns are in the columns schema table, so we need to add the names from
159159 // the aliases (and make sure we handle default aliases).
160160 List<String> keyAliases = row.getString(KEY_ALIASES) == null
161- ? Collections.<String>emptyList()
162- : SimpleJSONParser.parseStringList(row.getString(KEY_ALIASES));
161+ ? Collections.<String>emptyList()
162+ : SimpleJSONParser.parseStringList(row.getString(KEY_ALIASES));
163163 for (int i = 0; i < partitionKey.size(); i++) {
164164 String alias = keyAliases.size() > i ? keyAliases.get(i) : (i == 0 ? DEFAULT_KEY_ALIAS : DEFAULT_KEY_ALIAS + (i + 1));
165165 partitionKey.set(i, ColumnMetadata.forAlias(tm, alias, keyValidator.types.get(i)));
@@ -184,7 +184,7 @@
184184
185185 for (ColumnMetadata.Raw rawCol : rawCols.values()) {
186186 DataType dataType;
187- if(cassandraVersion.getMajor() >= 3) {
187+ if (cassandraVersion.getMajor() >= 3) {
188188 dataType = DataTypeCqlNameParser.parse(rawCol.dataType, cluster, ksm.getName(), ksm.userTypes, null, false, false);
189189 } else {
190190 dataType = DataTypeClassNameParser.parseOne(rawCol.dataType, protocolVersion, codecRegistry);
@@ -205,7 +205,7 @@
205205
206206 // legacy secondary indexes (C* < 3.0)
207207 IndexMetadata index = IndexMetadata.fromLegacy(col, rawCol);
208- if(index != null)
208+ if (index != null)
209209 indexes.put(index.getName(), index);
210210 }
211211
@@ -234,15 +234,15 @@
234234 private static Map<String, ColumnMetadata.Raw> pruneStaticCompactTableColumns(Map<String, ColumnMetadata.Raw> rawCols) {
235235 Collection<ColumnMetadata.Raw> cols = rawCols.values();
236236 Iterator<ColumnMetadata.Raw> it = cols.iterator();
237- while(it.hasNext()) {
237+ while (it.hasNext()) {
238238 ColumnMetadata.Raw col = it.next();
239- if(col.kind == ColumnMetadata.Raw.Kind.CLUSTERING_COLUMN) {
239+ if (col.kind == ColumnMetadata.Raw.Kind.CLUSTERING_COLUMN) {
240240 // remove "column1 text" clustering column
241241 it.remove();
242- } else if(col.kind == ColumnMetadata.Raw.Kind.REGULAR) {
242+ } else if (col.kind == ColumnMetadata.Raw.Kind.REGULAR) {
243243 // remove "value blob" regular column
244244 it.remove();
245- } else if(col.kind == ColumnMetadata.Raw.Kind.STATIC) {
245+ } else if (col.kind == ColumnMetadata.Raw.Kind.STATIC) {
246246 // remove "static" keyword
247247 col.kind = ColumnMetadata.Raw.Kind.REGULAR;
248248 }
@@ -257,10 +257,10 @@
257257 private static Map<String, ColumnMetadata.Raw> pruneDenseTableColumnsV3(Map<String, ColumnMetadata.Raw> rawCols) {
258258 Collection<ColumnMetadata.Raw> cols = rawCols.values();
259259 Iterator<ColumnMetadata.Raw> it = cols.iterator();
260- while(it.hasNext()) {
260+ while (it.hasNext()) {
261261 ColumnMetadata.Raw col = it.next();
262262 if (col.kind == ColumnMetadata.Raw.Kind.REGULAR
263- && col.dataType.equals(EMPTY_TYPE)) {
263+ && col.dataType.equals(EMPTY_TYPE)) {
264264 // remove "value empty" regular column
265265 it.remove();
266266 }
@@ -271,9 +271,9 @@
271271 private static Map<String, ColumnMetadata.Raw> pruneDenseTableColumnsV2(Map<String, ColumnMetadata.Raw> rawCols) {
272272 Collection<ColumnMetadata.Raw> cols = rawCols.values();
273273 Iterator<ColumnMetadata.Raw> it = cols.iterator();
274- while(it.hasNext()) {
274+ while (it.hasNext()) {
275275 ColumnMetadata.Raw col = it.next();
276- if(col.kind == ColumnMetadata.Raw.Kind.COMPACT_VALUE && col.name.isEmpty()) {
276+ if (col.kind == ColumnMetadata.Raw.Kind.COMPACT_VALUE && col.name.isEmpty()) {
277277 // remove "" blob regular COMPACT_VALUE column
278278 it.remove();
279279 }
@@ -283,7 +283,7 @@
283283
284284 private static int findPartitionKeySize(Collection<ColumnMetadata.Raw> cols, DataTypeClassNameParser.ParseResult keyValidator) {
285285 // C* 1.2, 2.0, 2.1 and 2.2
286- if(keyValidator != null)
286+ if (keyValidator != null)
287287 return keyValidator.types.size();
288288 // C* 3.0 onwards
289289 int maxId = -1;
@@ -320,8 +320,8 @@
320320 * Returns metadata on a index of this table.
321321 *
322322 * @param name the name of the index to retrieve ({@code name} will be
323- * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
324- * see {@link Metadata#quote}).
323+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
324+ * see {@link Metadata#quote}).
325325 * @return the metadata for the {@code name} index if it exists, or
326326 * {@code null} otherwise.
327327 */
@@ -342,8 +342,8 @@
342342 * Returns metadata on a view of this table.
343343 *
344344 * @param name the name of the view to retrieve ({@code name} will be
345- * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
346- * see {@link Metadata#quote}).
345+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
346+ * see {@link Metadata#quote}).
347347 * @return the metadata for the {@code name} view if it exists, or
348348 * {@code null} otherwise.
349349 */
@@ -367,11 +367,11 @@
367367 /**
368368 * Returns a {@code String} containing CQL queries representing this
369369 * table and the index on it.
370- * <p>
370+ * <p/>
371371 * In other words, this method returns the queries that would allow you to
372372 * recreate the schema of this table, along with the indexes and views defined on
373373 * this table, if any.
374- * <p>
374+ * <p/>
375375 * Note that the returned String is formatted to be human readable (for
376376 * some definition of human readable at least).
377377 *
@@ -437,17 +437,17 @@
437437 if (!(other instanceof TableMetadata))
438438 return false;
439439
440- TableMetadata that = (TableMetadata)other;
440+ TableMetadata that = (TableMetadata) other;
441441
442442 return Objects.equal(this.name, that.name) &&
443- Objects.equal(this.id, that.id) &&
444- Objects.equal(this.partitionKey, that.partitionKey) &&
445- Objects.equal(this.clusteringColumns, that.clusteringColumns) &&
446- Objects.equal(this.columns, that.columns) &&
447- Objects.equal(this.options, that.options) &&
448- Objects.equal(this.clusteringOrder, that.clusteringOrder) &&
449- Objects.equal(this.indexes, that.indexes) &&
450- Objects.equal(this.views, that.views);
443+ Objects.equal(this.id, that.id) &&
444+ Objects.equal(this.partitionKey, that.partitionKey) &&
445+ Objects.equal(this.clusteringColumns, that.clusteringColumns) &&
446+ Objects.equal(this.columns, that.columns) &&
447+ Objects.equal(this.options, that.options) &&
448+ Objects.equal(this.clusteringOrder, that.clusteringOrder) &&
449+ Objects.equal(this.indexes, that.indexes) &&
450+ Objects.equal(this.views, that.views);
451451 }
452452
453453 @Override
modified driver-core/src/main/java/com/datastax/driver/core/TableOptionsMetadata.java +44 −44
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Map;
20-
2118 import com.google.common.base.Objects;
2219 import com.google.common.collect.ImmutableMap;
2320
21+import java.nio.ByteBuffer;
22+import java.util.Map;
23+
2424 public class TableOptionsMetadata {
2525
2626 private static final String COMMENT = "comment";
@@ -111,11 +111,11 @@
111111
112112 if (is210OrHigher) {
113113 this.minIndexInterval = isNullOrAbsent(row, MIN_INDEX_INTERVAL)
114- ? DEFAULT_MIN_INDEX_INTERVAL
115- : row.getInt(MIN_INDEX_INTERVAL);
114+ ? DEFAULT_MIN_INDEX_INTERVAL
115+ : row.getInt(MIN_INDEX_INTERVAL);
116116 this.maxIndexInterval = isNullOrAbsent(row, MAX_INDEX_INTERVAL)
117- ? DEFAULT_MAX_INDEX_INTERVAL
118- : row.getInt(MAX_INDEX_INTERVAL);
117+ ? DEFAULT_MAX_INDEX_INTERVAL
118+ : row.getInt(MAX_INDEX_INTERVAL);
119119 } else {
120120 this.minIndexInterval = null;
121121 this.maxIndexInterval = null;
@@ -133,9 +133,9 @@
133133 this.compaction = ImmutableMap.copyOf(row.getMap(COMPACTION, String.class, String.class));
134134 else {
135135 this.compaction = ImmutableMap.<String, String>builder()
136- .put("class", row.getString(COMPACTION_CLASS))
137- .putAll(SimpleJSONParser.parseStringMap(row.getString(COMPACTION_OPTIONS)))
138- .build();
136+ .put("class", row.getString(COMPACTION_CLASS))
137+ .putAll(SimpleJSONParser.parseStringMap(row.getString(COMPACTION_OPTIONS)))
138+ .build();
139139 }
140140
141141 if (is300OrHigher)
@@ -145,12 +145,12 @@
145145
146146 if (is300OrHigher)
147147 this.crcCheckChance = isNullOrAbsent(row, CRC_CHECK_CHANCE)
148- ? DEFAULT_CRC_CHECK_CHANCE
149- : row.getDouble(CRC_CHECK_CHANCE);
148+ ? DEFAULT_CRC_CHECK_CHANCE
149+ : row.getDouble(CRC_CHECK_CHANCE);
150150 else
151151 this.crcCheckChance = null;
152152
153- if(is300OrHigher)
153+ if (is300OrHigher)
154154 this.extensions = ImmutableMap.copyOf(row.getMap(EXTENSIONS, String.class, ByteBuffer.class));
155155 else
156156 this.extensions = ImmutableMap.of();
@@ -158,7 +158,7 @@
158158
159159 private static boolean isNullOrAbsent(Row row, String name) {
160160 return row.getColumnDefinitions().getIndexOf(name) < 0
161- || row.isNull(name);
161+ || row.isNull(name);
162162 }
163163
164164 /**
@@ -199,7 +199,7 @@
199199
200200 /**
201201 * Returns whether replicateOnWrite is set for this table.
202- *
202+ * <p/>
203203 * This is only meaningful for tables holding counters.
204204 *
205205 * @return whether replicateOnWrite is set for this table.
@@ -259,7 +259,7 @@
259259
260260 /**
261261 * Returns the default TTL for this table.
262- * <p>
262+ * <p/>
263263 * Note: this option is not available in Cassandra 1.2 and will return 0 (no default
264264 * TTL) when connected to 1.2 nodes.
265265 *
@@ -272,7 +272,7 @@
272272
273273 /**
274274 * Returns the speculative retry option for this table.
275- * <p>
275+ * <p/>
276276 * Note: this option is not available in Cassandra 1.2 and will return "NONE" (no
277277 * speculative retry) when connected to 1.2 nodes.
278278 *
@@ -284,7 +284,7 @@
284284
285285 /**
286286 * Returns the index interval option for this table.
287- * <p>
287+ * <p/>
288288 * Note: this option is not available in Cassandra 1.2 (more precisely, it is not
289289 * configurable per-table) and will return 128 (the default index interval) when
290290 * connected to 1.2 nodes. It is deprecated in Cassandra 2.1 and above, and will
@@ -298,7 +298,7 @@
298298
299299 /**
300300 * Returns the minimum index interval option for this table.
301- * <p>
301+ * <p/>
302302 * Note: this option is available in Cassandra 2.1 and above, and will return
303303 * {@code null} for earlier versions.
304304 *
@@ -310,7 +310,7 @@
310310
311311 /**
312312 * Returns the maximum index interval option for this table.
313- * <p>
313+ * <p/>
314314 * Note: this option is available in Cassandra 2.1 and above, and will return
315315 * {@code null} for earlier versions.
316316 *
@@ -324,11 +324,11 @@
324324 * When compression is enabled, this option defines the probability
325325 * with which checksums for compressed blocks are checked during reads.
326326 * The default value for this options is 1.0 (always check).
327- * <p>
327+ * <p/>
328328 * Note that this option is available in Cassandra 3.0.0 and above, when it
329329 * became a "top-level" table option, whereas previously it was a suboption
330330 * of the {@link #getCompression() compression} option.
331- * <p>
331+ * <p/>
332332 * For Cassandra versions prior to 3.0.0, this method always returns {@code null}.
333333 *
334334 * @return the probability with which checksums for compressed blocks are checked during reads
@@ -357,7 +357,7 @@
357357
358358 /**
359359 * Returns the extension options for this table.
360- * <p>
360+ * <p/>
361361 * For Cassandra versions prior to 3.0.0, this method always returns an empty map.
362362 *
363363 * @return an immutable map containing the extension options for this table.
@@ -373,32 +373,32 @@
373373 if (!(other instanceof TableOptionsMetadata))
374374 return false;
375375
376- TableOptionsMetadata that = (TableOptionsMetadata)other;
376+ TableOptionsMetadata that = (TableOptionsMetadata) other;
377377 return this.isCompactStorage == that.isCompactStorage &&
378- Objects.equal(this.comment, that.comment) &&
379- this.readRepair == that.readRepair &&
380- this.localReadRepair == that.localReadRepair &&
381- this.replicateOnWrite == that.replicateOnWrite &&
382- this.gcGrace == that.gcGrace &&
383- this.bfFpChance == that.bfFpChance &&
384- Objects.equal(this.caching, that.caching) &&
385- this.populateCacheOnFlush == that.populateCacheOnFlush &&
386- this.memtableFlushPeriodMs == that.memtableFlushPeriodMs &&
387- this.defaultTTL == that.defaultTTL &&
388- Objects.equal(this.speculativeRetry, that.speculativeRetry) &&
389- Objects.equal(this.indexInterval, that.indexInterval) &&
390- Objects.equal(this.minIndexInterval, that.minIndexInterval) &&
391- Objects.equal(this.maxIndexInterval, that.maxIndexInterval) &&
392- Objects.equal(this.compaction, that.compaction) &&
393- Objects.equal(this.compression, that.compression) &&
394- Objects.equal(this.crcCheckChance, that.crcCheckChance) &&
395- Objects.equal(this.extensions, that.extensions);
378+ Objects.equal(this.comment, that.comment) &&
379+ this.readRepair == that.readRepair &&
380+ this.localReadRepair == that.localReadRepair &&
381+ this.replicateOnWrite == that.replicateOnWrite &&
382+ this.gcGrace == that.gcGrace &&
383+ this.bfFpChance == that.bfFpChance &&
384+ Objects.equal(this.caching, that.caching) &&
385+ this.populateCacheOnFlush == that.populateCacheOnFlush &&
386+ this.memtableFlushPeriodMs == that.memtableFlushPeriodMs &&
387+ this.defaultTTL == that.defaultTTL &&
388+ Objects.equal(this.speculativeRetry, that.speculativeRetry) &&
389+ Objects.equal(this.indexInterval, that.indexInterval) &&
390+ Objects.equal(this.minIndexInterval, that.minIndexInterval) &&
391+ Objects.equal(this.maxIndexInterval, that.maxIndexInterval) &&
392+ Objects.equal(this.compaction, that.compaction) &&
393+ Objects.equal(this.compression, that.compression) &&
394+ Objects.equal(this.crcCheckChance, that.crcCheckChance) &&
395+ Objects.equal(this.extensions, that.extensions);
396396 }
397397
398398 @Override
399399 public int hashCode() {
400400 return Objects.hashCode(isCompactStorage, comment, readRepair, localReadRepair, replicateOnWrite, gcGrace,
401- bfFpChance, caching, populateCacheOnFlush, memtableFlushPeriodMs, defaultTTL, speculativeRetry,
402- indexInterval, minIndexInterval, maxIndexInterval, compaction, compression, crcCheckChance, extensions);
401+ bfFpChance, caching, populateCacheOnFlush, memtableFlushPeriodMs, defaultTTL, speculativeRetry,
402+ indexInterval, minIndexInterval, maxIndexInterval, compaction, compression, crcCheckChance, extensions);
403403 }
404404 }
modified driver-core/src/main/java/com/datastax/driver/core/TableOrView.java +25 −24
@@ -16,11 +16,11 @@
1616 package com.datastax.driver.core;
1717
1818
19-import java.util.*;
20-
2119 import com.google.common.base.Predicate;
2220 import com.google.common.collect.Iterables;
2321
22+import java.util.*;
23+
2424 /**
2525 * Base class for Tables and Materialized Views.
2626 */
@@ -49,14 +49,14 @@
4949 protected final VersionNumber cassandraVersion;
5050
5151 TableOrView(KeyspaceMetadata keyspace,
52- String name,
53- UUID id,
54- List<ColumnMetadata> partitionKey,
55- List<ColumnMetadata> clusteringColumns,
56- Map<String, ColumnMetadata> columns,
57- TableOptionsMetadata options,
58- List<ClusteringOrder> clusteringOrder,
59- VersionNumber cassandraVersion) {
52+ String name,
53+ UUID id,
54+ List<ColumnMetadata> partitionKey,
55+ List<ColumnMetadata> clusteringColumns,
56+ Map<String, ColumnMetadata> columns,
57+ TableOptionsMetadata options,
58+ List<ClusteringOrder> clusteringOrder,
59+ VersionNumber cassandraVersion) {
6060 this.keyspace = keyspace;
6161 this.name = name;
6262 this.id = id;
@@ -79,7 +79,7 @@
7979
8080 /**
8181 * Returns the unique id of this table.
82- * <p>
82+ * <p/>
8383 * Note: this id is available in Cassandra 2.1 and above. It will be
8484 * {@code null} for earlier versions.
8585 *
@@ -102,8 +102,8 @@
102102 * Returns metadata on a column of this table.
103103 *
104104 * @param name the name of the column to retrieve ({@code name} will be
105- * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
106- * see {@link Metadata#quote}).
105+ * interpreted as a case-insensitive identifier unless enclosed in double-quotes,
106+ * see {@link Metadata#quote}).
107107 * @return the metadata for the column if it exists, or
108108 * {@code null} otherwise.
109109 */
@@ -113,7 +113,7 @@
113113
114114 /**
115115 * Returns a list containing all the columns of this table.
116- *
116+ * <p/>
117117 * The order of the columns in the list is consistent with
118118 * the order of the columns returned by a {@code SELECT * FROM thisTable}:
119119 * the first column is the partition key, next are the clustering
@@ -128,7 +128,7 @@
128128
129129 /**
130130 * Returns the list of columns composing the primary key for this table.
131- *
131+ * <p/>
132132 * A table will always at least have a partition key (that
133133 * may itself be one or more columns), so the returned list at least
134134 * has one element.
@@ -144,7 +144,7 @@
144144
145145 /**
146146 * Returns the list of columns composing the partition key for this table.
147- *
147+ * <p/>
148148 * A table always has a partition key so the returned list has
149149 * at least one element.
150150 *
@@ -166,7 +166,7 @@
166166
167167 /**
168168 * Returns the clustering order for this table.
169- * <p>
169+ * <p/>
170170 * The returned contains the clustering order of each clustering column. The
171171 * {@code i}th element of the result correspond to the order (ascending or
172172 * descending) of the {@code i}th clustering column (see
@@ -196,11 +196,11 @@
196196 /**
197197 * Returns a {@code String} containing CQL queries representing this
198198 * table and the index on it.
199- * <p>
199+ * <p/>
200200 * In other words, this method returns the queries that would allow you to
201201 * recreate the schema of this table, along with the indexes and views defined on
202202 * this table, if any.
203- * <p>
203+ * <p/>
204204 * Note that the returned String is formatted to be human readable (for
205205 * some definition of human readable at least).
206206 *
@@ -217,10 +217,10 @@
217217
218218 /**
219219 * Returns a CQL query representing this table.
220- * <p>
220+ * <p/>
221221 * This method returns a single 'CREATE TABLE' query with the options
222222 * corresponding to this table definition.
223- * <p>
223+ * <p/>
224224 * Note that the returned string is a single line; the returned query
225225 * is not formatted in any way.
226226 *
@@ -233,7 +233,7 @@
233233
234234 protected abstract String asCQLQuery(boolean formatted);
235235
236- protected StringBuilder appendOptions(StringBuilder sb, boolean formatted){
236+ protected StringBuilder appendOptions(StringBuilder sb, boolean formatted) {
237237 // Options
238238 sb.append(" WITH ");
239239 if (options.isCompactStorage())
@@ -251,7 +251,7 @@
251251 else
252252 and(sb, formatted).append("caching = ").append(formatOptionMap(options.getCaching()));
253253 if (options.getComment() != null)
254- and(sb, formatted).append("comment = '").append(options.getComment().replace("'","''")).append('\'');
254+ and(sb, formatted).append("comment = '").append(options.getComment().replace("'", "''")).append('\'');
255255 and(sb, formatted).append("compaction = ").append(formatOptionMap(options.getCompaction()));
256256 and(sb, formatted).append("compression = ").append(formatOptionMap(options.getCompression()));
257257 if (cassandraVersion.getMajor() >= 2) {
@@ -290,7 +290,8 @@
290290 sb.append("{ ");
291291 boolean first = true;
292292 for (Map.Entry<String, String> entry : m.entrySet()) {
293- if (first) first = false; else sb.append(", ");
293+ if (first) first = false;
294+ else sb.append(", ");
294295 sb.append('\'').append(entry.getKey()).append('\'');
295296 sb.append(" : ");
296297 try {
modified driver-core/src/main/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.java +2 −2
@@ -19,11 +19,11 @@
1919 /**
2020 * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing thread-local counter
2121 * to generate the sub-millisecond part.
22- * <p>
22+ * <p/>
2323 * This implementation guarantees incrementing timestamps for a given client thread, provided that no more than
2424 * 1000 are requested for a given clock tick (the exact granularity of of {@link System#currentTimeMillis()}
2525 * depends on the operating system).
26- * <p>
26+ * <p/>
2727 * If that rate is exceeded, a warning is logged and the timestamps don't increment anymore until the next clock
2828 * tick.
2929 */
modified driver-core/src/main/java/com/datastax/driver/core/TimestampGenerator.java +1 −1
@@ -17,7 +17,7 @@
1717
1818 /**
1919 * Generates client-side, microsecond-precision query timestamps.
20- * <p>
20+ * <p/>
2121 * Given that Cassandra uses those timestamps to resolve conflicts, implementations should generate
2222 * incrementing timestamps for successive implementations.
2323 */
modified driver-core/src/main/java/com/datastax/driver/core/Token.java +103 −64
@@ -15,18 +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;
2227 import java.util.List;
2328
24-import com.google.common.annotations.VisibleForTesting;
25-import com.google.common.collect.Lists;
26-import com.google.common.primitives.UnsignedBytes;
27-
28-import com.datastax.driver.core.utils.Bytes;
29-
3029 /**
3130 * A token on the Cassandra ring.
3231 */
@@ -70,17 +69,24 @@
7069
7170 static abstract class Factory {
7271 abstract Token fromString(String tokenStr);
72+
7373 abstract DataType getTokenType();
74+
7475 abstract Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion);
75- /** The minimum token is a special value that no key ever hashes to, it's used both as lower and upper bound. */
76+
77+ /**
78+ * The minimum token is a special value that no key ever hashes to, it's used both as lower and upper bound.
79+ */
7680 abstract Token minToken();
81+
7782 abstract Token hash(ByteBuffer partitionKey);
83+
7884 abstract List<Token> split(Token startToken, Token endToken, int numberOfSplits);
7985
8086 // Base implementation for split
8187 protected List<BigInteger> split(BigInteger start, BigInteger range,
82- BigInteger ringEnd, BigInteger ringLength,
83- int numberOfSplits) {
88+ BigInteger ringEnd, BigInteger ringLength,
89+ int numberOfSplits) {
8490 BigInteger[] tmp = range.divideAndRemainder(BigInteger.valueOf(numberOfSplits));
8591 BigInteger divider = tmp[0];
8692 int remainder = tmp[1].intValue();
@@ -88,7 +94,7 @@
8894 List<BigInteger> results = Lists.newArrayListWithExpectedSize(numberOfSplits - 1);
8995 BigInteger current = start;
9096 BigInteger dividerPlusOne = (remainder == 0) ? null // won't be used
91- : divider.add(BigInteger.ONE);
97+ : divider.add(BigInteger.ONE);
9298
9399 for (int i = 1; i < numberOfSplits; i++) {
94100 current = current.add(remainder-- > 0 ? dividerPlusOne : divider);
@@ -117,9 +123,9 @@
117123 int i_8 = index << 3;
118124 int blockOffset = offset + i_8;
119125 return ((long) key.get(blockOffset + 0) & 0xff) + (((long) key.get(blockOffset + 1) & 0xff) << 8) +
120- (((long) key.get(blockOffset + 2) & 0xff) << 16) + (((long) key.get(blockOffset + 3) & 0xff) << 24) +
121- (((long) key.get(blockOffset + 4) & 0xff) << 32) + (((long) key.get(blockOffset + 5) & 0xff) << 40) +
122- (((long) key.get(blockOffset + 6) & 0xff) << 48) + (((long) key.get(blockOffset + 7) & 0xff) << 56);
126+ (((long) key.get(blockOffset + 2) & 0xff) << 16) + (((long) key.get(blockOffset + 3) & 0xff) << 24) +
127+ (((long) key.get(blockOffset + 4) & 0xff) << 32) + (((long) key.get(blockOffset + 5) & 0xff) << 40) +
128+ (((long) key.get(blockOffset + 6) & 0xff) << 48) + (((long) key.get(blockOffset + 7) & 0xff) << 56);
123129 }
124130
125131 private long rotl64(long v, int n) {
@@ -154,14 +160,24 @@
154160 //----------
155161 // body
156162
157- for(int i = 0; i < nblocks; i++) {
158- long k1 = getblock(data, offset, i*2+0);
159- long k2 = getblock(data, offset, i*2+1);
160-
161- k1 *= c1; k1 = rotl64(k1,31); k1 *= c2; h1 ^= k1;
162- h1 = rotl64(h1,27); h1 += h2; h1 = h1*5+0x52dce729;
163- k2 *= c2; k2 = rotl64(k2,33); k2 *= c1; h2 ^= k2;
164- h2 = rotl64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5;
163+ for (int i = 0; i < nblocks; i++) {
164+ long k1 = getblock(data, offset, i * 2 + 0);
165+ long k2 = getblock(data, offset, i * 2 + 1);
166+
167+ k1 *= c1;
168+ k1 = rotl64(k1, 31);
169+ k1 *= c2;
170+ h1 ^= k1;
171+ h1 = rotl64(h1, 27);
172+ h1 += h2;
173+ h1 = h1 * 5 + 0x52dce729;
174+ k2 *= c2;
175+ k2 = rotl64(k2, 33);
176+ k2 *= c1;
177+ h2 ^= k2;
178+ h2 = rotl64(h2, 31);
179+ h2 += h1;
180+ h2 = h2 * 5 + 0x38495ab5;
165181 }
166182
167183 //----------
@@ -173,31 +189,54 @@
173189 long k1 = 0;
174190 long k2 = 0;
175191
176- switch(length & 15) {
177- case 15: k2 ^= ((long) data.get(offset+14)) << 48;
178- case 14: k2 ^= ((long) data.get(offset+13)) << 40;
179- case 13: k2 ^= ((long) data.get(offset+12)) << 32;
180- case 12: k2 ^= ((long) data.get(offset+11)) << 24;
181- case 11: k2 ^= ((long) data.get(offset+10)) << 16;
182- case 10: k2 ^= ((long) data.get(offset+9)) << 8;
183- case 9: k2 ^= ((long) data.get(offset+8)) << 0;
184- k2 *= c2; k2 = rotl64(k2,33); k2 *= c1; h2 ^= k2;
185-
186- case 8: k1 ^= ((long) data.get(offset+7)) << 56;
187- case 7: k1 ^= ((long) data.get(offset+6)) << 48;
188- case 6: k1 ^= ((long) data.get(offset+5)) << 40;
189- case 5: k1 ^= ((long) data.get(offset+4)) << 32;
190- case 4: k1 ^= ((long) data.get(offset+3)) << 24;
191- case 3: k1 ^= ((long) data.get(offset+2)) << 16;
192- case 2: k1 ^= ((long) data.get(offset+1)) << 8;
193- case 1: k1 ^= ((long) data.get(offset));
194- k1 *= c1; k1 = rotl64(k1,31); k1 *= c2; h1 ^= k1;
195- };
192+ switch (length & 15) {
193+ case 15:
194+ k2 ^= ((long) data.get(offset + 14)) << 48;
195+ case 14:
196+ k2 ^= ((long) data.get(offset + 13)) << 40;
197+ case 13:
198+ k2 ^= ((long) data.get(offset + 12)) << 32;
199+ case 12:
200+ k2 ^= ((long) data.get(offset + 11)) << 24;
201+ case 11:
202+ k2 ^= ((long) data.get(offset + 10)) << 16;
203+ case 10:
204+ k2 ^= ((long) data.get(offset + 9)) << 8;
205+ case 9:
206+ k2 ^= ((long) data.get(offset + 8)) << 0;
207+ k2 *= c2;
208+ k2 = rotl64(k2, 33);
209+ k2 *= c1;
210+ h2 ^= k2;
211+
212+ case 8:
213+ k1 ^= ((long) data.get(offset + 7)) << 56;
214+ case 7:
215+ k1 ^= ((long) data.get(offset + 6)) << 48;
216+ case 6:
217+ k1 ^= ((long) data.get(offset + 5)) << 40;
218+ case 5:
219+ k1 ^= ((long) data.get(offset + 4)) << 32;
220+ case 4:
221+ k1 ^= ((long) data.get(offset + 3)) << 24;
222+ case 3:
223+ k1 ^= ((long) data.get(offset + 2)) << 16;
224+ case 2:
225+ k1 ^= ((long) data.get(offset + 1)) << 8;
226+ case 1:
227+ k1 ^= ((long) data.get(offset));
228+ k1 *= c1;
229+ k1 = rotl64(k1, 31);
230+ k1 *= c2;
231+ h1 ^= k1;
232+ }
233+ ;
196234
197235 //----------
198236 // finalization
199237
200- h1 ^= length; h2 ^= length;
238+ h1 ^= length;
239+ h2 ^= length;
201240
202241 h1 += h2;
203242 h2 += h1;
@@ -243,16 +282,16 @@
243282 if (startToken.equals(endToken) && startToken.equals(MIN_TOKEN))
244283 endToken = MAX_TOKEN;
245284
246- BigInteger start = BigInteger.valueOf(((M3PToken)startToken).value);
247- BigInteger end = BigInteger.valueOf(((M3PToken)endToken).value);
285+ BigInteger start = BigInteger.valueOf(((M3PToken) startToken).value);
286+ BigInteger end = BigInteger.valueOf(((M3PToken) endToken).value);
248287
249288 BigInteger range = end.subtract(start);
250289 if (range.compareTo(BigInteger.ZERO) < 0)
251290 range = range.add(RING_LENGTH);
252291
253292 List<BigInteger> values = super.split(start, range,
254- RING_END, RING_LENGTH,
255- numberOfSplits);
293+ RING_END, RING_LENGTH,
294+ numberOfSplits);
256295 List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size());
257296 for (BigInteger value : values)
258297 tokens.add(new M3PToken(value.longValue()));
@@ -282,7 +321,7 @@
282321 @Override
283322 public int compareTo(Token other) {
284323 assert other instanceof M3PToken;
285- long otherValue = ((M3PToken)other).value;
324+ long otherValue = ((M3PToken) other).value;
286325 return value < otherValue ? -1 : (value == otherValue) ? 0 : 1;
287326 }
288327
@@ -293,12 +332,12 @@
293332 if (obj == null || this.getClass() != obj.getClass())
294333 return false;
295334
296- return value == ((M3PToken)obj).value;
335+ return value == ((M3PToken) obj).value;
297336 }
298337
299338 @Override
300339 public int hashCode() {
301- return (int)(value^(value>>>32));
340+ return (int) (value ^ (value >>> 32));
302341 }
303342
304343 @Override
@@ -361,8 +400,8 @@
361400 if (tokenOrder == 0 && startToken.equals(MIN_TOKEN))
362401 throw new IllegalArgumentException("Cannot split whole ring with ordered partitioner");
363402
364- OPPToken oppStartToken = (OPPToken)startToken;
365- OPPToken oppEndToken = (OPPToken)endToken;
403+ OPPToken oppStartToken = (OPPToken) startToken;
404+ OPPToken oppEndToken = (OPPToken) endToken;
366405
367406 int significantBytes;
368407 BigInteger start, end, range, ringEnd, ringLength;
@@ -404,8 +443,8 @@
404443 }
405444
406445 List<BigInteger> values = super.split(start, range,
407- ringEnd, ringLength,
408- numberOfSplits);
446+ ringEnd, ringLength,
447+ numberOfSplits);
409448 List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size());
410449 for (BigInteger value : values)
411450 tokens.add(new OPPToken(toBytes(value, significantBytes)));
@@ -461,8 +500,8 @@
461500 private static ByteBuffer stripTrailingZeroBytes(ByteBuffer b) {
462501 byte result[] = Bytes.getArray(b);
463502 int zeroIndex = result.length;
464- for(int i = result.length-1; i > 0; i--) {
465- if(result[i] == 0) {
503+ for (int i = result.length - 1; i > 0; i--) {
504+ if (result[i] == 0) {
466505 zeroIndex = i;
467506 } else {
468507 break;
@@ -490,8 +529,8 @@
490529 public int compareTo(Token other) {
491530 assert other instanceof OPPToken;
492531 return UnsignedBytes.lexicographicalComparator().compare(
493- Bytes.getArray(value),
494- Bytes.getArray(((OPPToken)other).value));
532+ Bytes.getArray(value),
533+ Bytes.getArray(((OPPToken) other).value));
495534 }
496535
497536 @Override
@@ -501,7 +540,7 @@
501540 if (obj == null || this.getClass() != obj.getClass())
502541 return false;
503542
504- return value.equals(((OPPToken)obj).value);
543+ return value.equals(((OPPToken) obj).value);
505544 }
506545
507546 @Override
@@ -571,16 +610,16 @@
571610 if (startToken.equals(endToken) && startToken.equals(MIN_TOKEN))
572611 endToken = MAX_TOKEN;
573612
574- BigInteger start = ((RPToken)startToken).value;
575- BigInteger end = ((RPToken)endToken).value;
613+ BigInteger start = ((RPToken) startToken).value;
614+ BigInteger end = ((RPToken) endToken).value;
576615
577616 BigInteger range = end.subtract(start);
578617 if (range.compareTo(BigInteger.ZERO) < 0)
579618 range = range.add(RING_LENGTH);
580619
581620 List<BigInteger> values = super.split(start, range,
582- MAX_VALUE, RING_LENGTH,
583- numberOfSplits);
621+ MAX_VALUE, RING_LENGTH,
622+ numberOfSplits);
584623 List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size());
585624 for (BigInteger value : values)
586625 tokens.add(new RPToken(value));
@@ -610,7 +649,7 @@
610649 @Override
611650 public int compareTo(Token other) {
612651 assert other instanceof RPToken;
613- return value.compareTo(((RPToken)other).value);
652+ return value.compareTo(((RPToken) other).value);
614653 }
615654
616655 @Override
@@ -620,7 +659,7 @@
620659 if (obj == null || this.getClass() != obj.getClass())
621660 return false;
622661
623- return value.equals(((RPToken)obj).value);
662+ return value.equals(((RPToken) obj).value);
624663 }
625664
626665 @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/TupleType.java +20 −23
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.List;
20-
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
2119 import com.google.common.collect.ImmutableList;
2220
23-import com.datastax.driver.core.exceptions.InvalidTypeException;
21+import java.util.Arrays;
22+import java.util.List;
2423
2524 /**
2625 * A tuple type.
27- * <p>
26+ * <p/>
2827 * A tuple type is a essentially a list of types.
2928 */
3029 public class TupleType extends DataType {
@@ -44,7 +43,7 @@
4443 * Creates a "disconnected" tuple type (<b>you should prefer
4544 * {@link Metadata#newTupleType(DataType...) cluster.getMetadata().newTupleType(...)}
4645 * whenever possible</b>).
47- * <p>
46+ * <p/>
4847 * This method is only exposed for situations where you don't have a {@code Cluster}
4948 * instance available. If you create a type with this method and use it with a
5049 * {@code Cluster} later, you won't be able to set tuple fields with custom codecs
@@ -52,9 +51,8 @@
5251 * match.
5352 *
5453 * @param protocolVersion the protocol version to use.
55- * @param codecRegistry the codec registry to use.
56- * @param types the types for the tuple type.
57- *
54+ * @param codecRegistry the codec registry to use.
55+ * @param types the types for the tuple type.
5856 * @return the newly created tuple type.
5957 */
6058 public static TupleType of(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, DataType... types) {
@@ -83,21 +81,20 @@
8381 /**
8482 * Returns a new value for this tuple type that uses the provided values
8583 * for the components.
86- * <p>
84+ * <p/>
8785 * The numbers of values passed to this method must correspond to the
8886 * number of components in this tuple type. The {@code i}th parameter
8987 * value will then be assigned to the {@code i}th component of the resulting
9088 * tuple value.
9189 *
9290 * @param values the values to use for the component of the resulting
93- * tuple.
91+ * tuple.
9492 * @return a new tuple values based on the provided values.
95- *
9693 * @throws IllegalArgumentException if the number of {@code values}
97- * provided does not correspond to the number of components in this tuple
98- * type.
99- * @throws InvalidTypeException if any of the provided value is not of
100- * the correct type for the component.
94+ * provided does not correspond to the number of components in this tuple
95+ * type.
96+ * @throws InvalidTypeException if any of the provided value is not of
97+ * the correct type for the component.
10198 */
10299 public TupleValue newValue(Object... values) {
103100 if (values.length != types.size())
@@ -106,7 +103,7 @@
106103 TupleValue t = newValue();
107104 for (int i = 0; i < values.length; i++) {
108105 DataType dataType = types.get(i);
109- if(values[i] == null)
106+ if (values[i] == null)
110107 t.setValue(i, null);
111108 else
112109 t.setValue(i, codecRegistry.codecFor(dataType, values[i]).serialize(values[i], protocolVersion));
@@ -145,7 +142,7 @@
145142
146143 @Override
147144 public int hashCode() {
148- return Arrays.hashCode(new Object[]{ name, types });
145+ return Arrays.hashCode(new Object[]{name, types});
149146 }
150147
151148 @Override
@@ -153,20 +150,20 @@
153150 if (!(o instanceof TupleType))
154151 return false;
155152
156- TupleType d = (TupleType)o;
153+ TupleType d = (TupleType) o;
157154 return name == d.name && types.equals(d.types);
158155 }
159156
160157 /**
161158 * Return {@code true} if this tuple type contains the given tuple type,
162159 * and {@code false} otherwise.
163- * <p>
160+ * <p/>
164161 * A tuple type is said to contain another one
165162 * if the latter has fewer components than the former,
166163 * but all of them are of the same type.
167164 * E.g. the type {@code tuple<int, text>}
168165 * is contained by the type {@code tuple<int, text, double>}.
169- * <p>
166+ * <p/>
170167 * A contained type can be seen as a "partial" view
171168 * of a containing type, where the missing components
172169 * are supposed to be {@code null}.
@@ -176,9 +173,9 @@
176173 * and {@code false} otherwise.
177174 */
178175 public boolean contains(TupleType other) {
179- if(this.equals(other))
176+ if (this.equals(other))
180177 return true;
181- if(other.types.size() > this.types.size())
178+ if (other.types.size() > this.types.size())
182179 return false;
183180 return types.subList(0, other.types.size()).equals(other.types);
184181 }
modified driver-core/src/main/java/com/datastax/driver/core/TupleValue.java +1 −1
@@ -61,7 +61,7 @@
6161 if (!(o instanceof TupleValue))
6262 return false;
6363
64- TupleValue that = (TupleValue)o;
64+ TupleValue that = (TupleValue) o;
6565 if (!type.equals(that.type))
6666 return false;
6767
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +171 −149
@@ -15,6 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.datastax.driver.core.utils.Bytes;
20+import com.google.common.collect.ImmutableMap;
21+import com.google.common.reflect.TypeToken;
22+
1823 import java.math.BigDecimal;
1924 import java.math.BigInteger;
2025 import java.net.InetAddress;
@@ -26,78 +31,68 @@
2631 import java.util.*;
2732 import java.util.regex.Pattern;
2833
29-import com.google.common.collect.ImmutableMap;
30-import com.google.common.reflect.TypeToken;
31-
34+import static com.datastax.driver.core.DataType.*;
3235 import static com.google.common.base.Preconditions.checkArgument;
3336 import static com.google.common.base.Preconditions.checkNotNull;
3437
35-import com.datastax.driver.core.exceptions.InvalidTypeException;
36-import com.datastax.driver.core.utils.Bytes;
37-
38-import static com.datastax.driver.core.TypeTokens.listOf;
39-import static com.datastax.driver.core.TypeTokens.mapOf;
40-import static com.datastax.driver.core.TypeTokens.setOf;
41-import static com.datastax.driver.core.DataType.*;
42-
4338 /**
4439 * A Codec that can serialize and deserialize to and from a given
4540 * {@link #getCqlType() CQL type} and a given {@link #getJavaType() Java Type}.
46- *
41+ * <p/>
4742 * <h3>Serializing and deserializing</h3>
48- *
43+ * <p/>
4944 * Two methods handle the serialization and deserialization of Java types into
5045 * CQL types according to the native protocol specifications:
5146 * <ol>
52- * <li>{@link #serialize(Object, ProtocolVersion)}: used to serialize from the codec's Java type to a
53- * {@link ByteBuffer} instance corresponding to the codec's CQL type;</li>
54- * <li>{@link #deserialize(ByteBuffer, ProtocolVersion)}: used to deserialize a {@link ByteBuffer} instance
55- * corresponding to the codec's CQL type to the codec's Java type.</li>
47+ * <li>{@link #serialize(Object, ProtocolVersion)}: used to serialize from the codec's Java type to a
48+ * {@link ByteBuffer} instance corresponding to the codec's CQL type;</li>
49+ * <li>{@link #deserialize(ByteBuffer, ProtocolVersion)}: used to deserialize a {@link ByteBuffer} instance
50+ * corresponding to the codec's CQL type to the codec's Java type.</li>
5651 * </ol>
57- *
52+ * <p/>
5853 * <h3>Formatting and parsing</h3>
59- *
54+ * <p/>
6055 * Two methods handle the formatting and parsing of Java types into
6156 * CQL strings:
6257 * <ol>
63- * <li>{@link #format(Object)}: formats the Java type handled by the codec as a CQL string;</li>
64- * <li>{@link #parse(String)}; parses a CQL string into the Java type handled by the codec.</li>
58+ * <li>{@link #format(Object)}: formats the Java type handled by the codec as a CQL string;</li>
59+ * <li>{@link #parse(String)}; parses a CQL string into the Java type handled by the codec.</li>
6560 * </ol>
66- *
61+ * <p/>
6762 * <h3>Inspection</h3>
68- *
63+ * <p/>
6964 * Codecs also have the following inspection methods:
70- *
65+ * <p/>
7166 * <ol>
72- * <li>{@link #accepts(DataType)}: returns true if the codec can deserialize the given CQL type;</li>
73- * <li>{@link #accepts(TypeToken)}: returns true if the codec can serialize the given Java type;</li>
74- * <li>{@link #accepts(Object)}; returns true if the codec can serialize the given object.</li>
67+ * <li>{@link #accepts(DataType)}: returns true if the codec can deserialize the given CQL type;</li>
68+ * <li>{@link #accepts(TypeToken)}: returns true if the codec can serialize the given Java type;</li>
69+ * <li>{@link #accepts(Object)}; returns true if the codec can serialize the given object.</li>
7570 * </ol>
76- *
71+ * <p/>
7772 * <h3>Implementation notes</h3>
78- *
73+ * <p/>
7974 * <ol>
80- * <li>TypeCodec implementations <em>must</em> be thread-safe.</li>
81- * <li>TypeCodec implementations <em>must</em> perform fast and never block.</li>
82- * <li>TypeCodec implementations <em>must</em> support all native protocol versions; it is not possible
83- * to use different codecs for the same types but under different protocol versions.</li>
84- * <li>TypeCodec implementations must comply with the native protocol specifications; failing
85- * to do so will result in unexpected results and could cause the driver to crash.</li>
86- * <li>TypeCodec implementations <em>should</em> be stateless and immutable.</li>
87- * <li>TypeCodec implementations <em>should</em> interpret {@code null} values and empty ByteBuffers
88- * (i.e. <code>{@link ByteBuffer#remaining()} == 0</code>) in a <em>reasonable</em> way;
89- * usually, {@code NULL} CQL values should map to {@code null} references, but exceptions exist;
90- * e.g. for varchar types, a {@code NULL} CQL value maps to a {@code null} reference,
91- * whereas an empty buffer maps to an empty String. For collection types, it is also admitted that
92- * {@code NULL} CQL values map to empty Java collections instead of {@code null} references.
93- * In any case, the codec's behavior in respect to {@code null} values and empty ByteBuffers
94- * should be clearly documented.</li>
95- * <li>TypeCodec implementations that wish to handle Java primitive types <em>must</em> be instantiated with
96- * the wrapper Java class instead, and implement the appropriate interface
97- * (e.g. {@link com.datastax.driver.core.TypeCodec.PrimitiveBooleanCodec} for primitive {@code boolean} types;
98- * there is one such interface for each Java primitive type).</li>
99- * <li>TypeCodec implementations should not consume {@link ByteBuffer} instances by performing read operations
100- * that modify their current position; if necessary, codecs should {@link ByteBuffer#duplicate()} duplicate} them.</li>
75+ * <li>TypeCodec implementations <em>must</em> be thread-safe.</li>
76+ * <li>TypeCodec implementations <em>must</em> perform fast and never block.</li>
77+ * <li>TypeCodec implementations <em>must</em> support all native protocol versions; it is not possible
78+ * to use different codecs for the same types but under different protocol versions.</li>
79+ * <li>TypeCodec implementations must comply with the native protocol specifications; failing
80+ * to do so will result in unexpected results and could cause the driver to crash.</li>
81+ * <li>TypeCodec implementations <em>should</em> be stateless and immutable.</li>
82+ * <li>TypeCodec implementations <em>should</em> interpret {@code null} values and empty ByteBuffers
83+ * (i.e. <code>{@link ByteBuffer#remaining()} == 0</code>) in a <em>reasonable</em> way;
84+ * usually, {@code NULL} CQL values should map to {@code null} references, but exceptions exist;
85+ * e.g. for varchar types, a {@code NULL} CQL value maps to a {@code null} reference,
86+ * whereas an empty buffer maps to an empty String. For collection types, it is also admitted that
87+ * {@code NULL} CQL values map to empty Java collections instead of {@code null} references.
88+ * In any case, the codec's behavior in respect to {@code null} values and empty ByteBuffers
89+ * should be clearly documented.</li>
90+ * <li>TypeCodec implementations that wish to handle Java primitive types <em>must</em> be instantiated with
91+ * the wrapper Java class instead, and implement the appropriate interface
92+ * (e.g. {@link com.datastax.driver.core.TypeCodec.PrimitiveBooleanCodec} for primitive {@code boolean} types;
93+ * there is one such interface for each Java primitive type).</li>
94+ * <li>TypeCodec implementations should not consume {@link ByteBuffer} instances by performing read operations
95+ * that modify their current position; if necessary, codecs should {@link ByteBuffer#duplicate()} duplicate} them.</li>
10196 * </ol>
10297 *
10398 * @param <T> The codec's Java type
@@ -105,22 +100,23 @@
105100 public abstract class TypeCodec<T> {
106101
107102 private static final Map<TypeToken<?>, TypeToken<?>> primitiveToWrapperMap = ImmutableMap.<TypeToken<?>, TypeToken<?>>builder()
108- .put(TypeToken.of(Boolean.TYPE) , TypeToken.of(Boolean.class))
109- .put(TypeToken.of(Byte.TYPE) , TypeToken.of(Byte.class))
110- .put(TypeToken.of(Character.TYPE), TypeToken.of(Character.class))
111- .put(TypeToken.of(Short.TYPE) , TypeToken.of(Short.class))
112- .put(TypeToken.of(Integer.TYPE) , TypeToken.of(Integer.class))
113- .put(TypeToken.of(Long.TYPE) , TypeToken.of(Long.class))
114- .put(TypeToken.of(Double.TYPE) , TypeToken.of(Double.class))
115- .put(TypeToken.of(Float.TYPE) , TypeToken.of(Float.class))
116- .build();
103+ .put(TypeToken.of(Boolean.TYPE), TypeToken.of(Boolean.class))
104+ .put(TypeToken.of(Byte.TYPE), TypeToken.of(Byte.class))
105+ .put(TypeToken.of(Character.TYPE), TypeToken.of(Character.class))
106+ .put(TypeToken.of(Short.TYPE), TypeToken.of(Short.class))
107+ .put(TypeToken.of(Integer.TYPE), TypeToken.of(Integer.class))
108+ .put(TypeToken.of(Long.TYPE), TypeToken.of(Long.class))
109+ .put(TypeToken.of(Double.TYPE), TypeToken.of(Double.class))
110+ .put(TypeToken.of(Float.TYPE), TypeToken.of(Float.class))
111+ .build();
117112
118113 /**
119114 * Return the default codec for the CQL type {@code boolean}.
120115 * The returned codec maps the CQL type {@code boolean} into the Java type {@link Boolean}.
121116 * The returned instance is a singleton.
117+ *
122118 * @return the default codec for CQL type {@code boolean}.
123- **/
119+ */
124120 public static PrimitiveBooleanCodec cboolean() {
125121 return BooleanCodec.instance;
126122 }
@@ -129,8 +125,9 @@
129125 * Return the default codec for the CQL type {@code tinyint}.
130126 * The returned codec maps the CQL type {@code tinyint} into the Java type {@link Byte}.
131127 * The returned instance is a singleton.
128+ *
132129 * @return the default codec for CQL type {@code tinyint}.
133- **/
130+ */
134131 public static PrimitiveByteCodec tinyInt() {
135132 return TinyIntCodec.instance;
136133 }
@@ -139,8 +136,9 @@
139136 * Return the default codec for the CQL type {@code smallint}.
140137 * The returned codec maps the CQL type {@code smallint} into the Java type {@link Short}.
141138 * The returned instance is a singleton.
139+ *
142140 * @return the default codec for CQL type {@code smallint}.
143- **/
141+ */
144142 public static PrimitiveShortCodec smallInt() {
145143 return SmallIntCodec.instance;
146144 }
@@ -149,8 +147,9 @@
149147 * Return the default codec for the CQL type {@code int}.
150148 * The returned codec maps the CQL type {@code int} into the Java type {@link Integer}.
151149 * The returned instance is a singleton.
150+ *
152151 * @return the default codec for CQL type {@code int}.
153- **/
152+ */
154153 public static PrimitiveIntCodec cint() {
155154 return IntCodec.instance;
156155 }
@@ -159,8 +158,9 @@
159158 * Return the default codec for the CQL type {@code bigint}.
160159 * The returned codec maps the CQL type {@code bigint} into the Java type {@link Long}.
161160 * The returned instance is a singleton.
161+ *
162162 * @return the default codec for CQL type {@code bigint}.
163- **/
163+ */
164164 public static PrimitiveLongCodec bigint() {
165165 return BigintCodec.instance;
166166 }
@@ -169,8 +169,9 @@
169169 * Return the default codec for the CQL type {@code counter}.
170170 * The returned codec maps the CQL type {@code counter} into the Java type {@link Long}.
171171 * The returned instance is a singleton.
172+ *
172173 * @return the default codec for CQL type {@code counter}.
173- **/
174+ */
174175 public static PrimitiveLongCodec counter() {
175176 return CounterCodec.instance;
176177 }
@@ -179,8 +180,9 @@
179180 * Return the default codec for the CQL type {@code float}.
180181 * The returned codec maps the CQL type {@code float} into the Java type {@link Float}.
181182 * The returned instance is a singleton.
183+ *
182184 * @return the default codec for CQL type {@code float}.
183- **/
185+ */
184186 public static PrimitiveFloatCodec cfloat() {
185187 return FloatCodec.instance;
186188 }
@@ -189,8 +191,9 @@
189191 * Return the default codec for the CQL type {@code double}.
190192 * The returned codec maps the CQL type {@code double} into the Java type {@link Double}.
191193 * The returned instance is a singleton.
194+ *
192195 * @return the default codec for CQL type {@code double}.
193- **/
196+ */
194197 public static PrimitiveDoubleCodec cdouble() {
195198 return DoubleCodec.instance;
196199 }
@@ -199,8 +202,9 @@
199202 * Return the default codec for the CQL type {@code varint}.
200203 * The returned codec maps the CQL type {@code varint} into the Java type {@link BigInteger}.
201204 * The returned instance is a singleton.
205+ *
202206 * @return the default codec for CQL type {@code varint}.
203- **/
207+ */
204208 public static TypeCodec<BigInteger> varint() {
205209 return VarintCodec.instance;
206210 }
@@ -209,8 +213,9 @@
209213 * Return the default codec for the CQL type {@code decimal}.
210214 * The returned codec maps the CQL type {@code decimal} into the Java type {@link BigDecimal}.
211215 * The returned instance is a singleton.
216+ *
212217 * @return the default codec for CQL type {@code decimal}.
213- **/
218+ */
214219 public static TypeCodec<BigDecimal> decimal() {
215220 return DecimalCodec.instance;
216221 }
@@ -219,8 +224,9 @@
219224 * Return the default codec for the CQL type {@code ascii}.
220225 * The returned codec maps the CQL type {@code ascii} into the Java type {@link String}.
221226 * The returned instance is a singleton.
227+ *
222228 * @return the default codec for CQL type {@code ascii}.
223- **/
229+ */
224230 public static TypeCodec<String> ascii() {
225231 return AsciiCodec.instance;
226232 }
@@ -229,8 +235,9 @@
229235 * Return the default codec for the CQL type {@code varchar}.
230236 * The returned codec maps the CQL type {@code varchar} into the Java type {@link String}.
231237 * The returned instance is a singleton.
238+ *
232239 * @return the default codec for CQL type {@code varchar}.
233- **/
240+ */
234241 public static TypeCodec<String> varchar() {
235242 return VarcharCodec.instance;
236243 }
@@ -239,8 +246,9 @@
239246 * Return the default codec for the CQL type {@code blob}.
240247 * The returned codec maps the CQL type {@code blob} into the Java type {@link ByteBuffer}.
241248 * The returned instance is a singleton.
249+ *
242250 * @return the default codec for CQL type {@code blob}.
243- **/
251+ */
244252 public static TypeCodec<ByteBuffer> blob() {
245253 return BlobCodec.instance;
246254 }
@@ -249,8 +257,9 @@
249257 * Return the default codec for the CQL type {@code date}.
250258 * The returned codec maps the CQL type {@code date} into the Java type {@link LocalDate}.
251259 * The returned instance is a singleton.
260+ *
252261 * @return the default codec for CQL type {@code date}.
253- **/
262+ */
254263 public static TypeCodec<LocalDate> date() {
255264 return DateCodec.instance;
256265 }
@@ -259,8 +268,9 @@
259268 * Return the default codec for the CQL type {@code time}.
260269 * The returned codec maps the CQL type {@code time} into the Java type {@link Long}.
261270 * The returned instance is a singleton.
271+ *
262272 * @return the default codec for CQL type {@code time}.
263- **/
273+ */
264274 public static PrimitiveLongCodec time() {
265275 return TimeCodec.instance;
266276 }
@@ -269,8 +279,9 @@
269279 * Return the default codec for the CQL type {@code timestamp}.
270280 * The returned codec maps the CQL type {@code timestamp} into the Java type {@link Date}.
271281 * The returned instance is a singleton.
282+ *
272283 * @return the default codec for CQL type {@code timestamp}.
273- **/
284+ */
274285 public static TypeCodec<Date> timestamp() {
275286 return TimestampCodec.instance;
276287 }
@@ -279,8 +290,9 @@
279290 * Return the default codec for the CQL type {@code uuid}.
280291 * The returned codec maps the CQL type {@code uuid} into the Java type {@link UUID}.
281292 * The returned instance is a singleton.
293+ *
282294 * @return the default codec for CQL type {@code uuid}.
283- **/
295+ */
284296 public static TypeCodec<UUID> uuid() {
285297 return UUIDCodec.instance;
286298 }
@@ -289,8 +301,9 @@
289301 * Return the default codec for the CQL type {@code timeuuid}.
290302 * The returned codec maps the CQL type {@code timeuuid} into the Java type {@link UUID}.
291303 * The returned instance is a singleton.
304+ *
292305 * @return the default codec for CQL type {@code timeuuid}.
293- **/
306+ */
294307 public static TypeCodec<UUID> timeUUID() {
295308 return TimeUUIDCodec.instance;
296309 }
@@ -299,8 +312,9 @@
299312 * Return the default codec for the CQL type {@code inet}.
300313 * The returned codec maps the CQL type {@code inet} into the Java type {@link InetAddress}.
301314 * The returned instance is a singleton.
315+ *
302316 * @return the default codec for CQL type {@code inet}.
303- **/
317+ */
304318 public static TypeCodec<InetAddress> inet() {
305319 return InetCodec.instance;
306320 }
@@ -311,9 +325,10 @@
311325 * The returned codec maps the CQL type {@code list} into the Java type {@link List}.
312326 * This method does not cache returned instances and returns a newly-allocated object
313327 * at each invocation.
328+ *
314329 * @param elementCodec the codec that will handle elements of this list.
315330 * @return A newly-created codec for CQL type {@code list}.
316- **/
331+ */
317332 public static <T> TypeCodec<List<T>> list(TypeCodec<T> elementCodec) {
318333 return new ListCodec<T>(elementCodec);
319334 }
@@ -324,9 +339,10 @@
324339 * The returned codec maps the CQL type {@code set} into the Java type {@link Set}.
325340 * This method does not cache returned instances and returns a newly-allocated object
326341 * at each invocation.
342+ *
327343 * @param elementCodec the codec that will handle elements of this set.
328344 * @return A newly-created codec for CQL type {@code set}.
329- **/
345+ */
330346 public static <T> TypeCodec<Set<T>> set(TypeCodec<T> elementCodec) {
331347 return new SetCodec<T>(elementCodec);
332348 }
@@ -337,10 +353,11 @@
337353 * The returned codec maps the CQL type {@code map} into the Java type {@link Map}.
338354 * This method does not cache returned instances and returns a newly-allocated object
339355 * at each invocation.
340- * @param keyCodec the codec that will handle keys of this map.
356+ *
357+ * @param keyCodec the codec that will handle keys of this map.
341358 * @param valueCodec the codec that will handle values of this map.
342359 * @return A newly-created codec for CQL type {@code map}.
343- **/
360+ */
344361 public static <K, V> TypeCodec<Map<K, V>> map(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec) {
345362 return new MapCodec<K, V>(keyCodec, valueCodec);
346363 }
@@ -350,9 +367,10 @@
350367 * The returned codec maps the user-defined type into the Java type {@link UDTValue}.
351368 * This method does not cache returned instances and returns a newly-allocated object
352369 * at each invocation.
370+ *
353371 * @param type the user-defined type this codec should handle.
354372 * @return A newly-created codec for the given user-defined CQL type.
355- **/
373+ */
356374 public static TypeCodec<UDTValue> userType(UserType type) {
357375 return new UDTCodec(type);
358376 }
@@ -362,9 +380,10 @@
362380 * The returned codec maps the tuple type into the Java type {@link TupleValue}.
363381 * This method does not cache returned instances and returns a newly-allocated object
364382 * at each invocation.
383+ *
365384 * @param type the tuple type this codec should handle.
366385 * @return A newly-created codec for the given CQL tuple type.
367- **/
386+ */
368387 public static TypeCodec<TupleValue> tuple(TupleType type) {
369388 return new TupleCodec(type);
370389 }
@@ -376,9 +395,10 @@
376395 * types that do not have a CQL equivalent.
377396 * This method does not cache returned instances and returns a newly-allocated object
378397 * at each invocation.
398+ *
379399 * @param type the custom type this codec should handle.
380400 * @return A newly-created codec for the given CQL custom type.
381- **/
401+ */
382402 public static TypeCodec<ByteBuffer> custom(CustomType type) {
383403 return new CustomCodec(type);
384404 }
@@ -407,6 +427,7 @@
407427
408428 /**
409429 * Return the Java type that this codec deserializes to and serializes from.
430+ *
410431 * @return The Java type this codec deserializes to and serializes from.
411432 */
412433 public TypeToken<T> getJavaType() {
@@ -415,6 +436,7 @@
415436
416437 /**
417438 * Return the CQL type that this codec deserializes from and serializes to.
439+ *
418440 * @return The Java type this codec deserializes from and serializes to.
419441 */
420442 public DataType getCqlType() {
@@ -424,21 +446,21 @@
424446 /**
425447 * Serialize the given value according to the CQL type
426448 * handled by this codec.
427- * <p>
449+ * <p/>
428450 * Implementation notes:
429451 * <ol>
430- * <li>Null values should be gracefully handled and no exception should be raised;
431- * these should be considered as the equivalent of a NULL CQL value;</li>
432- * <li>Codecs for CQL collection types should not permit null elements;</li>
433- * <li>Codecs for CQL collection types should treat a {@code null} input as
434- * the equivalent of an empty collection.</li>
452+ * <li>Null values should be gracefully handled and no exception should be raised;
453+ * these should be considered as the equivalent of a NULL CQL value;</li>
454+ * <li>Codecs for CQL collection types should not permit null elements;</li>
455+ * <li>Codecs for CQL collection types should treat a {@code null} input as
456+ * the equivalent of an empty collection.</li>
435457 * </ol>
436458 *
437- * @param value An instance of T; may be {@code null}.
459+ * @param value An instance of T; may be {@code null}.
438460 * @param protocolVersion the protocol version to use when serializing
439- * {@code bytes}. In most cases, the proper value to provide for this argument
440- * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
441- * is the protocol version in use by the driver).
461+ * {@code bytes}. In most cases, the proper value to provide for this argument
462+ * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
463+ * is the protocol version in use by the driver).
442464 * @return A {@link ByteBuffer} instance containing the serialized form of T
443465 * @throws InvalidTypeException if the given value does not have the expected type
444466 */
@@ -447,27 +469,27 @@
447469 /**
448470 * Deserialize the given {@link ByteBuffer} instance according to the CQL type
449471 * handled by this codec.
450- * <p>
472+ * <p/>
451473 * Implementation notes:
452474 * <ol>
453- * <li>Null or empty buffers should be gracefully handled and no exception should be raised;
454- * these should be considered as the equivalent of a NULL CQL value and, in most cases, should
455- * map to {@code null} or a default value for the corresponding Java type, if applicable;</li>
456- * <li>Codecs for CQL collection types should clearly document whether they return immutable collections or not
457- * (note that the driver's default collection codecs return <em>mutable</em> collections);</li>
458- * <li>Codecs for CQL collection types should avoid returning {@code null};
459- * they should return empty collections instead (the driver's default collection codecs all comply with this rule).</li>
460- * <li>The provided {@link ByteBuffer} should never be consumed by read operations that
461- * modify its current position; if necessary,
462- * {@link ByteBuffer#duplicate()} duplicate} it before consuming.</li>
475+ * <li>Null or empty buffers should be gracefully handled and no exception should be raised;
476+ * these should be considered as the equivalent of a NULL CQL value and, in most cases, should
477+ * map to {@code null} or a default value for the corresponding Java type, if applicable;</li>
478+ * <li>Codecs for CQL collection types should clearly document whether they return immutable collections or not
479+ * (note that the driver's default collection codecs return <em>mutable</em> collections);</li>
480+ * <li>Codecs for CQL collection types should avoid returning {@code null};
481+ * they should return empty collections instead (the driver's default collection codecs all comply with this rule).</li>
482+ * <li>The provided {@link ByteBuffer} should never be consumed by read operations that
483+ * modify its current position; if necessary,
484+ * {@link ByteBuffer#duplicate()} duplicate} it before consuming.</li>
463485 * </ol>
464486 *
465- * @param bytes A {@link ByteBuffer} instance containing the serialized form of T;
466- * may be {@code null} or empty.
487+ * @param bytes A {@link ByteBuffer} instance containing the serialized form of T;
488+ * may be {@code null} or empty.
467489 * @param protocolVersion the protocol version to use when serializing
468- * {@code bytes}. In most cases, the proper value to provide for this argument
469- * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
470- * is the protocol version in use by the driver).
490+ * {@code bytes}. In most cases, the proper value to provide for this argument
491+ * is the value returned by {@link ProtocolOptions#getProtocolVersion} (which
492+ * is the protocol version in use by the driver).
471493 * @return An instance of T
472494 * @throws InvalidTypeException if the given {@link ByteBuffer} instance cannot be deserialized
473495 */
@@ -505,13 +527,13 @@
505527 /**
506528 * Return {@code true} if this codec is capable of serializing
507529 * the given {@code javaType}.
508- * <p>
530+ * <p/>
509531 * The implementation is <em>invariant</em> with respect to the passed
510532 * argument (through the usage of {@link TypeToken#equals(Object)}
511533 * and <em>it's strongly recommended not to modify this behavior</em>.
512534 * This means that a codec will only ever accept the
513535 * <em>exact</em> Java type that it has been created for.
514- * <p>
536+ * <p/>
515537 * If the argument represents a Java primitive type, its wrapper type
516538 * is considered instead.
517539 *
@@ -548,10 +570,10 @@
548570 * from the object' runtime (raw) type, contrary
549571 * to {@link #accepts(TypeToken)} which is capable of
550572 * handling generic types.
551- * <p>
573+ * <p/>
552574 * This method is intended mostly to be used by the QueryBuilder
553575 * when no type information is available when the codec is used.
554- * <p>
576+ * <p/>
555577 * Implementation notes:
556578 * <ol>
557579 * <li>The default implementation is <em>covariant</em> with respect to the passed
@@ -637,7 +659,7 @@
637659 * A codec that is capable of handling primitive shorts,
638660 * thus avoiding the overhead of boxing and unboxing such primitives.
639661 */
640- public static abstract class PrimitiveShortCodec extends TypeCodec<Short>{
662+ public static abstract class PrimitiveShortCodec extends TypeCodec<Short> {
641663
642664 protected PrimitiveShortCodec(DataType cqlType) {
643665 super(cqlType, Short.class);
@@ -795,7 +817,7 @@
795817
796818 /**
797819 * {@inheritDoc}
798- *
820+ * <p/>
799821 * Implementation note: this method treats {@code null}s and empty buffers differently:
800822 * the formers are mapped to {@code null}s while the latters are mapped to empty strings.
801823 */
@@ -998,8 +1020,8 @@
9981020 */
9991021 private static class BooleanCodec extends PrimitiveBooleanCodec {
10001022
1001- private static final ByteBuffer TRUE = ByteBuffer.wrap(new byte[]{ 1 });
1002- private static final ByteBuffer FALSE = ByteBuffer.wrap(new byte[]{ 0 });
1023+ private static final ByteBuffer TRUE = ByteBuffer.wrap(new byte[]{1});
1024+ private static final ByteBuffer FALSE = ByteBuffer.wrap(new byte[]{0});
10031025
10041026 private static final BooleanCodec instance = new BooleanCodec();
10051027
@@ -1696,8 +1718,8 @@
16961718 bb = eltCodec.serialize(elt, protocolVersion);
16971719 } catch (ClassCastException e) {
16981720 throw new InvalidTypeException(
1699- String.format("Invalid type for %s element, expecting %s but got %s",
1700- cqlType, eltCodec.getJavaType(), elt.getClass()), e);
1721+ String.format("Invalid type for %s element, expecting %s but got %s",
1722+ cqlType, eltCodec.getJavaType(), elt.getClass()), e);
17011723 }
17021724 bbs[i++] = bb;
17031725 }
@@ -1779,7 +1801,7 @@
17791801 public boolean accepts(Object value) {
17801802 if (getJavaType().getRawType().isAssignableFrom(value.getClass())) {
17811803 // runtime type ok, now check element type
1782- Collection<?> coll = (Collection<?>)value;
1804+ Collection<?> coll = (Collection<?>) value;
17831805 if (coll.isEmpty())
17841806 return true;
17851807 Object elt = coll.iterator().next();
@@ -1869,7 +1891,7 @@
18691891 public boolean accepts(Object value) {
18701892 if (value instanceof Map) {
18711893 // runtime type ok, now check key and value types
1872- Map<?, ?> map = (Map<?, ?>)value;
1894+ Map<?, ?> map = (Map<?, ?>) value;
18731895 if (map.isEmpty())
18741896 return true;
18751897 Map.Entry<?, ?> entry = map.entrySet().iterator().next();
@@ -2071,7 +2093,7 @@
20712093 result.put(bb.duplicate());
20722094 }
20732095 }
2074- return (ByteBuffer)result.flip();
2096+ return (ByteBuffer) result.flip();
20752097 }
20762098
20772099 @Override
@@ -2177,10 +2199,10 @@
21772199 * Serialize an individual field in an object, as part of serializing the whole object to a CQL
21782200 * UDT (see {@link #serialize(Object, ProtocolVersion)}).
21792201 *
2180- * @param source The object to read the field from.
2181- * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
2182- * characters, it will be double-quoted (i.e. the string will contain actual
2183- * quote characters, as in {@code "\"foobar\""}).
2202+ * @param source The object to read the field from.
2203+ * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
2204+ * characters, it will be double-quoted (i.e. the string will contain actual
2205+ * quote characters, as in {@code "\"foobar\""}).
21842206 * @param protocolVersion The protocol version to use.
21852207 * @return The serialized field, or {@code null} if that field should be ignored.
21862208 */
@@ -2190,11 +2212,11 @@
21902212 * Deserialize an individual field and set it on an object, as part of deserializing the whole
21912213 * object from a CQL UDT (see {@link #deserialize(ByteBuffer, ProtocolVersion)}).
21922214 *
2193- * @param input The serialized form of the field.
2194- * @param target The object to set the field on.
2195- * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
2196- * characters, it will be double-quoted (i.e. the string will contain actual
2197- * quote characters, as in {@code "\"foobar\""}).
2215+ * @param input The serialized form of the field.
2216+ * @param target The object to set the field on.
2217+ * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
2218+ * characters, it will be double-quoted (i.e. the string will contain actual
2219+ * quote characters, as in {@code "\"foobar\""}).
21982220 * @param protocolVersion The protocol version to use.
21992221 * @return The target object with the field set. In most cases this should be the same as {@code target}, but if you're dealing
22002222 * with immutable types you'll need to return a different instance.
@@ -2205,7 +2227,7 @@
22052227 * Format an individual field in an object as a CQL literal, as part of formatting the whole object
22062228 * (see {@link #format(Object)}).
22072229 *
2208- * @param source The object to read the field from.
2230+ * @param source The object to read the field from.
22092231 * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
22102232 * characters, it will be double-quoted (i.e. the string will contain actual
22112233 * quote characters, as in {@code "\"foobar\""}).
@@ -2217,8 +2239,8 @@
22172239 * Parse an individual field and set it on an object, as part of parsing the whole object
22182240 * (see {@link #parse(String)}).
22192241 *
2220- * @param input The String to parse the field from.
2221- * @param target The value to write to.
2242+ * @param input The String to parse the field from.
2243+ * @param target The value to write to.
22222244 * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
22232245 * characters, it will be double-quoted (i.e. the string will contain actual
22242246 * quote characters, as in {@code "\"foobar\""}).
@@ -2239,7 +2261,7 @@
22392261
22402262 @Override
22412263 public boolean accepts(Object value) {
2242- return super.accepts(value) && ((UDTValue)value).getType().equals(definition);
2264+ return super.accepts(value) && ((UDTValue) value).getType().equals(definition);
22432265 }
22442266
22452267 @Override
@@ -2277,7 +2299,7 @@
22772299 * Base class for codecs mapping CQL {@link TupleType tuples} to Java objects.
22782300 * It can serve as a base class for codecs dealing with
22792301 * direct tuple-to-Pojo mappings.
2280-
2302+ *
22812303 * @param <T> The Java type that this codec handles.
22822304 */
22832305 public abstract static class AbstractTupleCodec<T> extends TypeCodec<T> {
@@ -2298,7 +2320,7 @@
22982320 public boolean accepts(DataType cqlType) {
22992321 // a tuple codec should accept tuple values of a different type,
23002322 // provided that the latter is contained in this codec's type.
2301- return super.accepts(cqlType) && definition.contains((TupleType)cqlType);
2323+ return super.accepts(cqlType) && definition.contains((TupleType) cqlType);
23022324 }
23032325
23042326 @Override
@@ -2321,7 +2343,7 @@
23212343 result.put(bb.duplicate());
23222344 }
23232345 }
2324- return (ByteBuffer)result.flip();
2346+ return (ByteBuffer) result.flip();
23252347 }
23262348
23272349 @Override
@@ -2408,8 +2430,8 @@
24082430 * Serialize an individual field in an object, as part of serializing the whole object to a CQL
24092431 * tuple (see {@link #serialize(Object, ProtocolVersion)}).
24102432 *
2411- * @param source The object to read the field from.
2412- * @param index The index of the field.
2433+ * @param source The object to read the field from.
2434+ * @param index The index of the field.
24132435 * @param protocolVersion The protocol version to use.
24142436 * @return The serialized field, or {@code null} if that field should be ignored.
24152437 */
@@ -2419,9 +2441,9 @@
24192441 * Deserialize an individual field and set it on an object, as part of deserializing the whole
24202442 * object from a CQL tuple (see {@link #deserialize(ByteBuffer, ProtocolVersion)}).
24212443 *
2422- * @param input The serialized form of the field.
2423- * @param target The object to set the field on.
2424- * @param index The index of the field.
2444+ * @param input The serialized form of the field.
2445+ * @param target The object to set the field on.
2446+ * @param index The index of the field.
24252447 * @param protocolVersion The protocol version to use.
24262448 * @return The target object with the field set. In most cases this should be the same as {@code target}, but if you're dealing
24272449 * with immutable types you'll need to return a different instance.
@@ -2433,7 +2455,7 @@
24332455 * (see {@link #format(Object)}).
24342456 *
24352457 * @param source The object to read the field from.
2436- * @param index The index of the field.
2458+ * @param index The index of the field.
24372459 * @return The formatted value.
24382460 */
24392461 protected abstract String formatField(T source, int index);
@@ -2442,9 +2464,9 @@
24422464 * Parse an individual field and set it on an object, as part of parsing the whole object
24432465 * (see {@link #parse(String)}).
24442466 *
2445- * @param input The String to parse the field from.
2467+ * @param input The String to parse the field from.
24462468 * @param target The value to write to.
2447- * @param index The index of the field.
2469+ * @param index The index of the field.
24482470 * @return The target object with the field set. In most cases this should be the same as {@code target}, but if you're dealing
24492471 * with immutable types you'll need to return a different instance.
24502472 */
@@ -2465,7 +2487,7 @@
24652487 public boolean accepts(Object value) {
24662488 // a tuple codec should accept tuple values of a different type,
24672489 // provided that the latter is contained in this codec's type.
2468- return super.accepts(value) && definition.contains(((TupleValue)value).getType());
2490+ return super.accepts(value) && definition.contains(((TupleValue) value).getType());
24692491 }
24702492
24712493 @Override
modified driver-core/src/main/java/com/datastax/driver/core/TypeTokens.java +37 −23
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.reflect.TypeParameter;
19+import com.google.common.reflect.TypeToken;
20+
1821 import java.util.List;
1922 import java.util.Map;
2023 import java.util.Set;
2124
22-import com.google.common.reflect.TypeParameter;
23-import com.google.common.reflect.TypeToken;
24-
2525 /**
2626 * Utility methods to create {@code TypeToken} instances.
2727 */
@@ -34,12 +34,14 @@
3434 * are of the given type.
3535 *
3636 * @param eltType The list element type.
37- * @param <T> The list element type.
37+ * @param <T> The list element type.
3838 * @return A {@link TypeToken} that represents a {@link List} whose elements
3939 * are of the given type.
4040 */
4141 public static <T> TypeToken<List<T>> listOf(Class<T> eltType) {
42- return new TypeToken<List<T>>(){}.where(new TypeParameter<T>(){}, eltType);
42+ return new TypeToken<List<T>>() {
43+ }.where(new TypeParameter<T>() {
44+ }, eltType);
4345 }
4446
4547 /**
@@ -47,12 +49,14 @@
4749 * are of the given type.
4850 *
4951 * @param eltType The list element type.
50- * @param <T> The list element type.
52+ * @param <T> The list element type.
5153 * @return A {@link TypeToken} that represents a {@link List} whose elements
5254 * are of the given type.
5355 */
5456 public static <T> TypeToken<List<T>> listOf(TypeToken<T> eltType) {
55- return new TypeToken<List<T>>(){}.where(new TypeParameter<T>(){}, eltType);
57+ return new TypeToken<List<T>>() {
58+ }.where(new TypeParameter<T>() {
59+ }, eltType);
5660 }
5761
5862 /**
@@ -60,12 +64,14 @@
6064 * are of the given type.
6165 *
6266 * @param eltType The set element type.
63- * @param <T> The set element type.
67+ * @param <T> The set element type.
6468 * @return A {@link TypeToken} that represents a {@link Set} whose elements
6569 * are of the given type.
6670 */
6771 public static <T> TypeToken<Set<T>> setOf(Class<T> eltType) {
68- return new TypeToken<Set<T>>(){}.where(new TypeParameter<T>(){}, eltType);
72+ return new TypeToken<Set<T>>() {
73+ }.where(new TypeParameter<T>() {
74+ }, eltType);
6975 }
7076
7177 /**
@@ -73,45 +79,53 @@
7379 * are of the given type.
7480 *
7581 * @param eltType The set element type.
76- * @param <T> The set element type.
82+ * @param <T> The set element type.
7783 * @return A {@link TypeToken} that represents a {@link Set} whose elements
7884 * are of the given type.
7985 */
8086 public static <T> TypeToken<Set<T>> setOf(TypeToken<T> eltType) {
81- return new TypeToken<Set<T>>(){}.where(new TypeParameter<T>(){}, eltType);
87+ return new TypeToken<Set<T>>() {
88+ }.where(new TypeParameter<T>() {
89+ }, eltType);
8290 }
8391
8492 /**
8593 * Create a {@link TypeToken} that represents a {@link Map} whose keys
8694 * and values are of the given key and value types.
8795 *
88- * @param keyType The map key type.
96+ * @param keyType The map key type.
8997 * @param valueType The map value type
90- * @param <K> The map key type.
91- * @param <V> The map value type
98+ * @param <K> The map key type.
99+ * @param <V> The map value type
92100 * @return A {@link TypeToken} that represents a {@link Map} whose keys
93101 * and values are of the given key and value types
94102 */
95103 public static <K, V> TypeToken<Map<K, V>> mapOf(Class<K> keyType, Class<V> valueType) {
96- return new TypeToken<Map<K, V>>(){}
97- .where(new TypeParameter<K>(){}, keyType)
98- .where(new TypeParameter<V>(){}, valueType);
104+ return new TypeToken<Map<K, V>>() {
105+ }
106+ .where(new TypeParameter<K>() {
107+ }, keyType)
108+ .where(new TypeParameter<V>() {
109+ }, valueType);
99110 }
100111
101112 /**
102113 * Create a {@link TypeToken} that represents a {@link Map} whose keys
103114 * and values are of the given key and value types.
104115 *
105- * @param keyType The map key type.
116+ * @param keyType The map key type.
106117 * @param valueType The map value type
107- * @param <K> The map key type.
108- * @param <V> The map value type
118+ * @param <K> The map key type.
119+ * @param <V> The map value type
109120 * @return A {@link TypeToken} that represents a {@link Map} whose keys
110121 * and values are of the given key and value types
111122 */
112123 public static <K, V> TypeToken<Map<K, V>> mapOf(TypeToken<K> keyType, TypeToken<V> valueType) {
113- return new TypeToken<Map<K, V>>(){}
114- .where(new TypeParameter<K>(){}, keyType)
115- .where(new TypeParameter<V>(){}, valueType);
124+ return new TypeToken<Map<K, V>>() {
125+ }
126+ .where(new TypeParameter<K>() {
127+ }, keyType)
128+ .where(new TypeParameter<V>() {
129+ }, valueType);
116130 }
117131 }
modified driver-core/src/main/java/com/datastax/driver/core/UDTValue.java +1 −3
@@ -15,8 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.google.common.base.Joiner;
19-
2018 /**
2119 * A value for a User Defined Type.
2220 */
@@ -63,7 +61,7 @@
6361 if (!(o instanceof UDTValue))
6462 return false;
6563
66- UDTValue that = (UDTValue)o;
64+ UDTValue that = (UDTValue) o;
6765 if (!definition.equals(that.definition))
6866 return false;
6967
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +21 −22
@@ -15,19 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import com.google.common.collect.ImmutableMap;
2119 import com.google.common.collect.Iterators;
2220
21+import java.util.*;
22+
2323 /**
2424 * A User Defined Type (UDT).
25- * <p>
25+ * <p/>
2626 * A UDT is a essentially a named collection of fields (with a name and a type).
2727 */
2828 public class UserType extends DataType implements Iterable<UserType.Field> {
2929
30- static final String TYPE_NAME = "type_name";
30+ static final String TYPE_NAME = "type_name";
3131 private static final String COLS_NAMES = "field_names";
3232 static final String COLS_TYPES = "field_types";
3333
@@ -58,7 +58,7 @@
5858
5959 ImmutableMap.Builder<String, int[]> builder = new ImmutableMap.Builder<String, int[]>();
6060 for (int i = 0; i < byIdx.length; i++)
61- builder.put(byIdx[i].getName(), new int[]{ i });
61+ builder.put(byIdx[i].getName(), new int[]{i});
6262 this.byName = builder.build();
6363 }
6464
@@ -125,8 +125,8 @@
125125 * Returns whether this UDT contains a given field.
126126 *
127127 * @param name the name to check. Note that {@code name} obey the usual
128- * CQL identifier rules: it should be quoted if it denotes a case sensitive
129- * identifier (you can use {@link Metadata#quote} for the quoting).
128+ * CQL identifier rules: it should be quoted if it denotes a case sensitive
129+ * identifier (you can use {@link Metadata#quote} for the quoting).
130130 * @return {@code true} if this UDT contains a field named {@code name},
131131 * {@code false} otherwise.
132132 */
@@ -157,13 +157,12 @@
157157 * Returns the type of a given field.
158158 *
159159 * @param name the name of the field. Note that {@code name} obey the usual
160- * CQL identifier rules: it should be quoted if it denotes a case sensitive
161- * identifier (you can use {@link Metadata#quote} for the quoting).
160+ * CQL identifier rules: it should be quoted if it denotes a case sensitive
161+ * identifier (you can use {@link Metadata#quote} for the quoting).
162162 * @return the type of field {@code name} if this UDT has a field of this
163163 * name, {@code null} otherwise.
164- *
165164 * @throws IllegalArgumentException if {@code name} is not a field of this
166- * UDT definition.
165+ * UDT definition.
167166 */
168167 public DataType getFieldType(String name) {
169168 int[] idx = byName.get(Metadata.handleId(name));
@@ -192,19 +191,19 @@
192191 if (!(o instanceof UserType))
193192 return false;
194193
195- UserType other = (UserType)o;
194+ UserType other = (UserType) o;
196195
197196 // Note: we don't test byName because it's redundant with byIdx in practice,
198197 // but also because the map holds 'int[]' which don't have proper equal.
199198 return name.equals(other.name)
200- && keyspace.equals(other.keyspace)
201- && typeName.equals(other.typeName)
202- && Arrays.equals(byIdx, other.byIdx);
199+ && keyspace.equals(other.keyspace)
200+ && typeName.equals(other.typeName)
201+ && Arrays.equals(byIdx, other.byIdx);
203202 }
204203
205204 /**
206205 * Returns a CQL query representing this user type in human readable form.
207- * <p>
206+ * <p/>
208207 * This method is equivalent to {@link #asCQLQuery} but the ouptut is
209208 * formatted to be human readable (for some definition of human readable).
210209 *
@@ -216,10 +215,10 @@
216215
217216 /**
218217 * Returns a CQL query representing this user type.
219- * <p>
218+ * <p/>
220219 * This method returns a single 'CREATE TYPE' query corresponding
221220 * to this UDT definition.
222- * <p>
221+ * <p/>
223222 * Note that the returned string is a single line; the returned query
224223 * is not formatted in any way.
225224 *
@@ -310,7 +309,7 @@
310309
311310 @Override
312311 public final int hashCode() {
313- return Arrays.hashCode(new Object[]{ name, type });
312+ return Arrays.hashCode(new Object[]{name, type});
314313 }
315314
316315 @Override
@@ -318,9 +317,9 @@
318317 if (!(o instanceof Field))
319318 return false;
320319
321- Field other = (Field)o;
320+ Field other = (Field) o;
322321 return name.equals(other.name)
323- && type.equals(other.type);
322+ && type.equals(other.type);
324323 }
325324
326325 @Override
@@ -332,7 +331,7 @@
332331 /**
333332 * A "shallow" definition of a UDT that only contains the keyspace and type name, without any information
334333 * about the type's structure.
335- *
334+ * <p/>
336335 * This is used for internal dependency analysis only, and never returned to the client.
337336 *
338337 * @since 3.0.0
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/CodecNotFoundException.java +1 −2
@@ -15,9 +15,8 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18-import com.google.common.reflect.TypeToken;
19-
2018 import com.datastax.driver.core.DataType;
19+import com.google.common.reflect.TypeToken;
2120
2221 /**
2322 * Thrown when a suitable {@link com.datastax.driver.core.TypeCodec} cannot be found by
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 was contacted.
29- * <p>
29+ * <p/>
3030 * This is a shortcut for {@link InetSocketAddress#getAddress() getAddress().getAddress()}.
3131 *
3232 * @return The coordinator host that was contacted;
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
@@ -36,7 +36,7 @@
3636
3737 /**
3838 * Copy the exception.
39- * <p>
39+ * <p/>
4040 * This returns a new exception, equivalent to the original one, except that
4141 * because a new object is created in the current thread, the top-most
4242 * 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 raised 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 is
2626 * available.
27- * <p>
27+ * <p/>
2828 * This exception is thrown if either:
2929 * <ul>
30- * <li>there is no host live in the cluster at the moment of the query;</li>
31- * <li>all hosts that have been tried have failed.</li>
30+ * <li>there is no host live in the cluster at the moment of the query;</li>
31+ * <li>all hosts that have been tried have failed.</li>
3232 * </ul>
33- *
33+ * <p/>
3434 * For debugging purposes, the list of hosts that have been tried along with the
3535 * failure cause can be retrieved using the {@link #getErrors()} 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/OperationTimedOutException.java +2 −2
@@ -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.SocketOptions;
2119
20+import java.net.InetSocketAddress;
21+
2222 /**
2323 * Thrown on a client-side timeout, i.e. when the client didn't hear back from the server within
2424 * {@link SocketOptions#getReadTimeoutMillis()}.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryConsistencyException.java +6 −6
@@ -15,20 +15,20 @@
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 failure to reach the required consistency level during the execution of 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 because either:
2828 * <ul>
29- * <li>the coordinator did not receive enough replica responses within the rpc timeout
30- * set for Cassandra;</li>
31- * <li>some replicas replied with an error.</li>
29+ * <li>the coordinator did not receive enough replica responses within the rpc timeout
30+ * set for Cassandra;</li>
31+ * <li>some replicas replied with an error.</li>
3232 * </ul>.
3333 */
3434 @SuppressWarnings("serial")
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- * <p>
20+ * <p/>
2121 * This corresponds to the exception that Cassandra throws when a (valid) query
2222 * cannot be executed (TimeoutException, UnavailableException, ...).
2323 */
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadFailureException.java +18 −18
@@ -15,13 +15,13 @@
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 non-timeout error during a read query.
24- * <p>
24+ * <p/>
2525 * This happens when some of the replicas that were contacted by the coordinator replied with an error.
2626 */
2727 @SuppressWarnings("serial")
@@ -40,11 +40,11 @@
4040
4141 public ReadFailureException(InetSocketAddress address, ConsistencyLevel consistency, int received, int required, int failed, boolean dataPresent) {
4242 super(address, String.format("Cassandra failure during read query at consistency %s "
43- + "(%d responses were required but only %d replica responded, %d failed)",
44- consistency, required, received, failed),
45- consistency,
46- received,
47- required);
43+ + "(%d responses were required but only %d replica responded, %d failed)",
44+ consistency, required, received, failed),
45+ consistency,
46+ received,
47+ required);
4848 this.failed = failed;
4949 this.dataPresent = dataPresent;
5050 }
@@ -66,7 +66,7 @@
6666
6767 /**
6868 * Whether the actual data was amongst the received replica responses.
69- *
69+ * <p/>
7070 * During reads, Cassandra doesn't request data from every replica to
7171 * minimize internal network traffic. Instead, some replicas are only asked
7272 * for a checksum of the data. A read timeout may occurred even if enough
@@ -82,18 +82,18 @@
8282 @Override
8383 public ReadFailureException copy() {
8484 return new ReadFailureException(getAddress(), getMessage(), this, getConsistencyLevel(), getReceivedAcknowledgements(),
85- getRequiredAcknowledgements(), getFailures(), wasDataRetrieved());
85+ getRequiredAcknowledgements(), getFailures(), wasDataRetrieved());
8686 }
8787
8888 public ReadFailureException copy(InetSocketAddress address) {
8989 return new ReadFailureException(
90- address,
91- getMessage(),
92- this,
93- getConsistencyLevel(),
94- getReceivedAcknowledgements(),
95- getRequiredAcknowledgements(),
96- failed,
97- dataPresent);
90+ address,
91+ getMessage(),
92+ this,
93+ getConsistencyLevel(),
94+ getReceivedAcknowledgements(),
95+ getRequiredAcknowledgements(),
96+ failed,
97+ dataPresent);
9898 }
9999 }
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 replicas are only asked
6969 * for a checksum of the data. A read timeout may occurred even if enough
@@ -79,26 +79,26 @@
7979 @Override
8080 public ReadTimeoutException copy() {
8181 return new ReadTimeoutException(
82- getAddress(),
83- getMessage(),
84- this,
85- getConsistencyLevel(),
86- getReceivedAcknowledgements(),
87- getRequiredAcknowledgements(),
88- wasDataRetrieved()
82+ getAddress(),
83+ getMessage(),
84+ this,
85+ getConsistencyLevel(),
86+ getReceivedAcknowledgements(),
87+ getRequiredAcknowledgements(),
88+ wasDataRetrieved()
8989 );
9090 }
9191
9292 /**
9393 * Create a copy of this exception with a nicer stack trace, and including the coordinator
9494 * address that caused this exception to be raised.
95- * <p>
95+ * <p/>
9696 * This method is mainly intended for internal use by the driver and exists mainly because:
9797 * <ol>
98- * <li>the original exception was decoded from a response frame
99- * and at that time, the coordinator address was not available; and</li>
100- * <li>the newly-created exception will refer to the current thread in its stack trace,
101- * which generally yields a more user-friendly stack trace that the original one.</li>
98+ * <li>the original exception was decoded from a response frame
99+ * and at that time, the coordinator address was not available; and</li>
100+ * <li>the newly-created exception will refer to the current thread in its stack trace,
101+ * which generally yields a more user-friendly stack trace that the original one.</li>
102102 * </ol>
103103 *
104104 * @param address The full address of the host that caused this exception to be thrown.
@@ -106,13 +106,13 @@
106106 */
107107 public ReadTimeoutException copy(InetSocketAddress address) {
108108 return new ReadTimeoutException(
109- address,
110- getMessage(),
111- this,
112- getConsistencyLevel(),
113- getReceivedAcknowledgements(),
114- getRequiredAcknowledgements(),
115- wasDataRetrieved()
109+ address,
110+ getMessage(),
111+ this,
112+ getConsistencyLevel(),
113+ getReceivedAcknowledgements(),
114+ getRequiredAcknowledgements(),
115+ wasDataRetrieved()
116116 );
117117 }
118118
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 replicas
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/UnresolvedUserTypeException.java +1 −1
@@ -17,7 +17,7 @@
1717
1818 /**
1919 * Thrown when a user type cannot be resolved.
20- * <p>
20+ * <p/>
2121 * This exception can be raised when the driver is rebuilding
2222 * its schema metadata, and a user-defined type cannot be completely
2323 * constructed due to some missing information.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedProtocolVersionException.java +2 −2
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import com.datastax.driver.core.ProtocolVersion;
19+
1820 import java.net.InetAddress;
1921 import java.net.InetSocketAddress;
2022
21-import com.datastax.driver.core.ProtocolVersion;
22-
2323 /**
2424 * Indicates that we've attempted to connect to a Cassandra node with a protocol version
2525 * that it cannot handle (e.g., connecting to a C* 1.2 node with protocol version 2).
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteFailureException.java +17 −17
@@ -15,14 +15,14 @@
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 non-timeout error during a write query.
25- * <p>
25+ * <p/>
2626 * This happens when some of the replicas that were contacted by the coordinator replied with an error.
2727 */
2828 @SuppressWarnings("serial")
@@ -40,11 +40,11 @@
4040
4141 public WriteFailureException(InetSocketAddress address, ConsistencyLevel consistency, WriteType writeType, int received, int required, int failed) {
4242 super(address, String.format("Cassandra failure during write query at consistency %s "
43- + "(%d responses were required but only %d replica responded, %d failed)",
44- consistency, required, received, failed),
45- consistency,
46- received,
47- required);
43+ + "(%d responses were required but only %d replica responded, %d failed)",
44+ consistency, required, received, failed),
45+ consistency,
46+ received,
47+ required);
4848 this.writeType = writeType;
4949 this.failed = failed;
5050 }
@@ -77,18 +77,18 @@
7777 @Override
7878 public WriteFailureException copy() {
7979 return new WriteFailureException(getAddress(), getMessage(), this, getConsistencyLevel(), getWriteType(),
80- getReceivedAcknowledgements(), getRequiredAcknowledgements(), getFailures());
80+ getReceivedAcknowledgements(), getRequiredAcknowledgements(), getFailures());
8181 }
8282
8383 public WriteFailureException copy(InetSocketAddress address) {
8484 return new WriteFailureException(
85- address,
86- getMessage(),
87- this,
88- getConsistencyLevel(),
89- getWriteType(),
90- getReceivedAcknowledgements(),
91- getRequiredAcknowledgements(),
92- failed);
85+ address,
86+ getMessage(),
87+ this,
88+ getConsistencyLevel(),
89+ getWriteType(),
90+ getReceivedAcknowledgements(),
91+ getRequiredAcknowledgements(),
92+ failed);
9393 }
9494 }
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 WriteTimeoutException 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/AddressTranslator.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.
@@ -53,10 +53,10 @@
5353 * Translates a Cassandra {@code rpc_address} to another address if necessary.
5454 *
5555 * @param address the address of a node as returned by Cassandra. Note that
56- * if the {@code rpc_address} of a node has been configured to {@code 0.0.0.0}
57- * server side, then the provided address will be the node {@code listen_address},
58- * *not* {@code 0.0.0.0}. Also note that the port for {@code InetSocketAddress}
59- * will always be the one set at Cluster construction time (9042 by default).
56+ * if the {@code rpc_address} of a node has been configured to {@code 0.0.0.0}
57+ * server side, then the provided address will be the node {@code listen_address},
58+ * *not* {@code 0.0.0.0}. Also note that the port for {@code InetSocketAddress}
59+ * will always be the one set at Cluster construction time (9042 by default).
6060 * @return the address the driver should actually use to connect to the node
6161 * designated by {@code address}. If the return is {@code null}, then {@code
6262 * address} will be used by the driver (it is thus equivalent to returing
modified driver-core/src/main/java/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.java +6 −8
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.concurrent.atomic.AtomicInteger;
19-
20-import com.google.common.base.Preconditions;
21-
2218 import com.datastax.driver.core.Cluster;
2319 import com.datastax.driver.core.Host;
2420 import com.datastax.driver.core.Statement;
21+import com.google.common.base.Preconditions;
22+
23+import java.util.concurrent.atomic.AtomicInteger;
2524
2625 /**
2726 * A {@link SpeculativeExecutionPolicy} that schedules a given number of speculative executions, separated by a fixed delay.
@@ -33,16 +32,15 @@
3332 /**
3433 * Builds a new instance.
3534 *
36- * @param constantDelayMillis the delay between each speculative execution. Must be strictly positive.
35+ * @param constantDelayMillis the delay between each speculative execution. Must be strictly positive.
3736 * @param maxSpeculativeExecutions the number of speculative executions. Must be strictly positive.
38- *
3937 * @throws IllegalArgumentException if one of the arguments does not respect the preconditions above.
4038 */
4139 public ConstantSpeculativeExecutionPolicy(final long constantDelayMillis, final int maxSpeculativeExecutions) {
4240 Preconditions.checkArgument(constantDelayMillis > 0,
43- "delay must be strictly positive (was %d)", constantDelayMillis);
41+ "delay must be strictly positive (was %d)", constantDelayMillis);
4442 Preconditions.checkArgument(maxSpeculativeExecutions > 0,
45- "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions);
43+ "number of speculative executions must be strictly positive (was %d)", maxSpeculativeExecutions);
4644 this.constantDelayMillis = constantDelayMillis;
4745 this.maxSpeculativeExecutions = maxSpeculativeExecutions;
4846 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +26 −27
@@ -15,12 +15,7 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.*;
19-import java.util.concurrent.ConcurrentHashMap;
20-import java.util.concurrent.ConcurrentMap;
21-import java.util.concurrent.CopyOnWriteArrayList;
22-import java.util.concurrent.atomic.AtomicInteger;
23-
18+import com.datastax.driver.core.*;
2419 import com.google.common.annotations.VisibleForTesting;
2520 import com.google.common.base.Joiner;
2621 import com.google.common.base.Preconditions;
@@ -29,18 +24,22 @@
2924 import org.slf4j.Logger;
3025 import org.slf4j.LoggerFactory;
3126
32-import com.datastax.driver.core.*;
27+import java.util.*;
28+import java.util.concurrent.ConcurrentHashMap;
29+import java.util.concurrent.ConcurrentMap;
30+import java.util.concurrent.CopyOnWriteArrayList;
31+import java.util.concurrent.atomic.AtomicInteger;
3332
3433 /**
3534 * A data-center aware Round-robin load balancing policy.
36- * <p>
35+ * <p/>
3736 * This policy provides round-robin queries over the node of the local
3837 * data center. It also includes in the query plans returned a configurable
3938 * number of hosts in the remote data centers, but those are always tried
4039 * after the local nodes. In other words, this policy guarantees that no
4140 * host in a remote data center will be queried unless no host in the local
4241 * data center can be reached.
43- * <p>
42+ * <p/>
4443 * If used with a single data center, this policy is equivalent to the
4544 * {@link RoundRobinPolicy}, but its DC awareness incurs a slight overhead
4645 * so the latter should be preferred to this policy in that case.
@@ -123,16 +122,16 @@
123122
124123 @SuppressWarnings("unchecked")
125124 private static CopyOnWriteArrayList<Host> cloneList(CopyOnWriteArrayList<Host> list) {
126- return (CopyOnWriteArrayList<Host>)list.clone();
125+ return (CopyOnWriteArrayList<Host>) list.clone();
127126 }
128127
129128 /**
130129 * Return the HostDistance for the provided host.
131- * <p>
130+ * <p/>
132131 * This policy consider nodes in the local datacenter as {@code LOCAL}.
133132 * For each remote datacenter, it considers a configurable number of
134133 * hosts as {@code REMOTE} and the rest is {@code IGNORED}.
135- * <p>
134+ * <p/>
136135 * To configure how many hosts in each remote datacenter should be considered,
137136 * see {@link Builder#withUsedHostsPerRemoteDc(int)}.
138137 *
@@ -152,13 +151,13 @@
152151 // We need to clone, otherwise our subList call is not thread safe
153152 dcHosts = cloneList(dcHosts);
154153 return dcHosts.subList(0, Math.min(dcHosts.size(), usedHostsPerRemoteDc)).contains(host)
155- ? HostDistance.REMOTE
156- : HostDistance.IGNORED;
154+ ? HostDistance.REMOTE
155+ : HostDistance.IGNORED;
157156 }
158157
159158 /**
160159 * Returns the hosts to use for a new query.
161- * <p>
160+ * <p/>
162161 * The returned plan will always try each known host in the local
163162 * datacenter first, and then, if none of the local host is reachable,
164163 * will try up to a configurable number of other host per remote datacenter.
@@ -166,8 +165,8 @@
166165 * Round-robin algorithm.
167166 *
168167 * @param loggedKeyspace the keyspace currently logged in on for this
169- * query.
170- * @param statement the query for which to build the plan.
168+ * query.
169+ * @param statement the query for which to build the plan.
171170 * @return a new query plan, i.e. an iterator indicating which host to
172171 * try first for querying, which one to use as failover, etc...
173172 */
@@ -210,8 +209,8 @@
210209 }
211210
212211 ConsistencyLevel cl = statement.getConsistencyLevel() == null
213- ? configuration.getQueryOptions().getConsistencyLevel()
214- : statement.getConsistencyLevel();
212+ ? configuration.getQueryOptions().getConsistencyLevel()
213+ : statement.getConsistencyLevel();
215214
216215 if (dontHopForLocalCL && cl.isDCLocal())
217216 return endOfData();
@@ -292,10 +291,10 @@
292291
293292 /**
294293 * Sets the name of the datacenter that will be considered "local" by the policy.
295- * <p>
294+ * <p/>
296295 * This must be the name as known by Cassandra (in other words, the name in that appears in
297296 * {@code system.peers}, or in the output of admin tools like nodetool).
298- * <p>
297+ * <p/>
299298 * If this method isn't called, the policy will default to the datacenter of the first node
300299 * connected to. This will always be ok if all the contact points use at {@code Cluster}
301300 * creation are in the local data-center. Otherwise, you should provide the name yourself
@@ -306,24 +305,24 @@
306305 */
307306 public Builder withLocalDc(String localDc) {
308307 Preconditions.checkArgument(!Strings.isNullOrEmpty(localDc),
309- "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC");
308+ "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC");
310309 this.localDc = localDc;
311310 return this;
312311 }
313312
314313 /**
315314 * Sets the number of hosts per remote datacenter that the policy should consider.
316- * <p>
315+ * <p/>
317316 * The policy's {@code distance()} method will return a {@code HostDistance.REMOTE} distance for only {@code usedHostsPerRemoteDc}
318317 * hosts per remote datacenter. Other hosts of the remote datacenters will be ignored (and thus no connections to them will be
319318 * maintained).
320- * <p>
319+ * <p/>
321320 * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host in the local datacenter can be reached and if the consistency
322321 * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM}, then up to {@code usedHostsPerRemoteDc} hosts per remote
323322 * datacenter will be tried by the policy as a fallback. By default, no remote host will be used for {@code LOCAL_ONE} and
324323 * {@code LOCAL_QUORUM}, since this would change the meaning of the consistency level, somewhat breaking the consistency contract
325324 * (this can be overridden with {@link #allowRemoteDCsForLocalConsistencyLevel()}).
326- * <p>
325+ * <p/>
327326 * If this method isn't called, the policy will default to 0.
328327 *
329328 * @param usedHostsPerRemoteDc the number.
@@ -331,7 +330,7 @@
331330 */
332331 public Builder withUsedHostsPerRemoteDc(int usedHostsPerRemoteDc) {
333332 Preconditions.checkArgument(usedHostsPerRemoteDc >= 0,
334- "usedHostsPerRemoteDc must be equal or greater than 0");
333+ "usedHostsPerRemoteDc must be equal or greater than 0");
335334 this.usedHostsPerRemoteDc = usedHostsPerRemoteDc;
336335 return this;
337336 }
@@ -339,7 +338,7 @@
339338 /**
340339 * Allows the policy to return remote hosts when building query plans for queries having consistency level {@code LOCAL_ONE}
341340 * or {@code LOCAL_QUORUM}.
342- * <p>
341+ * <p/>
343342 * When used in conjunction with {@link #withUsedHostsPerRemoteDc(int) usedHostsPerRemoteDc} > 0, this overrides the policy of
344343 * never using remote datacenter nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is however inadvisable to do
345344 * 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 +33 −32
@@ -23,16 +23,16 @@
2323
2424 /**
2525 * The default retry policy.
26- * <p>
26+ * <p/>
2727 * This policy retries queries in only two cases:
2828 * <ul>
29- * <li>On a read timeout, if enough replicas replied but data was not retrieved.</li>
30- * <li>On a write timeout, if we timeout while writing the distributed log used by batch statements.</li>
29+ * <li>On a read timeout, if enough replicas replied but data was not retrieved.</li>
30+ * <li>On a write timeout, if we timeout while writing the distributed log used by batch statements.</li>
3131 * </ul>
32- * <p>
32+ * <p/>
3333 * This retry policy is conservative in that it will never retry with a
3434 * different consistency level than the one of the initial operation.
35- * <p>
35+ * <p/>
3636 * In some cases, it may be convenient to use a more aggressive retry policy
3737 * like {@link DowngradingConsistencyRetryPolicy}.
3838 */
@@ -40,11 +40,12 @@
4040
4141 public static final DefaultRetryPolicy INSTANCE = new DefaultRetryPolicy();
4242
43- private DefaultRetryPolicy() {}
43+ private DefaultRetryPolicy() {
44+ }
4445
4546 /**
4647 * Defines whether to retry and at which consistency level on a read timeout.
47- * <p>
48+ * <p/>
4849 * This method triggers a maximum of one retry, and only if enough
4950 * replicas had responded to the read request but data was not retrieved
5051 * amongst those. Indeed, that case usually means that enough replica
@@ -54,15 +55,15 @@
5455 * timeout the dead replica will likely have been detected as dead and
5556 * the retry has a high chance of success.
5657 *
57- * @param statement the original query that timed out.
58- * @param cl the original consistency level of the read that timed out.
58+ * @param statement the original query that timed out.
59+ * @param cl the original consistency level of the read that timed out.
5960 * @param requiredResponses the number of responses that were required to
60- * achieve the requested consistency level.
61+ * achieve the requested consistency level.
6162 * @param receivedResponses the number of responses that had been received
62- * by the time the timeout exception was raised.
63- * @param dataRetrieved whether actual data (by opposition to data checksum)
64- * was present in the received responses.
65- * @param nbRetry the number of retries already performed for this operation.
63+ * by the time the timeout exception was raised.
64+ * @param dataRetrieved whether actual data (by opposition to data checksum)
65+ * was present in the received responses.
66+ * @param nbRetry the number of retries already performed for this operation.
6667 * @return {@code RetryDecision.retry(cl)} if no retry attempt has yet been tried and
6768 * {@code receivedResponses >= requiredResponses && !dataRetrieved}, {@code RetryDecision.rethrow()} otherwise.
6869 */
@@ -76,7 +77,7 @@
7677
7778 /**
7879 * Defines whether to retry and at which consistency level on a write timeout.
79- * <p>
80+ * <p/>
8081 * This method triggers a maximum of one retry, and only in the case of
8182 * a {@code WriteType.BATCH_LOG} write. The reasoning for the retry in
8283 * that case is that write to the distributed batch log is tried by the
@@ -87,14 +88,14 @@
8788 * nodes will likely have been detected as dead and the retry has thus a
8889 * high chance of success.
8990 *
90- * @param statement the original query that timed out.
91- * @param cl the original consistency level of the write that timed out.
92- * @param writeType the type of the write that timed out.
91+ * @param statement the original query that timed out.
92+ * @param cl the original consistency level of the write that timed out.
93+ * @param writeType the type of the write that timed out.
9394 * @param requiredAcks the number of acknowledgments that were required to
94- * achieve the requested consistency level.
95+ * achieve the requested consistency level.
9596 * @param receivedAcks the number of acknowledgments that had been received
96- * by the time the timeout exception was raised.
97- * @param nbRetry the number of retry already performed for this operation.
97+ * by the time the timeout exception was raised.
98+ * @param nbRetry the number of retry already performed for this operation.
9899 * @return {@code RetryDecision.retry(cl)} if no retry attempt has yet been tried and
99100 * {@code writeType == WriteType.BATCH_LOG}, {@code RetryDecision.rethrow()} otherwise.
100101 */
@@ -110,7 +111,7 @@
110111 /**
111112 * Defines whether to retry and at which consistency level on an
112113 * unavailable exception.
113- * <p>
114+ * <p/>
114115 * This method triggers a retry iff no retry has been executed before
115116 * (nbRetry == 0), with
116117 * {@link RetryPolicy.RetryDecision#tryNextHost(ConsistencyLevel) RetryDecision.tryNextHost(cl)},
@@ -121,26 +122,26 @@
121122 * be "network" isolated from all the other nodes but can still answer to
122123 * the client, it makes sense to retry the query on another node.
123124 *
124- * @param statement the original query for which the consistency level cannot
125- * be achieved.
126- * @param cl the original consistency level for the operation.
125+ * @param statement the original query for which the consistency level cannot
126+ * be achieved.
127+ * @param cl the original consistency level for the operation.
127128 * @param requiredReplica the number of replica that should have been
128- * (known) alive for the operation to be attempted.
129- * @param aliveReplica the number of replica that were know to be alive by
130- * the coordinator of the operation.
131- * @param nbRetry the number of retry already performed for this operation.
129+ * (known) alive for the operation to be attempted.
130+ * @param aliveReplica the number of replica that were know to be alive by
131+ * the coordinator of the operation.
132+ * @param nbRetry the number of retry already performed for this operation.
132133 * @return {@code RetryDecision.rethrow()}.
133134 */
134135 @Override
135136 public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
136137 return (nbRetry == 0)
137- ? RetryDecision.tryNextHost(cl)
138- : RetryDecision.rethrow();
138+ ? RetryDecision.tryNextHost(cl)
139+ : RetryDecision.rethrow();
139140 }
140141
141142 /**
142143 * {@inheritDoc}
143- * <p>
144+ * <p/>
144145 * For historical reasons, this implementation triggers a retry on the next host in the query plan
145146 * with the same consistency level, regardless of the statement's idempotence.
146147 * Note that this breaks the general rule
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +45 −44
@@ -24,7 +24,7 @@
2424 /**
2525 * A retry policy that sometimes retry with a lower consistency level than
2626 * the one initially requested.
27- * <p>
27+ * <p/>
2828 * <b>BEWARE</b>: This policy may retry queries using a lower consistency
2929 * level than the one initially requested. By doing so, it may break
3030 * consistency guarantees. In other words, if you use this retry policy,
@@ -34,34 +34,34 @@
3434 * are ok with that. It is also highly recommended to always wrap this
3535 * policy into {@link LoggingRetryPolicy} to log the occurrences of
3636 * such consistency break.
37- * <p>
37+ * <p/>
3838 * This policy implements the same retries than the {@link DefaultRetryPolicy}
3939 * policy. But on top of that, it also retries in the following cases:
4040 * <ul>
41- * <li>On a read timeout: if the number of replica that responded is
42- * greater than one but lower than is required by the requested
43- * consistency level, the operation is retried at a lower consistency
44- * level.</li>
45- * <li>On a write timeout: if the operation is an {@code
46- * WriteType.UNLOGGED_BATCH} and at least one replica acknowledged the
47- * write, the operation is retried at a lower consistency level.
48- * Furthermore, for other operation, if at least one replica acknowledged
49- * the write, the timeout is ignored.</li>
50- * <li>On an unavailable exception: if at least one replica is alive, the
51- * operation is retried at a lower consistency level.</li>
41+ * <li>On a read timeout: if the number of replica that responded is
42+ * greater than one but lower than is required by the requested
43+ * consistency level, the operation is retried at a lower consistency
44+ * level.</li>
45+ * <li>On a write timeout: if the operation is an {@code
46+ * WriteType.UNLOGGED_BATCH} and at least one replica acknowledged the
47+ * write, the operation is retried at a lower consistency level.
48+ * Furthermore, for other operation, if at least one replica acknowledged
49+ * the write, the timeout is ignored.</li>
50+ * <li>On an unavailable exception: if at least one replica is alive, the
51+ * operation is retried at a lower consistency level.</li>
5252 * </ul>
53- * <p>
53+ * <p/>
5454 * The reasoning being this retry policy is the following one. If, based
5555 * on the information the Cassandra coordinator node returns, retrying the
5656 * operation with the initially requested consistency has a change to
5757 * succeed, do it. Otherwise, if based on these information we know <b>the
5858 * initially requested consistency level cannot be achieve currently</b>, then:
5959 * <ul>
60- * <li>For writes, ignore the exception (thus silently failing the
61- * consistency requirement) if we know the write has been persisted on at
62- * least one replica.</li>
63- * <li>For reads, try reading at a lower consistency level (thus silently
64- * failing the consistency requirement).</li>
60+ * <li>For writes, ignore the exception (thus silently failing the
61+ * consistency requirement) if we know the write has been persisted on at
62+ * least one replica.</li>
63+ * <li>For reads, try reading at a lower consistency level (thus silently
64+ * failing the consistency requirement).</li>
6565 * </ul>
6666 * In other words, this policy implements the idea that if the requested
6767 * consistency level cannot be achieved, the next best thing for writes is
@@ -72,7 +72,8 @@
7272
7373 public static final DowngradingConsistencyRetryPolicy INSTANCE = new DowngradingConsistencyRetryPolicy();
7474
75- private DowngradingConsistencyRetryPolicy() {}
75+ private DowngradingConsistencyRetryPolicy() {
76+ }
7677
7778 private RetryDecision maxLikelyToWorkCL(int knownOk) {
7879 if (knownOk >= 3)
@@ -87,7 +88,7 @@
8788
8889 /**
8990 * Defines whether to retry and at which consistency level on a read timeout.
90- * <p>
91+ * <p/>
9192 * This method triggers a maximum of one retry. If less replica
9293 * responded than required by the consistency level (but at least one
9394 * replica did respond), the operation is retried at a lower
@@ -95,15 +96,15 @@
9596 * retrieve, the operation is retried with the initial consistency
9697 * level. Otherwise, an exception is thrown.
9798 *
98- * @param statement the original query that timed out.
99- * @param cl the original consistency level of the read that timed out.
99+ * @param statement the original query that timed out.
100+ * @param cl the original consistency level of the read that timed out.
100101 * @param requiredResponses the number of responses that were required to
101- * achieve the requested consistency level.
102+ * achieve the requested consistency level.
102103 * @param receivedResponses the number of responses that had been received
103- * by the time the timeout exception was raised.
104- * @param dataRetrieved whether actual data (by opposition to data checksum)
105- * was present in the received responses.
106- * @param nbRetry the number of retry already performed for this operation.
104+ * by the time the timeout exception was raised.
105+ * @param dataRetrieved whether actual data (by opposition to data checksum)
106+ * was present in the received responses.
107+ * @param nbRetry the number of retry already performed for this operation.
107108 * @return a RetryDecision as defined above.
108109 */
109110 @Override
@@ -128,7 +129,7 @@
128129
129130 /**
130131 * Defines whether to retry and at which consistency level on a write timeout.
131- * <p>
132+ * <p/>
132133 * This method triggers a maximum of one retry. If {@code writeType ==
133134 * WriteType.BATCH_LOG}, the write is retried with the initial
134135 * consistency level. If {@code writeType == WriteType.UNLOGGED_BATCH}
@@ -139,14 +140,14 @@
139140 * and {@code WriteType.BATCH}), if we know the write has been persisted on at
140141 * least one replica, we ignore the exception. Otherwise, an exception is thrown.
141142 *
142- * @param statement the original query that timed out.
143- * @param cl the original consistency level of the write that timed out.
144- * @param writeType the type of the write that timed out.
143+ * @param statement the original query that timed out.
144+ * @param cl the original consistency level of the write that timed out.
145+ * @param writeType the type of the write that timed out.
145146 * @param requiredAcks the number of acknowledgments that were required to
146- * achieve the requested consistency level.
147+ * achieve the requested consistency level.
147148 * @param receivedAcks the number of acknowledgments that had been received
148- * by the time the timeout exception was raised.
149- * @param nbRetry the number of retry already performed for this operation.
149+ * by the time the timeout exception was raised.
150+ * @param nbRetry the number of retry already performed for this operation.
150151 * @return a RetryDecision as defined above.
151152 */
152153 @Override
@@ -173,19 +174,19 @@
173174 /**
174175 * Defines whether to retry and at which consistency level on an
175176 * unavailable exception.
176- * <p>
177+ * <p/>
177178 * This method triggers a maximum of one retry. If at least one replica
178179 * is know to be alive, the operation is retried at a lower consistency
179180 * level.
180181 *
181- * @param statement the original query for which the consistency level cannot
182- * be achieved.
183- * @param cl the original consistency level for the operation.
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.
184185 * @param requiredReplica the number of replica that should have been
185- * (known) alive for the operation to be attempted.
186- * @param aliveReplica the number of replica that were know to be alive by
187- * the coordinator of the operation.
188- * @param nbRetry the number of retry already performed for this operation.
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.
189190 * @return a RetryDecision as defined above.
190191 */
191192 @Override
@@ -199,7 +200,7 @@
199200
200201 /**
201202 * {@inheritDoc}
202- * <p>
203+ * <p/>
203204 * For historical reasons, this implementation triggers a retry on the next host in the query plan
204205 * with the same consistency level, regardless of the statement's idempotence.
205206 * Note that this breaks the general rule
modified driver-core/src/main/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.java +15 −16
@@ -15,12 +15,12 @@
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.Cluster;
19+import com.datastax.driver.core.exceptions.DriverException;
2320 import com.google.common.annotations.VisibleForTesting;
21+import org.slf4j.Logger;
22+import org.slf4j.LoggerFactory;
23+
2424 import javax.naming.Context;
2525 import javax.naming.NamingEnumeration;
2626 import javax.naming.NamingException;
@@ -28,23 +28,22 @@
2828 import javax.naming.directory.Attributes;
2929 import javax.naming.directory.DirContext;
3030 import javax.naming.directory.InitialDirContext;
31-import org.slf4j.Logger;
32-import org.slf4j.LoggerFactory;
33-
34-import com.datastax.driver.core.Cluster;
35-import com.datastax.driver.core.exceptions.DriverException;
31+import java.net.InetAddress;
32+import java.net.InetSocketAddress;
33+import java.util.Enumeration;
34+import java.util.Hashtable;
3635
3736 /**
3837 * {@link AddressTranslator} implementation for a multi-region EC2 deployment <b>where clients are also deployed in EC2</b>.
39- * <p>
38+ * <p/>
4039 * Its distinctive feature is that it translates addresses according to the location of the Cassandra host:
4140 * <ul>
4241 * <li>addresses in different EC2 regions (than the client) are unchanged;</li>
4342 * <li>addresses in the same EC2 region are <b>translated to private IPs</b>.</li>
4443 * </ul>
4544 * This optimizes network costs, because Amazon charges more for communication over public IPs.
46- *
47- * <p>
45+ * <p/>
46+ * <p/>
4847 * Implementation note: this class performs a reverse DNS lookup of the origin address, to find the domain name of the target
4948 * instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the private/public switch automatically
5049 * based on location.
@@ -99,9 +98,9 @@
9998 }
10099
101100 private String lookupPtrRecord(String reversedDomain) throws Exception {
102- Attributes attrs = ctx.getAttributes(reversedDomain, new String[]{ "PTR" });
101+ Attributes attrs = ctx.getAttributes(reversedDomain, new String[]{"PTR"});
103102 for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) {
104- Attribute attr = (Attribute)ae.next();
103+ Attribute attr = (Attribute) ae.next();
105104 for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); )
106105 return vals.nextElement().toString();
107106 }
@@ -142,7 +141,7 @@
142141 int lowNibble = b & 0x0F;
143142 int highNibble = b >> 4 & 0x0F;
144143 builder.append(Integer.toHexString(lowNibble)).append('.')
145- .append(Integer.toHexString(highNibble)).append('.');
144+ .append(Integer.toHexString(highNibble)).append('.');
146145 }
147146 builder.append("ip6.arpa");
148147 return builder.toString();
modified driver-core/src/main/java/com/datastax/driver/core/policies/ExponentialReconnectionPolicy.java +3 −3
@@ -32,8 +32,8 @@
3232 * Creates a reconnection policy waiting exponentially longer for each new attempt.
3333 *
3434 * @param baseDelayMs the base delay in milliseconds to use for
35- * the schedules created by this policy.
36- * @param maxDelayMs the maximum delay to wait between two attempts.
35+ * the schedules created by this policy.
36+ * @param maxDelayMs the maximum delay to wait between two attempts.
3737 */
3838 public ExponentialReconnectionPolicy(long baseDelayMs, long maxDelayMs) {
3939 if (baseDelayMs < 0 || maxDelayMs < 0)
@@ -73,7 +73,7 @@
7373
7474 /**
7575 * A new schedule that used an exponentially growing delay between reconnection attempts.
76- * <p>
76+ * <p/>
7777 * For this schedule, reconnection attempt {@code i} will be tried
7878 * {@code Math.min(2^(i-1) * getBaseDelayMs(), getMaxDelayMs())} milliseconds after the previous one.
7979 *
modified driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java +24 −23
@@ -23,7 +23,7 @@
2323
2424 /**
2525 * A retry policy that never retry (nor ignore).
26- * <p>
26+ * <p/>
2727 * All of the methods of this retry policy unconditionally return {@link RetryPolicy.RetryDecision#rethrow}.
2828 * If this policy is used, retry will have to be implemented in business code.
2929 */
@@ -31,20 +31,21 @@
3131
3232 public static final FallthroughRetryPolicy INSTANCE = new FallthroughRetryPolicy();
3333
34- private FallthroughRetryPolicy() {}
34+ private FallthroughRetryPolicy() {
35+ }
3536
3637 /**
3738 * Defines whether to retry and at which consistency level on a read timeout.
3839 *
39- * @param statement the original query that timed out.
40- * @param cl the original consistency level of the read that timed out.
40+ * @param statement the original query that timed out.
41+ * @param cl the original consistency level of the read that timed out.
4142 * @param requiredResponses the number of responses that were required to
42- * achieve the requested consistency level.
43+ * achieve the requested consistency level.
4344 * @param receivedResponses the number of responses that had been received
44- * by the time the timeout exception was raised.
45- * @param dataRetrieved whether actual data (by opposition to data checksum)
46- * was present in the received responses.
47- * @param nbRetry the number of retry already performed for this operation.
45+ * by the time the timeout exception was raised.
46+ * @param dataRetrieved whether actual data (by opposition to data checksum)
47+ * was present in the received responses.
48+ * @param nbRetry the number of retry already performed for this operation.
4849 * @return {@code RetryDecision.rethrow()}.
4950 */
5051 @Override
@@ -55,14 +56,14 @@
5556 /**
5657 * Defines whether to retry and at which consistency level on a write timeout.
5758 *
58- * @param statement the original query that timed out.
59- * @param cl the original consistency level of the write that timed out.
60- * @param writeType the type of the write that timed out.
59+ * @param statement the original query that timed out.
60+ * @param cl the original consistency level of the write that timed out.
61+ * @param writeType the type of the write that timed out.
6162 * @param requiredAcks the number of acknowledgments that were required to
62- * achieve the requested consistency level.
63+ * achieve the requested consistency level.
6364 * @param receivedAcks the number of acknowledgments that had been received
64- * by the time the timeout exception was raised.
65- * @param nbRetry the number of retry already performed for this operation.
65+ * by the time the timeout exception was raised.
66+ * @param nbRetry the number of retry already performed for this operation.
6667 * @return {@code RetryDecision.rethrow()}.
6768 */
6869 @Override
@@ -74,14 +75,14 @@
7475 * Defines whether to retry and at which consistency level on an
7576 * unavailable exception.
7677 *
77- * @param statement the original query for which the consistency level cannot
78- * be achieved.
79- * @param cl the original consistency level for the operation.
78+ * @param statement the original query for which the consistency level cannot
79+ * be achieved.
80+ * @param cl the original consistency level for the operation.
8081 * @param requiredReplica the number of replica that should have been
81- * (known) alive for the operation to be attempted.
82- * @param aliveReplica the number of replica that were know to be alive by
83- * the coordinator of the operation.
84- * @param nbRetry the number of retry already performed for this operation.
82+ * (known) alive for the operation to be attempted.
83+ * @param aliveReplica the number of replica that were know to be alive by
84+ * the coordinator of the operation.
85+ * @param nbRetry the number of retry already performed for this operation.
8586 * @return {@code RetryDecision.rethrow()}.
8687 */
8788 @Override
@@ -91,7 +92,7 @@
9192
9293 /**
9394 * {@inheritDoc}
94- * <p>
95+ * <p/>
9596 * This implementation always returns {@code RetryDecision.rethrow()}.
9697 */
9798 @Override
modified driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java +17 −20
@@ -15,24 +15,23 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import java.util.ArrayList;
19-import java.util.Collection;
20-import java.util.Iterator;
21-import java.util.List;
22-
23-import com.google.common.base.Predicate;
24-import com.google.common.base.Predicates;
25-import com.google.common.collect.ImmutableSet;
26-
2718 import com.datastax.driver.core.Cluster;
2819 import com.datastax.driver.core.Host;
2920 import com.datastax.driver.core.HostDistance;
3021 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;
3130
3231 /**
3332 * A load balancing policy wrapper that ensures that only hosts matching the predicate
3433 * will ever be returned.
35- * <p>
34+ * <p/>
3635 * This policy wraps another load balancing policy and will delegate the choice
3736 * of hosts to the wrapped policy with the exception that only hosts matching
3837 * the predicate provided when constructing this policy will ever be
@@ -48,8 +47,8 @@
4847 * matching the predicate.
4948 *
5049 * @param childPolicy the wrapped policy.
51- * @param predicate the host predicate. Only hosts matching this predicate may get connected
52- * 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).
5352 */
5453 public HostFilterPolicy(LoadBalancingPolicy childPolicy, Predicate<Host> predicate) {
5554 this.childPolicy = childPolicy;
@@ -65,7 +64,7 @@
6564 * {@inheritDoc}
6665 *
6766 * @throws IllegalArgumentException if none of the host in {@code hosts}
68- * (which will correspond to the contact points) matches the predicate.
67+ * (which will correspond to the contact points) matches the predicate.
6968 */
7069 @Override
7170 public void init(Cluster cluster, Collection<Host> hosts) {
@@ -89,13 +88,13 @@
8988 @Override
9089 public HostDistance distance(Host host) {
9190 return predicate.apply(host)
92- ? childPolicy.distance(host)
93- : HostDistance.IGNORED;
91+ ? childPolicy.distance(host)
92+ : HostDistance.IGNORED;
9493 }
9594
9695 /**
9796 * {@inheritDoc}
98- * <p>
97+ * <p/>
9998 * It is guaranteed that only hosts matching the predicate will be returned.
10099 */
101100 @Override
@@ -140,8 +139,7 @@
140139 * whose DC belongs to the provided list.
141140 *
142141 * @param childPolicy the wrapped policy.
143- * @param dcs the DCs.
144- *
142+ * @param dcs the DCs.
145143 * @return the policy.
146144 */
147145 public static HostFilterPolicy fromDCWhiteList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) {
@@ -153,8 +151,7 @@
153151 * whose DC belongs to the provided list.
154152 *
155153 * @param childPolicy the wrapped policy.
156- * @param dcs the DCs.
157- *
154+ * @param dcs the DCs.
158155 * @return the policy.
159156 */
160157 public static HostFilterPolicy fromDCBlackList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) {
modified driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java +7 −6
@@ -20,10 +20,10 @@
2020
2121 /**
2222 * A retry policy that avoids retrying non-idempotent statements.
23- * <p>
23+ * <p/>
2424 * In case of write timeouts or unexpected errors, this policy will always return {@link RetryDecision#rethrow()}
2525 * if the statement is deemed non-idempotent (see {@link #isIdempotent(Statement)}).
26- * <p>
26+ * <p/>
2727 * For all other cases, this policy delegates the decision to the child policy.
2828 */
2929 public class IdempotenceAwareRetryPolicy implements RetryPolicy {
@@ -34,6 +34,7 @@
3434
3535 /**
3636 * Creates a new instance.
37+ *
3738 * @param childPolicy the policy to wrap.
3839 */
3940 public IdempotenceAwareRetryPolicy(RetryPolicy childPolicy) {
@@ -47,7 +48,7 @@
4748
4849 @Override
4950 public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
50- if(isIdempotent(statement))
51+ if (isIdempotent(statement))
5152 return childPolicy.onWriteTimeout(statement, cl, writeType, requiredAcks, receivedAcks, nbRetry);
5253 else
5354 return RetryDecision.rethrow();
@@ -60,7 +61,7 @@
6061
6162 @Override
6263 public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
63- if(isIdempotent(statement))
64+ if (isIdempotent(statement))
6465 return childPolicy.onRequestError(statement, cl, e, nbRetry);
6566 else
6667 return RetryDecision.rethrow();
@@ -78,12 +79,12 @@
7879
7980 /**
8081 * Determines whether the given statement is idempotent or not.
81- * <p>
82+ * <p/>
8283 * The current implementation inspects the statement's
8384 * {@link Statement#isIdempotent() idempotent flag};
8485 * if this flag is not set, then it inspects
8586 * {@link QueryOptions#getDefaultIdempotence()}.
86- * <p>
87+ * <p/>
8788 * Subclasses may override if they have better knowledge of
8889 * the statement being executed.
8990 *
modified driver-core/src/main/java/com/datastax/driver/core/policies/IdentityTranslator.java +3 −3
@@ -15,10 +15,10 @@
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 * The default {@link AddressTranslator} used by the driver that do no
2424 * translation.
@@ -32,7 +32,7 @@
3232
3333 /**
3434 * Translates a Cassandra {@code rpc_address} to another address if necessary.
35- * <p>
35+ * <p/>
3636 * This method is the identity function, it always return the address passed
3737 * in argument, doing no translation.
3838 *
modified driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java +52 −56
@@ -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
@@ -374,11 +375,11 @@
374375 * and tend to make the host's score look better than it actually is.
375376 */
376377 private static final Set<Class<? extends DriverException>> EXCLUDED_EXCEPTIONS = ImmutableSet.of(
377- UnavailableException.class, // this is done via the snitch and is usually very fast
378- OverloadedException.class,
379- BootstrappingException.class,
380- UnpreparedException.class,
381- QueryValidationException.class // query validation also happens at early stages in the coordinator
378+ UnavailableException.class, // this is done via the snitch and is usually very fast
379+ OverloadedException.class,
380+ BootstrappingException.class,
381+ UnpreparedException.class,
382+ QueryValidationException.class // query validation also happens at early stages in the coordinator
382383 );
383384
384385 private class Tracker implements LatencyTracker {
@@ -387,7 +388,7 @@
387388 private volatile long cachedMin = -1L;
388389
389390 public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
390- if(shouldConsiderNewLatency(statement, exception)) {
391+ if (shouldConsiderNewLatency(statement, exception)) {
391392 HostLatencyTracker hostTracker = latencies.get(host);
392393 if (hostTracker == null) {
393394 hostTracker = new HostLatencyTracker(scale, (30L * minMeasure) / 100L);
@@ -401,9 +402,9 @@
401402
402403 private boolean shouldConsiderNewLatency(Statement statement, Exception exception) {
403404 // query was successful: always consider
404- if(exception == null) return true;
405+ if (exception == null) return true;
405406 // filter out "fast" errors
406- if(EXCLUDED_EXCEPTIONS.contains(exception.getClass())) return false;
407+ if (EXCLUDED_EXCEPTIONS.contains(exception.getClass())) return false;
407408 return true;
408409 }
409410
@@ -470,7 +471,7 @@
470471 private final AtomicReference<TimestampedAverage> current = new AtomicReference<TimestampedAverage>();
471472
472473 HostLatencyTracker(long scale, long thresholdToAccount) {
473- this.scale = (double)scale; // We keep in double since that's how we'll use it.
474+ this.scale = (double) scale; // We keep in double since that's how we'll use it.
474475 this.thresholdToAccount = thresholdToAccount;
475476 }
476477
@@ -504,11 +505,11 @@
504505 if (delay <= 0)
505506 return null;
506507
507- double scaledDelay = ((double)delay)/scale;
508+ double scaledDelay = ((double) delay) / scale;
508509 // 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
509510 // refuse ridiculously big scales, scaledDelay can't be so low that scaledDelay+1 == 1.0 (due to rounding)).
510- double prevWeight = Math.log(scaledDelay+1) / scaledDelay;
511- long newAverage = (long)((1.0 - prevWeight) * newLatencyNanos + prevWeight * previous.average);
511+ double prevWeight = Math.log(scaledDelay + 1) / scaledDelay;
512+ long newAverage = (long) ((1.0 - prevWeight) * newLatencyNanos + prevWeight * previous.average);
512513
513514 return new TimestampedAverage(currentTimestamp, newAverage, nbMeasure);
514515 }
@@ -520,13 +521,13 @@
520521
521522 /**
522523 * Helper builder object to create a latency aware policy.
523- * <p>
524+ * <p/>
524525 * This helper allows to configure the different parameters used by
525526 * {@code LatencyAwarePolicy}. The only mandatory parameter is the child
526527 * policy that will be wrapped with latency awareness. The other parameters
527528 * can be set through the methods of this builder, but all have defaults (that
528529 * are documented in the javadoc of each method) if you don't.
529- * <p>
530+ * <p/>
530531 * If you observe that the resulting policy excludes hosts too aggressively or
531532 * not enough so, the main parameters to check are the exclusion threshold
532533 * ({@link #withExclusionThreshold}) and scale ({@link #withScale}).
@@ -554,7 +555,7 @@
554555 * that the resulting policy wraps.
555556 *
556557 * @param childPolicy the load balancing policy to wrap with latency
557- * awareness.
558+ * awareness.
558559 */
559560 public Builder(LoadBalancingPolicy childPolicy) {
560561 this.childPolicy = childPolicy;
@@ -562,19 +563,18 @@
562563
563564 /**
564565 * Sets the exclusion threshold to use for the resulting latency aware policy.
565- * <p>
566+ * <p/>
566567 * The exclusion threshold controls how much worse the average latency
567568 * of a node must be compared to the fastest performing node for it to be
568569 * penalized by the policy.
569- * <p>
570+ * <p/>
570571 * The default exclusion threshold (if this method is not called) is <b>2</b>.
571572 * In other words, the resulting policy excludes nodes that are more than
572573 * twice slower than the fastest node.
573574 *
574575 * @param exclusionThreshold the exclusion threshold to use. Must be
575- * greater or equal to 1.
576+ * greater or equal to 1.
576577 * @return this builder.
577- *
578578 * @throws IllegalArgumentException if {@code exclusionThreshold &lt; 1}.
579579 */
580580 public Builder withExclusionThreshold(double exclusionThreshold) {
@@ -586,32 +586,31 @@
586586
587587 /**
588588 * Sets the scale to use for the resulting latency aware policy.
589- * <p>
589+ * <p/>
590590 * The {@code scale} provides control on how the weight given to older latencies
591591 * decreases over time. For a given host, if a new latency \(l\) is received at
592592 * time \(t\), and the previously calculated average is \(prev\) calculated at
593593 * time \(t'\), then the newly calculated average \(avg\) for that host is calculated
594594 * thusly:
595595 * \[
596- * d = \frac{t - t'}{scale} \\
597- * \alpha = 1 - \left(\frac{\ln(d+1)}{d}\right) \\
598- * avg = \alpha * l + (1-\alpha) * prev
596+ * d = \frac{t - t'}{scale} \\
597+ * \alpha = 1 - \left(\frac{\ln(d+1)}{d}\right) \\
598+ * avg = \alpha * l + (1-\alpha) * prev
599599 * \]
600600 * Typically, with a {@code scale} of 100 milliseconds (the default), if a new
601601 * latency is measured and the previous measure is 10 millisecond old (so \(d=0.1\)),
602602 * then \(\alpha\) will be around \(0.05\). In other words, the new latency will
603603 * weight 5% of the updated average. A bigger scale will get less weight to new
604604 * measurements (compared to previous ones), a smaller one will give them more weight.
605- * <p>
605+ * <p/>
606606 * The default scale (if this method is not used) is of <b>100 milliseconds</b>. If unsure, try
607607 * this default scale first and experiment only if it doesn't provide acceptable results
608608 * (hosts are excluded too quickly or not fast enough and tuning the exclusion threshold
609609 * doesn't help).
610610 *
611611 * @param scale the scale to use.
612- * @param unit the unit of {@code scale}.
612+ * @param unit the unit of {@code scale}.
613613 * @return this builder.
614- *
615614 * @throws IllegalArgumentException if {@code scale &lte; 0}.
616615 */
617616 public Builder withScale(long scale, TimeUnit unit) {
@@ -623,7 +622,7 @@
623622
624623 /**
625624 * Sets the retry period for the resulting latency aware policy.
626- * <p>
625+ * <p/>
627626 * The retry period defines how long a node may be penalized by the
628627 * policy before it is given a 2nd change. More precisely, a node is excluded
629628 * from query plans if both his calculated average latency is {@code exclusionThreshold}
@@ -633,9 +632,8 @@
633632 * latency updated, this is basically how long the policy will exclude a node.
634633 *
635634 * @param retryPeriod the retry period to use.
636- * @param unit the unit for {@code retryPeriod}.
635+ * @param unit the unit for {@code retryPeriod}.
637636 * @return this builder.
638- *
639637 * @throws IllegalArgumentException if {@code retryPeriod &lt; 0}.
640638 */
641639 public Builder withRetryPeriod(long retryPeriod, TimeUnit unit) {
@@ -647,14 +645,14 @@
647645
648646 /**
649647 * Sets the update rate for the resulting latency aware policy.
650- *
648+ * <p/>
651649 * The update rate defines how often the minimum average latency is
652650 * recomputed. While the average latency score of each node is computed
653651 * iteratively (updated each time a new latency is collected), the
654652 * minimum score needs to be recomputed from scratch every time, which
655653 * is slightly more costly. For this reason, the minimum is only
656654 * re-calculated at the given fixed rate and cached between re-calculation.
657- * <p>
655+ * <p/>
658656 * The default update rate if <b>100 milliseconds</b>, which should be
659657 * appropriate for most applications. In particular, note that while we
660658 * want to avoid to recompute the minimum for every query, that
@@ -663,9 +661,8 @@
663661 * unnecessarily slow for instance).
664662 *
665663 * @param updateRate the update rate to use.
666- * @param unit the unit for {@code updateRate}.
664+ * @param unit the unit for {@code updateRate}.
667665 * @return this builder.
668- *
669666 * @throws IllegalArgumentException if {@code updateRate &lte; 0}.
670667 */
671668 public Builder withUpdateRate(long updateRate, TimeUnit unit) {
@@ -678,7 +675,7 @@
678675 /**
679676 * Sets the minimum number of measurements per-host to consider for
680677 * the resulting latency aware policy.
681- * <p>
678+ * <p/>
682679 * Penalizing nodes is based on an average of their recently measured
683680 * average latency. This average is only meaningful if a minimum of
684681 * measurements have been collected (moreover, a newly started
@@ -691,10 +688,10 @@
691688 * ignored, while the {@code 70%} next ones are accounted in the latency
692689 * computed but the node won't get convicted until we've had at least
693690 * {@code minMeasure} measurements).
694- * <p>
691+ * <p/>
695692 * Note that the number of collected measurements for a given host is
696693 * reset if the node is restarted.
697- * <p>
694+ * <p/>
698695 * The default for this option (if this method is not called) is <b>50</b>.
699696 * Note that it is probably not a good idea to put this option too low
700697 * if only to avoid the influence of JVM warm-up on newly restarted
@@ -702,7 +699,6 @@
702699 *
703700 * @param minMeasure the minimum measurements to consider.
704701 * @return this builder.
705- *
706702 * @throws IllegalArgumentException if {@code minMeasure &lt; 0}.
707703 */
708704 public Builder withMininumMeasurements(int minMeasure) {
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoadBalancingPolicy.java +20 −20
@@ -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 informed of hosts up/down events. For efficiency
3838 * purposes, the policy is expected to exclude down hosts from query plans.
3939 */
@@ -41,25 +41,25 @@
4141
4242 /**
4343 * Initialize this load balancing policy.
44- * <p>
44+ * <p/>
4545 * Note that the driver guarantees that it will call this method exactly
4646 * once per policy object and will do so before any call to another of the
4747 * methods of the policy.
4848 *
4949 * @param cluster the {@code Cluster} instance for which the policy is created.
50- * @param hosts the initial hosts to use.
50+ * @param hosts the initial hosts to use.
5151 */
5252 public void init(Cluster cluster, Collection<Host> hosts);
5353
5454 /**
5555 * Returns the distance assigned by this policy to the provided host.
56- * <p>
56+ * <p/>
5757 * The distance of an host influence how much connections are kept to the
5858 * node (see {@link HostDistance}). A policy should assign a {@code
5959 * LOCAL} distance to nodes that are susceptible to be returned first by
6060 * {@code newQueryPlan} and it is useless for {@code newQueryPlan} to
6161 * return hosts to which it assigns an {@code IGNORED} distance.
62- * <p>
62+ * <p/>
6363 * The host distance is primarily used to prevent keeping too many
6464 * connections to host in remote datacenters when the policy itself always
6565 * picks host in the local datacenter first.
@@ -71,7 +71,7 @@
7171
7272 /**
7373 * Returns the hosts to use for a new query.
74- * <p>
74+ * <p/>
7575 * Each new query will call this method. The first host in the result will
7676 * then be used to perform the query. In the event of a connection problem
7777 * (the queried host is down or appear to be so), the next host will be
@@ -79,10 +79,10 @@
7979 * will fail.
8080 *
8181 * @param loggedKeyspace the currently logged keyspace (the one set through either
82- * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for
83- * the session on which this plan need to be built. This can be {@code null} if
84- * the corresponding session has no keyspace logged in.
85- * @param statement the query for which to build a plan.
82+ * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for
83+ * the session on which this plan need to be built. This can be {@code null} if
84+ * the corresponding session has no keyspace logged in.
85+ * @param statement the query for which to build a plan.
8686 * @return an iterator of Host. The query is tried against the hosts
8787 * returned by this iterator in order, until the query has been sent
8888 * successfully to one of the host.
@@ -91,7 +91,7 @@
9191
9292 /**
9393 * Called when a new node is added to the cluster.
94- * <p>
94+ * <p/>
9595 * The newly added node should be considered up.
9696 *
9797 * @param host the host that has been newly added.
@@ -121,7 +121,7 @@
121121
122122 /**
123123 * Gets invoked at cluster shutdown.
124- *
124+ * <p/>
125125 * This gives the policy the opportunity to perform some cleanup, for instance stop threads that it might have started.
126126 */
127127 void close();
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java +30 −23
@@ -15,19 +15,18 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import com.google.common.annotations.VisibleForTesting;
19-import org.slf4j.Logger;
20-import org.slf4j.LoggerFactory;
21-
2218 import com.datastax.driver.core.Cluster;
2319 import com.datastax.driver.core.ConsistencyLevel;
2420 import com.datastax.driver.core.Statement;
2521 import com.datastax.driver.core.WriteType;
2622 import com.datastax.driver.core.exceptions.DriverException;
23+import com.google.common.annotations.VisibleForTesting;
24+import org.slf4j.Logger;
25+import org.slf4j.LoggerFactory;
2726
2827 /**
2928 * A retry policy that wraps another policy, logging the decision made by its sub-policy.
30- * <p>
29+ * <p/>
3130 * Note that this policy only log the IGNORE and RETRY decisions (since
3231 * RETHROW decisions are just meant to propagate the cassandra exception). The
3332 * logging is done at the INFO level.
@@ -36,29 +35,37 @@
3635
3736 private static final Logger logger = LoggerFactory.getLogger(LoggingRetryPolicy.class);
3837
39- @VisibleForTesting static final String IGNORING_READ_TIMEOUT =
40- "Ignoring read timeout (initial consistency: {}, required responses: {}, received responses: {}, data retrieved: {}, retries: {})";
38+ @VisibleForTesting
39+ static final String IGNORING_READ_TIMEOUT =
40+ "Ignoring read timeout (initial consistency: {}, required responses: {}, received responses: {}, data retrieved: {}, retries: {})";
4141
42- @VisibleForTesting static final String RETRYING_ON_READ_TIMEOUT =
43- "Retrying on read timeout on {} at consistency {} (initial consistency: {}, required responses: {}, received responses: {}, data retrieved: {}, retries: {})";
42+ @VisibleForTesting
43+ static final String RETRYING_ON_READ_TIMEOUT =
44+ "Retrying on read timeout on {} at consistency {} (initial consistency: {}, required responses: {}, received responses: {}, data retrieved: {}, retries: {})";
4445
45- @VisibleForTesting static final String IGNORING_WRITE_TIMEOUT =
46- "Ignoring write timeout (initial consistency: {}, write type: {}, required acknowledgments: {}, received acknowledgments: {}, retries: {})";
46+ @VisibleForTesting
47+ static final String IGNORING_WRITE_TIMEOUT =
48+ "Ignoring write timeout (initial consistency: {}, write type: {}, required acknowledgments: {}, received acknowledgments: {}, retries: {})";
4749
48- @VisibleForTesting static final String RETRYING_ON_WRITE_TIMEOUT =
49- "Retrying on write timeout on {} at consistency {} (initial consistency: {}, write type: {}, required acknowledgments: {}, received acknowledgments: {}, retries: {})";
50+ @VisibleForTesting
51+ static final String RETRYING_ON_WRITE_TIMEOUT =
52+ "Retrying on write timeout on {} at consistency {} (initial consistency: {}, write type: {}, required acknowledgments: {}, received acknowledgments: {}, retries: {})";
5053
51- @VisibleForTesting static final String IGNORING_UNAVAILABLE =
52- "Ignoring unavailable exception (initial consistency: {}, required replica: {}, alive replica: {}, retries: {})";
54+ @VisibleForTesting
55+ static final String IGNORING_UNAVAILABLE =
56+ "Ignoring unavailable exception (initial consistency: {}, required replica: {}, alive replica: {}, retries: {})";
5357
54- @VisibleForTesting static final String RETRYING_ON_UNAVAILABLE =
55- "Retrying on unavailable exception on {} at consistency {} (initial consistency: {}, required replica: {}, alive replica: {}, retries: {})";
58+ @VisibleForTesting
59+ static final String RETRYING_ON_UNAVAILABLE =
60+ "Retrying on unavailable exception on {} at consistency {} (initial consistency: {}, required replica: {}, alive replica: {}, retries: {})";
5661
57- @VisibleForTesting static final String IGNORING_REQUEST_ERROR =
58- "Ignoring request error (initial consistency: {}, retries: {}, exception: {})";
62+ @VisibleForTesting
63+ static final String IGNORING_REQUEST_ERROR =
64+ "Ignoring request error (initial consistency: {}, retries: {}, exception: {})";
5965
60- @VisibleForTesting static final String RETRYING_ON_REQUEST_ERROR =
61- "Retrying on request error on {} at consistency {} (initial consistency: {}, retries: {}, exception: {})";
66+ @VisibleForTesting
67+ static final String RETRYING_ON_REQUEST_ERROR =
68+ "Retrying on request error on {} at consistency {} (initial consistency: {}, retries: {}, exception: {})";
6269
6370 private final RetryPolicy policy;
6471
@@ -66,7 +73,7 @@
6673 * Creates a new {@code RetryPolicy} that logs the decision of {@code policy}.
6774 *
6875 * @param policy the policy to wrap. The policy created by this constructor
69- * will return the same decision than {@code policy} but will log them.
76+ * will return the same decision than {@code policy} but will log them.
7077 */
7178 public LoggingRetryPolicy(RetryPolicy policy) {
7279 this.policy = policy;
@@ -150,7 +157,7 @@
150157 * Logs the decision according to the given template and parameters.
151158 * The log level is INFO, but subclasses may override.
152159 *
153- * @param template The template to use; arguments must be specified in SLF4J style, i.e. {@code "{}"}.
160+ * @param template The template to use; arguments must be specified in SLF4J style, i.e. {@code "{}"}.
154161 * @param parameters The template parameters.
155162 */
156163 protected void logDecision(String template, Object... parameters) {
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 +23 −24
@@ -15,11 +15,10 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import com.google.common.base.Objects;
19-
2018 import com.datastax.driver.core.AtomicMonotonicTimestampGenerator;
2119 import com.datastax.driver.core.ServerSideTimestampGenerator;
2220 import com.datastax.driver.core.TimestampGenerator;
21+import com.google.common.base.Objects;
2322
2423 /**
2524 * Policies configured for a {@link com.datastax.driver.core.Cluster} instance.
@@ -48,11 +47,11 @@
4847 private final SpeculativeExecutionPolicy speculativeExecutionPolicy;
4948
5049 private Policies(LoadBalancingPolicy loadBalancingPolicy,
51- ReconnectionPolicy reconnectionPolicy,
52- RetryPolicy retryPolicy,
53- AddressTranslator addressTranslator,
54- TimestampGenerator timestampGenerator,
55- SpeculativeExecutionPolicy speculativeExecutionPolicy) {
50+ ReconnectionPolicy reconnectionPolicy,
51+ RetryPolicy retryPolicy,
52+ AddressTranslator addressTranslator,
53+ TimestampGenerator timestampGenerator,
54+ SpeculativeExecutionPolicy speculativeExecutionPolicy) {
5655 this.loadBalancingPolicy = loadBalancingPolicy;
5756 this.reconnectionPolicy = reconnectionPolicy;
5857 this.retryPolicy = retryPolicy;
@@ -63,10 +62,10 @@
6362
6463 /**
6564 * The default load balancing policy.
66- * <p>
65+ * <p/>
6766 * The default load balancing policy is {@link DCAwareRoundRobinPolicy} with token
6867 * awareness (so {@code new TokenAwarePolicy(new DCAwareRoundRobinPolicy())}).
69- * <p>
68+ * <p/>
7069 * Note that this policy shuffles the replicas when token awareness is used, see
7170 * {@link TokenAwarePolicy#TokenAwarePolicy(LoadBalancingPolicy, boolean)} for an
7271 * explanation of the tradeoffs.
@@ -81,7 +80,7 @@
8180
8281 /**
8382 * The default reconnection policy.
84- * <p>
83+ * <p/>
8584 * The default reconnection policy is an {@link ExponentialReconnectionPolicy}
8685 * where the base delay is 1 second and the max delay is 10 minutes;
8786 *
@@ -93,7 +92,7 @@
9392
9493 /**
9594 * The default retry policy.
96- * <p>
95+ * <p/>
9796 * The default retry policy is {@link DefaultRetryPolicy}.
9897 *
9998 * @return the default retry policy.
@@ -104,7 +103,7 @@
104103
105104 /**
106105 * The default address translator.
107- * <p>
106+ * <p/>
108107 * The default address translator is {@link IdentityTranslator}.
109108 *
110109 * @return the default address translator.
@@ -115,7 +114,7 @@
115114
116115 /**
117116 * The default timestamp generator.
118- * <p>
117+ * <p/>
119118 * This is an instance of {@link ServerSideTimestampGenerator}.
120119 *
121120 * @return the default timestamp generator.
@@ -126,7 +125,7 @@
126125
127126 /**
128127 * The default speculative retry policy.
129- * <p>
128+ * <p/>
130129 * The default speculative retry policy is a {@link NoSpeculativeExecutionPolicy}.
131130 *
132131 * @return the default speculative retry policy.
@@ -137,7 +136,7 @@
137136
138137 /**
139138 * The load balancing policy in use.
140- * <p>
139+ * <p/>
141140 * The load balancing policy defines how Cassandra hosts are picked for queries.
142141 *
143142 * @return the load balancing policy in use.
@@ -148,7 +147,7 @@
148147
149148 /**
150149 * The reconnection policy in use.
151- * <p>
150+ * <p/>
152151 * The reconnection policy defines how often the driver tries to reconnect to a dead node.
153152 *
154153 * @return the reconnection policy in use.
@@ -159,7 +158,7 @@
159158
160159 /**
161160 * The retry policy in use.
162- * <p>
161+ * <p/>
163162 * The retry policy defines in which conditions a query should be
164163 * automatically retries by the driver.
165164 *
@@ -275,19 +274,19 @@
275274
276275 /**
277276 * Builds the final object from this builder.
278- * <p>
277+ * <p/>
279278 * Any field that hasn't been set explicitly will get its default value.
280279 *
281280 * @return the object.
282281 */
283282 public Policies build() {
284283 return new Policies(
285- loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy,
286- Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()),
287- Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()),
288- Objects.firstNonNull(addressTranslator, Policies.defaultAddressTranslator()),
289- Objects.firstNonNull(timestampGenerator, Policies.defaultTimestampGenerator()),
290- Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy()));
284+ loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy,
285+ Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()),
286+ Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()),
287+ Objects.firstNonNull(addressTranslator, Policies.defaultAddressTranslator()),
288+ Objects.firstNonNull(timestampGenerator, Policies.defaultTimestampGenerator()),
289+ Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy()));
291290 }
292291 }
293292 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/ReconnectionPolicy.java +5 −5
@@ -19,18 +19,18 @@
1919
2020 /**
2121 * Policy that decides how often the reconnection to a dead node is attempted.
22- *
22+ * <p/>
2323 * Each time a node is detected dead (because a connection error occurs), a new
2424 * {@code ReconnectionSchedule} instance is created (through the {@link #newSchedule()}).
2525 * Then each call to the {@link ReconnectionSchedule#nextDelayMs} method of
2626 * this instance will decide when the next reconnection attempt to this node
2727 * will be tried.
28- *
28+ * <p/>
2929 * Note that if the driver receives a push notification from the Cassandra cluster
3030 * that a node is UP, any existing {@code ReconnectionSchedule} on that node
3131 * will be cancelled and a new one will be created (in effect, the driver reset
3232 * the scheduler).
33- *
33+ * <p/>
3434 * The default {@link ExponentialReconnectionPolicy} policy is usually
3535 * adequate.
3636 */
@@ -50,7 +50,7 @@
5050
5151 /**
5252 * When to attempt the next reconnection.
53- *
53+ * <p/>
5454 * This method will be called once when the host is detected down to
5555 * schedule the first reconnection attempt, and then once after each failed
5656 * reconnection attempt to schedule the next one. Hence each call to this
@@ -71,7 +71,7 @@
7171
7272 /**
7373 * Gets invoked at cluster shutdown.
74- *
74+ * <p/>
7575 * This gives the policy the opportunity to perform some cleanup, for instance stop threads that it might have started.
7676 */
7777 void close();
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +50 −45
@@ -20,7 +20,7 @@
2020
2121 /**
2222 * A policy that defines a default behavior to adopt when a request fails.
23- *
23+ * <p/>
2424 * Such policy allows to centralize the handling of query retries, allowing to
2525 * minimize the need for exception catching/handling in business code.
2626 */
@@ -29,28 +29,30 @@
2929 /**
3030 * A retry decision to adopt on a Cassandra exception (read/write timeout
3131 * or unavailable exception).
32- * <p>
32+ * <p/>
3333 * There are three possible decisions:
3434 * <ul>
35- * <li>RETHROW: no retry should be attempted and an exception should be thrown.</li>
36- * <li>RETRY: the operation will be retried. The consistency level of the
37- * retry should be specified.</li>
38- * <li>IGNORE: no retry should be attempted and the exception should be
39- * ignored. In that case, the operation that triggered the Cassandra
40- * exception will return an empty result set.</li>
35+ * <li>RETHROW: no retry should be attempted and an exception should be thrown.</li>
36+ * <li>RETRY: the operation will be retried. The consistency level of the
37+ * retry should be specified.</li>
38+ * <li>IGNORE: no retry should be attempted and the exception should be
39+ * ignored. In that case, the operation that triggered the Cassandra
40+ * exception will return an empty result set.</li>
4141 * </ul>
4242 */
4343 class RetryDecision {
4444 /**
4545 * The types of retry decisions.
4646 */
47- public enum Type { RETRY, RETHROW, IGNORE }
47+ public enum Type {
48+ RETRY, RETHROW, IGNORE
49+ }
4850
4951 private final Type type;
5052 private final ConsistencyLevel retryCL;
5153 private final boolean retryCurrent;
5254
53- private RetryDecision(Type type, ConsistencyLevel retryCL, boolean retryCurrent){
55+ private RetryDecision(Type type, ConsistencyLevel retryCL, boolean retryCurrent) {
5456 this.type = type;
5557 this.retryCL = retryCL;
5658 this.retryCurrent = retryCurrent;
@@ -135,9 +137,12 @@
135137 @Override
136138 public String toString() {
137139 switch (type) {
138- case RETRY: return "Retry at " + retryCL + " on " + (retryCurrent ? "same " : "next ") + "host.";
139- case RETHROW: return "Rethrow";
140- case IGNORE: return "Ignore";
140+ case RETRY:
141+ return "Retry at " + retryCL + " on " + (retryCurrent ? "same " : "next ") + "host.";
142+ case RETHROW:
143+ return "Rethrow";
144+ case IGNORE:
145+ return "Ignore";
141146 }
142147 throw new AssertionError();
143148 }
@@ -145,21 +150,21 @@
145150
146151 /**
147152 * Defines whether to retry and at which consistency level on a read timeout.
148- * <p>
153+ * <p/>
149154 * Note that this method may be called even if
150155 * {@code requiredResponses >= receivedResponses} if {@code dataPresent} is
151156 * {@code false} (see
152157 * {@link com.datastax.driver.core.exceptions.ReadTimeoutException#wasDataRetrieved}).
153158 *
154- * @param statement the original query that timed out.
155- * @param cl the original consistency level of the read that timed out.
159+ * @param statement the original query that timed out.
160+ * @param cl the original consistency level of the read that timed out.
156161 * @param requiredResponses the number of responses that were required to
157- * achieve the requested consistency level.
162+ * achieve the requested consistency level.
158163 * @param receivedResponses the number of responses that had been received
159- * by the time the timeout exception was raised.
160- * @param dataRetrieved whether actual data (by opposition to data checksum)
161- * was present in the received responses.
162- * @param nbRetry the number of retry already performed for this operation.
164+ * by the time the timeout exception was raised.
165+ * @param dataRetrieved whether actual data (by opposition to data checksum)
166+ * was present in the received responses.
167+ * @param nbRetry the number of retry already performed for this operation.
163168 * @return the retry decision. If {@code RetryDecision.RETHROW} is returned,
164169 * a {@link com.datastax.driver.core.exceptions.ReadTimeoutException} will
165170 * be thrown for the operation.
@@ -169,14 +174,14 @@
169174 /**
170175 * Defines whether to retry and at which consistency level on a write timeout.
171176 *
172- * @param statement the original query that timed out.
173- * @param cl the original consistency level of the write that timed out.
174- * @param writeType the type of the write that timed out.
177+ * @param statement the original query that timed out.
178+ * @param cl the original consistency level of the write that timed out.
179+ * @param writeType the type of the write that timed out.
175180 * @param requiredAcks the number of acknowledgments that were required to
176- * achieve the requested consistency level.
181+ * achieve the requested consistency level.
177182 * @param receivedAcks the number of acknowledgments that had been received
178- * by the time the timeout exception was raised.
179- * @param nbRetry the number of retry already performed for this operation.
183+ * by the time the timeout exception was raised.
184+ * @param nbRetry the number of retry already performed for this operation.
180185 * @return the retry decision. If {@code RetryDecision.RETHROW} is returned,
181186 * a {@link com.datastax.driver.core.exceptions.WriteTimeoutException} will
182187 * be thrown for the operation.
@@ -187,14 +192,14 @@
187192 * Defines whether to retry and at which consistency level on an
188193 * unavailable exception.
189194 *
190- * @param statement the original query for which the consistency level cannot
191- * be achieved.
192- * @param cl the original consistency level for the operation.
195+ * @param statement the original query for which the consistency level cannot
196+ * be achieved.
197+ * @param cl the original consistency level for the operation.
193198 * @param requiredReplica the number of replica that should have been
194- * (known) alive for the operation to be attempted.
195- * @param aliveReplica the number of replica that were know to be alive by
196- * the coordinator of the operation.
197- * @param nbRetry the number of retry already performed for this operation.
199+ * (known) alive for the operation to be attempted.
200+ * @param aliveReplica the number of replica that were know to be alive by
201+ * the coordinator of the operation.
202+ * @param nbRetry the number of retry already performed for this operation.
198203 * @return the retry decision. If {@code RetryDecision.RETHROW} is returned,
199204 * an {@link com.datastax.driver.core.exceptions.UnavailableException} will
200205 * be thrown for the operation.
@@ -204,24 +209,24 @@
204209 /**
205210 * Defines whether to retry and at which consistency level on an
206211 * unexpected error.
207- * <p>
212+ * <p/>
208213 * This method might be invoked in the following situations:
209214 * <ol>
210- * <li>On a client timeout, while waiting for the server response
211- * (see {@link SocketOptions#getReadTimeoutMillis()});</li>
212- * <li>On a connection error (socket closed, etc.);</li>
213- * <li>When the contacted host replies with an error, such as
214- * {@code OVERLOADED}, {@code IS_BOOTSTRAPPING}, {@code SERVER_ERROR}, etc.</li>
215+ * <li>On a client timeout, while waiting for the server response
216+ * (see {@link SocketOptions#getReadTimeoutMillis()});</li>
217+ * <li>On a connection error (socket closed, etc.);</li>
218+ * <li>When the contacted host replies with an error, such as
219+ * {@code OVERLOADED}, {@code IS_BOOTSTRAPPING}, {@code SERVER_ERROR}, etc.</li>
215220 * </ol>
216- *
221+ * <p/>
217222 * Note that when this method is invoked, <em>the driver cannot guarantee that the mutation has
218223 * been effectively applied server-side</em>; a retry should only be attempted if the request
219224 * is known to be idempotent.
220225 *
221226 * @param statement the original query that failed.
222- * @param cl the original consistency level for the operation.
223- * @param e the exception that caused this request to fail.
224- * @param nbRetry the number of retries already performed for this operation.
227+ * @param cl the original consistency level for the operation.
228+ * @param e the exception that caused this request to fail.
229+ * @param nbRetry the number of retries already performed for this operation.
225230 * @return the retry decision. If {@code RetryDecision.RETHROW} is returned,
226231 * the {@link DriverException} passed to this method will be thrown for the operation.
227232 */
@@ -236,7 +241,7 @@
236241
237242 /**
238243 * Gets invoked at cluster shutdown.
239- *
244+ * <p/>
240245 * This gives the policy the opportunity to perform some cleanup, for instance stop threads that it might have started.
241246 */
242247 void close();
modified driver-core/src/main/java/com/datastax/driver/core/policies/RoundRobinPolicy.java +18 −23
@@ -15,6 +15,11 @@
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;
@@ -22,24 +27,13 @@
2227 import java.util.concurrent.CopyOnWriteArrayList;
2328 import java.util.concurrent.atomic.AtomicInteger;
2429
25-import com.google.common.collect.AbstractIterator;
26-import org.slf4j.Logger;
27-import org.slf4j.LoggerFactory;
28-
29-import com.datastax.driver.core.Cluster;
30-import com.datastax.driver.core.Configuration;
31-import com.datastax.driver.core.ConsistencyLevel;
32-import com.datastax.driver.core.Host;
33-import com.datastax.driver.core.HostDistance;
34-import com.datastax.driver.core.Statement;
35-
3630 /**
3731 * A Round-robin load balancing policy.
38- * <p>
32+ * <p/>
3933 * This policy queries nodes in a round-robin fashion. For a given query,
4034 * if an host fail, the next one (following the round-robin order) is
4135 * tried, until all hosts have been tried.
42- * <p>
36+ * <p/>
4337 * This policy is not datacenter aware and will include every known
4438 * Cassandra host in its round robin algorithm. If you use multiple
4539 * datacenter this will be inefficient and you will want to use the
@@ -59,7 +53,8 @@
5953 * Creates a load balancing policy that picks host to query in a round robin
6054 * fashion (on all the hosts of the Cassandra cluster).
6155 */
62- public RoundRobinPolicy() {}
56+ public RoundRobinPolicy() {
57+ }
6358
6459 @Override
6560 public void init(Cluster cluster, Collection<Host> hosts) {
@@ -70,7 +65,7 @@
7065
7166 /**
7267 * Return the HostDistance for the provided host.
73- * <p>
68+ * <p/>
7469 * This policy consider all nodes as local. This is generally the right
7570 * thing to do in a single datacenter deployment. If you use multiple
7671 * datacenter, see {@link DCAwareRoundRobinPolicy} instead.
@@ -85,14 +80,14 @@
8580
8681 /**
8782 * Returns the hosts to use for a new query.
88- * <p>
83+ * <p/>
8984 * The returned plan will try each known host of the cluster. Upon each
9085 * call to this method, the {@code i}th host of the plans returned will cycle
9186 * over all the hosts of the cluster in a round-robin fashion.
9287 *
9388 * @param loggedKeyspace the keyspace currently logged in on for this
94- * query.
95- * @param statement the query for which to build the plan.
89+ * query.
90+ * @param statement the query for which to build the plan.
9691 * @return a new query plan, i.e. an iterator indicating which host to
9792 * try first for querying, which one to use as failover, etc...
9893 */
@@ -101,13 +96,13 @@
10196
10297 if (!hasLoggedLocalCLUse) {
10398 ConsistencyLevel cl = statement.getConsistencyLevel() == null
104- ? configuration.getQueryOptions().getConsistencyLevel()
105- : statement.getConsistencyLevel();
99+ ? configuration.getQueryOptions().getConsistencyLevel()
100+ : statement.getConsistencyLevel();
106101 if (cl.isDCLocal()) {
107102 hasLoggedLocalCLUse = true;
108103 logger.warn("Detected request at Consistency Level {} but the non-DC aware RoundRobinPolicy is in use. "
109- + "It is strongly advised to use DCAwareRoundRobinPolicy if you have multiple DCs/use DC-aware consistency levels "
110- + "(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());
111106 }
112107 }
113108
@@ -116,7 +111,7 @@
116111 // would be racy). We use clone() as it don't involve a copy of the
117112 // underlying array (and thus we rely on liveHosts being a CopyOnWriteArrayList).
118113 @SuppressWarnings("unchecked")
119- final List<Host> hosts = (List<Host>)liveHosts.clone();
114+ final List<Host> hosts = (List<Host>) liveHosts.clone();
120115 final int startIdx = index.getAndIncrement();
121116
122117 // 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 +17 −21
@@ -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
@@ -57,7 +55,7 @@
5755 /**
5856 * Creates a new {@code TokenAware} policy.
5957 *
60- * @param childPolicy the load balancing policy to wrap with token awareness.
58+ * @param childPolicy the load balancing policy to wrap with token awareness.
6159 * @param shuffleReplicas whether to shuffle the replicas returned by {@code getRoutingKey}.
6260 * Note that setting this parameter to {@code true} might decrease the
6361 * effectiveness of caching (especially at consistency level ONE), since
@@ -65,7 +63,6 @@
6563 * "primary" replica without shuffling).
6664 * On the other hand, shuffling will better distribute writes, and can
6765 * alleviate hotspots caused by "fat" partitions.
68- *
6966 */
7067 public TokenAwarePolicy(LoadBalancingPolicy childPolicy, boolean shuffleReplicas) {
7168 this.childPolicy = childPolicy;
@@ -76,8 +73,7 @@
7673 * Creates a new {@code TokenAware} policy with shuffling of replicas.
7774 *
7875 * @param childPolicy the load balancing policy to wrap with token
79- * awareness.
80- *
76+ * awareness.
8177 * @see #TokenAwarePolicy(LoadBalancingPolicy, boolean)
8278 */
8379 public TokenAwarePolicy(LoadBalancingPolicy childPolicy) {
@@ -110,7 +106,7 @@
110106
111107 /**
112108 * Returns the hosts to use for a new query.
113- * <p>
109+ * <p/>
114110 * The returned plan will first return replicas (whose {@code HostDistance}
115111 * for the child policy is {@code LOCAL}) for the query if it can determine
116112 * them (i.e. mainly if {@code statement.getRoutingKey()} is not {@code null}).
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 +4 −4
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.List;
19-
2018 import com.datastax.driver.core.CodecRegistry;
2119
20+import java.util.List;
21+
2222 import static com.datastax.driver.core.querybuilder.Utils.appendName;
2323 import static com.datastax.driver.core.querybuilder.Utils.appendValue;
2424
@@ -75,8 +75,8 @@
7575
7676 CounterAssignment(String name, Object value, boolean isIncr) {
7777 super(name);
78- if (!isIncr && value instanceof Long && ((Long)value) < 0) {
79- this.value = -((Long)value);
78+ if (!isIncr && value instanceof Long && ((Long) value) < 0) {
79+ this.value = -((Long) value);
8080 this.isIncr = true;
8181 } else {
8282 this.value = value;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +17 −19
@@ -15,12 +15,15 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.CodecRegistry;
19+import com.datastax.driver.core.ProtocolVersion;
20+import com.datastax.driver.core.RegularStatement;
21+import com.datastax.driver.core.SimpleStatement;
22+
1823 import java.nio.ByteBuffer;
1924 import java.util.ArrayList;
2025 import java.util.List;
2126
22-import com.datastax.driver.core.*;
23-
2427 /**
2528 * A built BATCH statement.
2629 */
@@ -34,10 +37,10 @@
3437 private int nonBuiltStatementValues;
3538
3639 Batch(RegularStatement[] statements, boolean logged) {
37- super((String)null);
40+ super((String) null);
3841 this.statements = statements.length == 0
39- ? new ArrayList<RegularStatement>()
40- : new ArrayList<RegularStatement>(statements.length);
42+ ? new ArrayList<RegularStatement>()
43+ : new ArrayList<RegularStatement>(statements.length);
4144 this.logged = logged;
4245 this.usings = new Options(this);
4346
@@ -50,8 +53,8 @@
5053 StringBuilder builder = new StringBuilder();
5154
5255 builder.append(isCounterOp()
53- ? "BEGIN COUNTER BATCH"
54- : (logged ? "BEGIN BATCH" : "BEGIN UNLOGGED BATCH"));
56+ ? "BEGIN COUNTER BATCH"
57+ : (logged ? "BEGIN BATCH" : "BEGIN UNLOGGED BATCH"));
5558
5659 if (!usings.usings.isEmpty()) {
5760 builder.append(" USING ");
@@ -62,7 +65,7 @@
6265 for (int i = 0; i < statements.size(); i++) {
6366 RegularStatement stmt = statements.get(i);
6467 if (stmt instanceof BuiltStatement) {
65- BuiltStatement bst = (BuiltStatement)stmt;
68+ BuiltStatement bst = (BuiltStatement) stmt;
6669 builder.append(maybeAddSemicolon(bst.buildQueryString(variables, codecRegistry)));
6770
6871 } else {
@@ -85,9 +88,8 @@
8588 *
8689 * @param statement the new statement to add.
8790 * @return this batch.
88- *
8991 * @throws IllegalArgumentException if counter and non-counter operations
90- * are mixed.
92+ * are mixed.
9193 */
9294 public Batch add(RegularStatement statement) {
9395 boolean isCounterOp = statement instanceof BuiltStatement && ((BuiltStatement) statement).isCounterOp();
@@ -99,16 +101,13 @@
99101
100102 this.statements.add(statement);
101103
102- if (statement instanceof BuiltStatement)
103- {
104- this.hasBindMarkers |= ((BuiltStatement)statement).hasBindMarkers;
105- }
106- else
107- {
104+ if (statement instanceof BuiltStatement) {
105+ this.hasBindMarkers |= ((BuiltStatement) statement).hasBindMarkers;
106+ } else {
108107 // For non-BuiltStatement, we cannot know if it includes a bind makers and we assume it does. In practice,
109108 // this means we will always serialize values as strings when there is non-BuiltStatement
110109 this.hasBindMarkers = true;
111- this.nonBuiltStatementValues += ((SimpleStatement)statement).valuesCount();
110+ this.nonBuiltStatementValues += ((SimpleStatement) statement).valuesCount();
112111 }
113112
114113 checkForBindMarkers(null);
@@ -128,8 +127,7 @@
128127
129128 ByteBuffer[] values = new ByteBuffer[nonBuiltStatementValues];
130129 int i = 0;
131- for (RegularStatement statement : statements)
132- {
130+ for (RegularStatement statement : statements) {
133131 if (statement instanceof BuiltStatement)
134132 continue;
135133
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 +25 −27
@@ -15,24 +15,24 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.CodecNotFoundException;
20+import com.datastax.driver.core.policies.RetryPolicy;
21+
1822 import java.nio.ByteBuffer;
1923 import java.util.ArrayList;
2024 import java.util.Arrays;
2125 import java.util.List;
2226 import java.util.regex.Pattern;
2327
24-import com.datastax.driver.core.*;
25-import com.datastax.driver.core.exceptions.CodecNotFoundException;
26-import com.datastax.driver.core.policies.RetryPolicy;
27-
2828 /**
2929 * Common ancestor to statements generated with the {@link QueryBuilder}.
30- * <p>
30+ * <p/>
3131 * The actual query string will be generated and cached the first time it is requested,
3232 * which is either when the driver tries to execute the query, or when you call certain
3333 * public methods (for example {@link RegularStatement#getQueryString(CodecRegistry)},
3434 * {@link #getObject(int, CodecRegistry)}).
35- * <p>
35+ * <p/>
3636 * Whenever possible (and unless you call {@link #setForceNoValues(boolean)}, the builder
3737 * will try to handle values passed to its methods as standalone values bound to the query
3838 * string with placeholders. For instance:
@@ -43,12 +43,12 @@
4343 * </pre>
4444 * There are a few exceptions to this rule:
4545 * <ul>
46- * <li>for fixed-size number types, the builder can't guess what the actual CQL type
47- * is. Standalone values are sent to Cassandra in their serialized form, and number
48- * types aren't all serialized in the same way, so picking the wrong type could
49- * lead to a query error;</li>
50- * <li>if the value is a "special" element like a function call, it can't be serialized.
51- * This also applies to collections mixing special elements and regular objects.</li>
46+ * <li>for fixed-size number types, the builder can't guess what the actual CQL type
47+ * is. Standalone values are sent to Cassandra in their serialized form, and number
48+ * types aren't all serialized in the same way, so picking the wrong type could
49+ * lead to a query error;</li>
50+ * <li>if the value is a "special" element like a function call, it can't be serialized.
51+ * This also applies to collections mixing special elements and regular objects.</li>
5252 * </ul>
5353 * In these cases, the builder will inline the value in the query string:
5454 * <pre>
@@ -120,16 +120,14 @@
120120 /**
121121 * Returns the {@code i}th value as the Java type matching its CQL type.
122122 *
123- * @param i the index to retrieve.
123+ * @param i the index to retrieve.
124124 * @param codecRegistry the codec registry that will be used if the statement must be
125125 * rebuilt in order to determine if it has values, and Java objects
126126 * must be inlined in the process (see {@link BuiltStatement} for
127127 * more explanations on why this is so).
128128 * @return the value of the {@code i}th value of this statement.
129- *
130- * @throws IllegalStateException if this statement does not have values.
129+ * @throws IllegalStateException if this statement does not have values.
131130 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
132- *
133131 * @see #getObject(int)
134132 */
135133 public Object getObject(int i, CodecRegistry codecRegistry) {
@@ -140,9 +138,10 @@
140138 throw new ArrayIndexOutOfBoundsException(i);
141139 return values.get(i);
142140 }
141+
143142 /**
144143 * Returns the {@code i}th value as the Java type matching its CQL type.
145- * <p>
144+ * <p/>
146145 * This method calls {@link #getObject(int, CodecRegistry)} with
147146 * {@link CodecRegistry#DEFAULT_INSTANCE}.
148147 * It's safe to use if you don't use any custom codecs, or if your custom codecs are in
@@ -151,8 +150,7 @@
151150 *
152151 * @param i the index to retrieve.
153152 * @return the value of the {@code i}th value of this statement.
154- *
155- * @throws IllegalStateException if this statement does not have values.
153+ * @throws IllegalStateException if this statement does not have values.
156154 * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
157155 */
158156 public Object getObject(int i) {
@@ -174,7 +172,7 @@
174172
175173 if (values.size() > 65535)
176174 throw new IllegalArgumentException("Too many values for built statement, the maximum allowed is 65535");
177-
175+
178176 if (values.isEmpty())
179177 values = null;
180178 }
@@ -249,14 +247,14 @@
249247 ByteBuffer[] routingKeyParts = new ByteBuffer[partitionKey.size()];
250248 for (int i = 0; i < partitionKey.size(); i++) {
251249 Object value = routingKeyValues.get(i);
252- if(value == null)
250+ if (value == null)
253251 return null;
254252 TypeCodec<Object> codec = codecRegistry.codecFor(partitionKey.get(i).getType(), value);
255253 routingKeyParts[i] = codec.serialize(value, protocolVersion);
256254 }
257255 return routingKeyParts.length == 1
258- ? routingKeyParts[0]
259- : Utils.compose(routingKeyParts);
256+ ? routingKeyParts[0]
257+ : Utils.compose(routingKeyParts);
260258 }
261259
262260 @Override
@@ -302,7 +300,7 @@
302300
303301 /**
304302 * Allows to force this builder to not generate values (through its {@code getValues()} method).
305- * <p>
303+ * <p/>
306304 * By default (and unless the protocol version 1 is in use, see below) and
307305 * for performance reasons, the query builder will not serialize all values
308306 * provided to strings. This means that {@link #getQueryString(CodecRegistry)}
@@ -315,13 +313,13 @@
315313 * return {@code null} and that the string returned by {@code
316314 * getQueryString()} will contain no other bind markers than the ones
317315 * specified by the user.
318- * <p>
316+ * <p/>
319317 * If the native protocol version 1 is in use, the driver will default
320318 * to not generating values since those are not supported by that version of
321319 * the protocol. In practice, the driver will automatically call this method
322320 * with {@code true} as argument prior to execution. Hence, calling this
323321 * method when the protocol version 1 is in use is basically a no-op.
324- * <p>
322+ * <p/>
325323 * Note that this method is mainly useful for debugging purpose. In general,
326324 * the default behavior should be the correct and most efficient one.
327325 *
@@ -342,7 +340,7 @@
342340 T statement;
343341
344342 ForwardingStatement(T statement) {
345- super((String)null);
343+ super((String) null);
346344 this.statement = statement;
347345 }
348346
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +3 −2
@@ -15,13 +15,14 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.List;
19-
2018 import com.datastax.driver.core.CodecRegistry;
2119
20+import java.util.List;
21+
2222 public abstract class Clause extends Utils.Appendeable {
2323
2424 abstract String name();
25+
2526 abstract Object firstValue();
2627
2728 private static abstract class AbstractClause extends Clause {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +15 −17
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.ArrayList;
19-import java.util.List;
20-
2118 import com.datastax.driver.core.CodecRegistry;
2219 import com.datastax.driver.core.TableMetadata;
2320
21+import java.util.ArrayList;
22+import java.util.List;
23+
2424 /**
2525 * A built DELETE statement.
2626 */
@@ -87,7 +87,7 @@
8787
8888 /**
8989 * Adds a WHERE clause to this statement.
90- *
90+ * <p/>
9191 * This is a shorter/more readable version for {@code where().and(clause)}.
9292 *
9393 * @param clause the clause to add.
@@ -108,7 +108,7 @@
108108
109109 /**
110110 * Adds a conditions clause (IF) to this statement.
111- * <p>
111+ * <p/>
112112 * This is a shorter/more readable version for {@code onlyIf().and(condition)}.
113113 *
114114 * @param condition the condition to add.
@@ -150,7 +150,7 @@
150150
151151 /**
152152 * Sets the 'IF EXISTS' option for this DELETE statement.
153- *
153+ * <p/>
154154 * <p>
155155 * A delete with that option will report whether the statement actually
156156 * resulted in data being deleted. The existence check and deletion are
@@ -186,8 +186,7 @@
186186 * @param clause the clause to add.
187187 * @return this WHERE clause.
188188 */
189- public Where and(Clause clause)
190- {
189+ public Where and(Clause clause) {
191190 clauses.add(clause);
192191 statement.maybeAddRoutingKey(clause.name(), clause.firstValue());
193192 checkForBindMarkers(clause);
@@ -207,7 +206,7 @@
207206 /**
208207 * Sets the 'IF EXISTS' option for the DELETE statement this WHERE clause
209208 * is part of.
210- *
209+ * <p/>
211210 * <p>
212211 * A delete with that option will report whether the statement actually
213212 * resulted in data being deleted. The existence check and deletion are
@@ -300,7 +299,7 @@
300299 * Adds the table to delete from.
301300 *
302301 * @param keyspace the name of the keyspace to delete from.
303- * @param table the name of the table to delete from.
302+ * @param table the name of the table to delete from.
304303 * @return a newly built DELETE statement that deletes from {@code keyspace.table}.
305304 */
306305 public Delete from(String keyspace, String table) {
@@ -327,7 +326,6 @@
327326 * Deletes all columns (i.e. "DELETE FROM ...")
328327 *
329328 * @return an in-build DELETE statement.
330- *
331329 * @throws IllegalStateException if some columns had already been selected for this builder.
332330 */
333331 public Builder all() {
@@ -352,7 +350,7 @@
352350 * Deletes the provided list element.
353351 *
354352 * @param columnName the name of the list column.
355- * @param idx the index of the element to delete.
353+ * @param idx the index of the element to delete.
356354 * @return this in-build DELETE Selection
357355 */
358356 public Selection listElt(String columnName, int idx) {
@@ -365,7 +363,7 @@
365363 * specified as a bind marker.
366364 *
367365 * @param columnName the name of the list column.
368- * @param idx the index of the element to delete.
366+ * @param idx the index of the element to delete.
369367 * @return this in-build DELETE Selection
370368 */
371369 public Selection listElt(String columnName, BindMarker idx) {
@@ -377,7 +375,7 @@
377375 * Deletes the provided set element.
378376 *
379377 * @param columnName the name of the set column.
380- * @param element the element to delete.
378+ * @param element the element to delete.
381379 * @return this in-build DELETE Selection
382380 */
383381 public Selection setElt(String columnName, Object element) {
@@ -390,7 +388,7 @@
390388 * specified as a bind marker.
391389 *
392390 * @param columnName the name of the set column.
393- * @param element the element to delete.
391+ * @param element the element to delete.
394392 * @return this in-build DELETE Selection
395393 */
396394 public Selection setElt(String columnName, BindMarker element) {
@@ -402,7 +400,7 @@
402400 * Deletes a map element given a key.
403401 *
404402 * @param columnName the name of the map column.
405- * @param key the key for the element to delete.
403+ * @param key the key for the element to delete.
406404 * @return this in-build DELETE Selection
407405 */
408406 public Selection mapElt(String columnName, Object key) {
@@ -488,7 +486,7 @@
488486
489487 /**
490488 * Adds the provided condition for the deletion.
491- * <p>
489+ * <p/>
492490 * Note that while the query builder accept any type of {@code Clause}
493491 * as conditions, Cassandra currently only allows equality ones.
494492 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +17 −17
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.CodecRegistry;
19+import com.datastax.driver.core.TableMetadata;
20+
1821 import java.util.ArrayList;
1922 import java.util.Arrays;
2023 import java.util.List;
2124
22-import com.datastax.driver.core.CodecRegistry;
23-import com.datastax.driver.core.TableMetadata;
24-
2525 /**
2626 * A built INSERT statement.
2727 */
@@ -72,7 +72,7 @@
7272 /**
7373 * Adds a column/value pair to the values inserted by this INSERT statement.
7474 *
75- * @param name the name of the column to insert/update.
75+ * @param name the name of the column to insert/update.
7676 * @param value the value to insert/update for {@code name}.
7777 * @return this INSERT statement.
7878 */
@@ -89,10 +89,10 @@
8989 /**
9090 * Adds multiple column/value pairs to the values inserted by this INSERT statement.
9191 *
92- * @param names a list of column names to insert/update.
92+ * @param names a list of column names to insert/update.
9393 * @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}.
94+ * value in {@code values} will be inserted for the {@code i}th column
95+ * in {@code names}.
9696 * @return this INSERT statement.
9797 * @throws IllegalArgumentException if {@code names.length != values.length}.
9898 */
@@ -103,10 +103,10 @@
103103 /**
104104 * Adds multiple column/value pairs to the values inserted by this INSERT statement.
105105 *
106- * @param names a list of column names to insert/update.
106+ * @param names a list of column names to insert/update.
107107 * @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}.
108+ * value in {@code values} will be inserted for the {@code i}th column
109+ * in {@code names}.
110110 * @return this INSERT statement.
111111 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
112112 */
@@ -145,15 +145,16 @@
145145 public Options using() {
146146 return usings;
147147 }
148+
148149 /**
149150 * Sets the 'IF NOT EXISTS' option for this INSERT statement.
150- * <p>
151+ * <p/>
151152 * An insert with that option will not succeed unless the row does not
152153 * exist at the time the insertion is executed. The existence check and
153154 * insertions are done transactionally in the sense that if multiple
154155 * clients attempt to create a given row with this option, then at most one
155156 * may succeed.
156- * <p>
157+ * <p/>
157158 * Please keep in mind that using this option has a non negligible
158159 * performance impact and should be avoided when possible.
159160 *
@@ -190,7 +191,7 @@
190191 /**
191192 * Adds a column/value pair to the values inserted by this INSERT statement.
192193 *
193- * @param name the name of the column to insert/update.
194+ * @param name the name of the column to insert/update.
194195 * @param value the value to insert/update for {@code name}.
195196 * @return the INSERT statement those options are part of.
196197 */
@@ -201,12 +202,11 @@
201202 /**
202203 * Adds multiple column/value pairs to the values inserted by this INSERT statement.
203204 *
204- * @param names a list of column names to insert/update.
205+ * @param names a list of column names to insert/update.
205206 * @param values a list of values to insert/update. The {@code i}th
206- * value in {@code values} will be inserted for the {@code i}th column
207- * in {@code names}.
207+ * value in {@code values} will be inserted for the {@code i}th column
208+ * in {@code names}.
208209 * @return the INSERT statement those options are part of.
209- *
210210 * @throws IllegalArgumentException if {@code names.length != values.length}.
211211 */
212212 public Insert values(String[] names, Object[] values) {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java +2 −2
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.List;
19-
2018 import com.datastax.driver.core.CodecRegistry;
2119
20+import java.util.List;
21+
2222 public class Ordering extends Utils.Appendeable {
2323
2424 private final String name;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +105 −109
@@ -15,34 +15,36 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.*;
19-
20-import com.datastax.driver.core.*;
18+import com.datastax.driver.core.RegularStatement;
19+import com.datastax.driver.core.TableMetadata;
2120 import com.datastax.driver.core.exceptions.InvalidQueryException;
2221
22+import java.util.*;
23+
2324 /**
2425 * Builds CQL3 query via a fluent API.
25- * <p>
26+ * <p/>
2627 * The queries built by this builder will provide a value for the
2728 * {@link com.datastax.driver.core.Statement#getRoutingKey} method only when a
2829 * {@link com.datastax.driver.core.TableMetadata} is provided to the builder.
2930 * It is thus advised to do so if a {@link com.datastax.driver.core.policies.TokenAwarePolicy}
3031 * is in use.
31- * <p>
32+ * <p/>
3233 * The provider builders perform very little validation of the built query.
3334 * There is thus no guarantee that a built query is valid, and it is
3435 * definitively possible to create invalid queries.
35- * <p>
36+ * <p/>
3637 * Note that it could be convenient to use an 'import static' to bring the static methods of
3738 * this class into scope.
3839 */
3940 public final class QueryBuilder {
4041
41- private QueryBuilder() {}
42+ private QueryBuilder() {
43+ }
4244
4345 /**
4446 * Start building a new SELECT query that selects the provided names.
45- *
47+ * <p/>
4648 * Note that {@code select(c1, c2)} is just a shortcut for {@code select().column(c1).column(c2) }.
4749 *
4850 * @param columns the columns names that should be selected by the query.
@@ -50,7 +52,7 @@
5052 * least a FROM clause to complete the query).
5153 */
5254 public static Select.Builder select(String... columns) {
53- return new Select.Builder(Arrays.asList((Object[])columns));
55+ return new Select.Builder(Arrays.asList((Object[]) columns));
5456 }
5557
5658 /**
@@ -78,7 +80,7 @@
7880 * Start building a new INSERT query.
7981 *
8082 * @param keyspace the name of the keyspace to use.
81- * @param table the name of the table to insert into.
83+ * @param table the name of the table to insert into.
8284 * @return an in-construction INSERT query.
8385 */
8486 public static Insert insertInto(String keyspace, String table) {
@@ -110,7 +112,7 @@
110112 * Start building a new UPDATE query.
111113 *
112114 * @param keyspace the name of the keyspace to use.
113- * @param table the name of the table to update.
115+ * @param table the name of the table to update.
114116 * @return an in-construction UPDATE query (at least a SET and a WHERE
115117 * clause needs to be provided to complete the query).
116118 */
@@ -153,7 +155,7 @@
153155
154156 /**
155157 * Built a new BATCH query on the provided statements.
156- * <p>
158+ * <p/>
157159 * This method will build a logged batch (this is the default in CQL3). To
158160 * create unlogged batches, use {@link #unloggedBatch}. Also note that
159161 * for convenience, if the provided statements are counter statements, this
@@ -170,14 +172,14 @@
170172
171173 /**
172174 * Built a new UNLOGGED BATCH query on the provided statements.
173- * <p>
175+ * <p/>
174176 * Compared to logged batches (the default), unlogged batch don't
175177 * use the distributed batch log server side and as such are not
176178 * guaranteed to be atomic. In other words, if an unlogged batch
177179 * timeout, some of the batched statements may have been persisted
178180 * while some have not. Unlogged batch will however be slightly
179181 * faster than logged batch.
180- * <p>
182+ * <p/>
181183 * If the statements added to the batch are counter statements, the
182184 * resulting batch will be a COUNTER one.
183185 *
@@ -203,7 +205,7 @@
203205 * Creates a new TRUNCATE query.
204206 *
205207 * @param keyspace the name of the keyspace to use.
206- * @param table the name of the table to truncate.
208+ * @param table the name of the table to truncate.
207209 * @return the truncation query.
208210 */
209211 public static Truncate truncate(String keyspace, String table) {
@@ -246,7 +248,7 @@
246248
247249 /**
248250 * The token of column names.
249- * <p>
251+ * <p/>
250252 * This variant is most useful when the partition key is composite.
251253 *
252254 * @param columnNames the column names to take the token of.
@@ -255,7 +257,7 @@
255257 public static String token(String... columnNames) {
256258 StringBuilder sb = new StringBuilder();
257259 sb.append("token(");
258- Utils.joinAndAppendNames(sb, null, ",", Arrays.asList((Object[])columnNames));
260+ Utils.joinAndAppendNames(sb, null, ",", Arrays.asList((Object[]) columnNames));
259261 sb.append(')');
260262 return sb.toString();
261263 }
@@ -264,7 +266,7 @@
264266 * Creates an "equal" where clause stating the provided column must be
265267 * equal to the provided value.
266268 *
267- * @param name the column name
269+ * @param name the column name
268270 * @param value the value
269271 * @return the corresponding where clause.
270272 */
@@ -276,31 +278,31 @@
276278 * Create an "in" where clause stating the provided column must be equal
277279 * to one of the provided values.
278280 *
279- * @param name the column name
281+ * @param name the column name
280282 * @param values the values
281283 * @return the corresponding where clause.
282284 */
283285 public static Clause in(String name, Object... values) {
284286 return new Clause.InClause(name, Arrays.asList(values));
285287 }
286-
288+
287289 /**
288290 * Create an "in" where clause stating the provided column must be equal
289291 * to one of the provided values.
290292 *
291- * @param name the column name
293+ * @param name the column name
292294 * @param values the values
293295 * @return the corresponding where clause.
294296 */
295- public static Clause in(String name, List<?> values) {
296- return new Clause.InClause(name, values);
297- }
297+ public static Clause in(String name, List<?> values) {
298+ return new Clause.InClause(name, values);
299+ }
298300
299301 /**
300302 * Creates a "contains" where clause stating the provided column must contain
301303 * the value provided.
302304 *
303- * @param name the column name
305+ * @param name the column name
304306 * @param value the value
305307 * @return the corresponding where clause.
306308 */
@@ -313,7 +315,7 @@
313315 * the key provided.
314316 *
315317 * @param name the column name
316- * @param key the key
318+ * @param key the key
317319 * @return the corresponding where clause.
318320 */
319321 public static Clause containsKey(String name, Object key) {
@@ -324,7 +326,7 @@
324326 * Creates a "lesser than" where clause stating the provided column must be less than
325327 * the provided value.
326328 *
327- * @param name the column name
329+ * @param name the column name
328330 * @param value the value
329331 * @return the corresponding where clause.
330332 */
@@ -334,16 +336,15 @@
334336
335337 /**
336338 * Creates a "lesser than" where clause for a group of clustering columns.
337- * <p>
339+ * <p/>
338340 * For instance, {@code lt(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
339341 * will generate the CQL WHERE clause {@code (a, b) &lt; (2, 'test') }.
340- * <p>
342+ * <p/>
341343 * Please note that this variant is only supported starting with Cassandra 2.0.6.
342344 *
343- * @param names the column names
345+ * @param names the column names
344346 * @param values the values
345347 * @return the corresponding where clause.
346- *
347348 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
348349 */
349350 public static Clause lt(List<String> names, List<?> values) {
@@ -357,7 +358,7 @@
357358 * Creates a "lesser than or equal" where clause stating the provided column must
358359 * be lesser than or equal to the provided value.
359360 *
360- * @param name the column name
361+ * @param name the column name
361362 * @param value the value
362363 * @return the corresponding where clause.
363364 */
@@ -367,16 +368,15 @@
367368
368369 /**
369370 * Creates a "lesser than or equal" where clause for a group of clustering columns.
370- * <p>
371+ * <p/>
371372 * For instance, {@code lte(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
372373 * will generate the CQL WHERE clause {@code (a, b) &lte; (2, 'test') }.
373- * <p>
374+ * <p/>
374375 * Please note that this variant is only supported starting with Cassandra 2.0.6.
375376 *
376- * @param names the column names
377+ * @param names the column names
377378 * @param values the values
378379 * @return the corresponding where clause.
379- *
380380 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
381381 */
382382 public static Clause lte(List<String> names, List<?> values) {
@@ -390,7 +390,7 @@
390390 * Creates a "greater than" where clause stating the provided column must
391391 * be greater to the provided value.
392392 *
393- * @param name the column name
393+ * @param name the column name
394394 * @param value the value
395395 * @return the corresponding where clause.
396396 */
@@ -400,16 +400,15 @@
400400
401401 /**
402402 * Creates a "greater than" where clause for a group of clustering columns.
403- * <p>
403+ * <p/>
404404 * For instance, {@code gt(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
405405 * will generate the CQL WHERE clause {@code (a, b) &gt; (2, 'test') }.
406- * <p>
406+ * <p/>
407407 * Please note that this variant is only supported starting with Cassandra 2.0.6.
408408 *
409- * @param names the column names
409+ * @param names the column names
410410 * @param values the values
411411 * @return the corresponding where clause.
412- *
413412 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
414413 */
415414 public static Clause gt(List<String> names, List<?> values) {
@@ -423,7 +422,7 @@
423422 * Creates a "greater than or equal" where clause stating the provided
424423 * column must be greater than or equal to the provided value.
425424 *
426- * @param name the column name
425+ * @param name the column name
427426 * @param value the value
428427 * @return the corresponding where clause.
429428 */
@@ -433,16 +432,15 @@
433432
434433 /**
435434 * Creates a "greater than or equal" where clause for a group of clustering columns.
436- * <p>
435+ * <p/>
437436 * For instance, {@code gte(Arrays.asList("a", "b"), Arrays.asList(2, "test"))}
438437 * will generate the CQL WHERE clause {@code (a, b) &gte; (2, 'test') }.
439- * <p>
438+ * <p/>
440439 * Please note that this variant is only supported starting with Cassandra 2.0.6.
441440 *
442- * @param names the column names
441+ * @param names the column names
443442 * @param values the values
444443 * @return the corresponding where clause.
445- *
446444 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
447445 */
448446 public static Clause gte(List<String> names, List<?> values) {
@@ -477,7 +475,6 @@
477475 *
478476 * @param timestamp the timestamp (in microseconds) to use.
479477 * @return the corresponding option
480- *
481478 * @throws IllegalArgumentException if {@code timestamp &lt; 0}.
482479 */
483480 public static Using timestamp(long timestamp) {
@@ -502,7 +499,6 @@
502499 *
503500 * @param ttl the ttl (in seconds) to use.
504501 * @return the corresponding option
505- *
506502 * @throws IllegalArgumentException if {@code ttl &lt; 0}.
507503 */
508504 public static Using ttl(int ttl) {
@@ -524,10 +520,10 @@
524520
525521 /**
526522 * Simple "set" assignment of a value to a column.
527- * <p>
523+ * <p/>
528524 * This will generate: {@code name = value}.
529525 *
530- * @param name the column name
526+ * @param name the column name
531527 * @param value the value to assign
532528 * @return the correspond assignment (to use in an update query)
533529 */
@@ -537,7 +533,7 @@
537533
538534 /**
539535 * Incrementation of a counter column.
540- * <p>
536+ * <p/>
541537 * This will generate: {@code name = name + 1}.
542538 *
543539 * @param name the column name to increment
@@ -549,10 +545,10 @@
549545
550546 /**
551547 * Incrementation of a counter column by a provided value.
552- * <p>
548+ * <p/>
553549 * This will generate: {@code name = name + value}.
554550 *
555- * @param name the column name to increment
551+ * @param name the column name to increment
556552 * @param value the value by which to increment
557553 * @return the correspond assignment (to use in an update query)
558554 */
@@ -562,10 +558,10 @@
562558
563559 /**
564560 * Incrementation of a counter column by a provided value.
565- * <p>
561+ * <p/>
566562 * This will generate: {@code name = name + value}.
567563 *
568- * @param name the column name to increment
564+ * @param name the column name to increment
569565 * @param value a bind marker representing the value by which to increment
570566 * @return the correspond assignment (to use in an update query)
571567 */
@@ -575,7 +571,7 @@
575571
576572 /**
577573 * Decrementation of a counter column.
578- * <p>
574+ * <p/>
579575 * This will generate: {@code name = name - 1}.
580576 *
581577 * @param name the column name to decrement
@@ -587,10 +583,10 @@
587583
588584 /**
589585 * Decrementation of a counter column by a provided value.
590- * <p>
586+ * <p/>
591587 * This will generate: {@code name = name - value}.
592588 *
593- * @param name the column name to decrement
589+ * @param name the column name to decrement
594590 * @param value the value by which to decrement
595591 * @return the correspond assignment (to use in an update query)
596592 */
@@ -600,10 +596,10 @@
600596
601597 /**
602598 * Decrementation of a counter column by a provided value.
603- * <p>
599+ * <p/>
604600 * This will generate: {@code name = name - value}.
605601 *
606- * @param name the column name to decrement
602+ * @param name the column name to decrement
607603 * @param value a bind marker representing the value by which to decrement
608604 * @return the correspond assignment (to use in an update query)
609605 */
@@ -613,10 +609,10 @@
613609
614610 /**
615611 * Prepend a value to a list column.
616- * <p>
612+ * <p/>
617613 * This will generate: {@code name = [ value ] + name}.
618614 *
619- * @param name the column name (must be of type list).
615+ * @param name the column name (must be of type list).
620616 * @param value the value to prepend. Using a BindMarker here is not supported.
621617 * To use a BindMarker use {@code QueryBuilder#prependAll} with a
622618 * singleton list.
@@ -631,7 +627,7 @@
631627
632628 /**
633629 * Prepend a list of values to a list column.
634- * <p>
630+ * <p/>
635631 * This will generate: {@code name = list + name}.
636632 *
637633 * @param name the column name (must be of type list).
@@ -644,7 +640,7 @@
644640
645641 /**
646642 * Prepend a list of values to a list column.
647- * <p>
643+ * <p/>
648644 * This will generate: {@code name = list + name}.
649645 *
650646 * @param name the column name (must be of type list).
@@ -657,10 +653,10 @@
657653
658654 /**
659655 * Append a value to a list column.
660- * <p>
656+ * <p/>
661657 * This will generate: {@code name = name + [value]}.
662658 *
663- * @param name the column name (must be of type list).
659+ * @param name the column name (must be of type list).
664660 * @param value the value to append. Using a BindMarker here is not supported.
665661 * To use a BindMarker use {@code QueryBuilder#appendAll} with a
666662 * singleton list.
@@ -675,7 +671,7 @@
675671
676672 /**
677673 * Append a list of values to a list column.
678- * <p>
674+ * <p/>
679675 * This will generate: {@code name = name + list}.
680676 *
681677 * @param name the column name (must be of type list).
@@ -688,7 +684,7 @@
688684
689685 /**
690686 * Append a list of values to a list column.
691- * <p>
687+ * <p/>
692688 * This will generate: {@code name = name + list}.
693689 *
694690 * @param name the column name (must be of type list).
@@ -701,10 +697,10 @@
701697
702698 /**
703699 * Discard a value from a list column.
704- * <p>
700+ * <p/>
705701 * This will generate: {@code name = name - [value]}.
706702 *
707- * @param name the column name (must be of type list).
703+ * @param name the column name (must be of type list).
708704 * @param value the value to discard. Using a BindMarker here is not supported.
709705 * To use a BindMarker use {@code QueryBuilder#discardAll} with a singleton list.
710706 * @return the correspond assignment (to use in an update query)
@@ -718,7 +714,7 @@
718714
719715 /**
720716 * Discard a list of values to a list column.
721- * <p>
717+ * <p/>
722718 * This will generate: {@code name = name - list}.
723719 *
724720 * @param name the column name (must be of type list).
@@ -731,7 +727,7 @@
731727
732728 /**
733729 * Discard a list of values to a list column.
734- * <p>
730+ * <p/>
735731 * This will generate: {@code name = name - list}.
736732 *
737733 * @param name the column name (must be of type list).
@@ -744,11 +740,11 @@
744740
745741 /**
746742 * Sets a list column value by index.
747- * <p>
743+ * <p/>
748744 * This will generate: {@code name[idx] = value}.
749745 *
750- * @param name the column name (must be of type list).
751- * @param idx the index to set
746+ * @param name the column name (must be of type list).
747+ * @param idx the index to set
752748 * @param value the value to set
753749 * @return the correspond assignment (to use in an update query)
754750 */
@@ -758,17 +754,17 @@
758754
759755 /**
760756 * Adds a value to a set column.
761- * <p>
757+ * <p/>
762758 * This will generate: {@code name = name + {value}}.
763759 *
764- * @param name the column name (must be of type set).
760+ * @param name the column name (must be of type set).
765761 * @param value the value to add. Using a BindMarker here is not supported.
766762 * To use a BindMarker use {@code QueryBuilder#addAll} with a
767763 * singleton set.
768764 * @return the correspond assignment (to use in an update query)
769765 */
770766 public static Assignment add(String name, Object value) {
771- if (value instanceof BindMarker){
767+ if (value instanceof BindMarker) {
772768 throw new InvalidQueryException("Binding a value in add() is not supported, use addAll() and bind a singleton list");
773769 }
774770 return addAll(name, Collections.singleton(value));
@@ -776,11 +772,11 @@
776772
777773 /**
778774 * Adds a set of values to a set column.
779- * <p>
775+ * <p/>
780776 * This will generate: {@code name = name + set}.
781777 *
782778 * @param name the column name (must be of type set).
783- * @param set the set of values to append
779+ * @param set the set of values to append
784780 * @return the correspond assignment (to use in an update query)
785781 */
786782 public static Assignment addAll(String name, Set<?> set) {
@@ -789,11 +785,11 @@
789785
790786 /**
791787 * Adds a set of values to a set column.
792- * <p>
788+ * <p/>
793789 * This will generate: {@code name = name + set}.
794790 *
795791 * @param name the column name (must be of type set).
796- * @param set a bind marker representing the set of values to append
792+ * @param set a bind marker representing the set of values to append
797793 * @return the correspond assignment (to use in an update query)
798794 */
799795 public static Assignment addAll(String name, BindMarker set) {
@@ -802,10 +798,10 @@
802798
803799 /**
804800 * Remove a value from a set column.
805- * <p>
801+ * <p/>
806802 * This will generate: {@code name = name - {value}}.
807803 *
808- * @param name the column name (must be of type set).
804+ * @param name the column name (must be of type set).
809805 * @param value the value to remove. Using a BindMarker here is not supported.
810806 * To use a BindMarker use {@code QueryBuilder#removeAll} with a singleton set.
811807 * @return the correspond assignment (to use in an update query)
@@ -819,11 +815,11 @@
819815
820816 /**
821817 * Remove a set of values from a set column.
822- * <p>
818+ * <p/>
823819 * This will generate: {@code name = name - set}.
824820 *
825821 * @param name the column name (must be of type set).
826- * @param set the set of values to remove
822+ * @param set the set of values to remove
827823 * @return the correspond assignment (to use in an update query)
828824 */
829825 public static Assignment removeAll(String name, Set<?> set) {
@@ -832,11 +828,11 @@
832828
833829 /**
834830 * Remove a set of values from a set column.
835- * <p>
831+ * <p/>
836832 * This will generate: {@code name = name - set}.
837833 *
838834 * @param name the column name (must be of type set).
839- * @param set a bind marker representing the set of values to remove
835+ * @param set a bind marker representing the set of values to remove
840836 * @return the correspond assignment (to use in an update query)
841837 */
842838 public static Assignment removeAll(String name, BindMarker set) {
@@ -845,11 +841,11 @@
845841
846842 /**
847843 * Puts a new key/value pair to a map column.
848- * <p>
844+ * <p/>
849845 * This will generate: {@code name[key] = value}.
850846 *
851- * @param name the column name (must be of type map).
852- * @param key the key to put
847+ * @param name the column name (must be of type map).
848+ * @param key the key to put
853849 * @param value the value to put
854850 * @return the correspond assignment (to use in an update query)
855851 */
@@ -859,11 +855,11 @@
859855
860856 /**
861857 * Puts a map of new key/value pairs to a map column.
862- * <p>
858+ * <p/>
863859 * This will generate: {@code name = name + map}.
864860 *
865861 * @param name the column name (must be of type map).
866- * @param map the map of key/value pairs to put
862+ * @param map the map of key/value pairs to put
867863 * @return the correspond assignment (to use in an update query)
868864 */
869865 public static Assignment putAll(String name, Map<?, ?> map) {
@@ -872,11 +868,11 @@
872868
873869 /**
874870 * Puts a map of new key/value pairs to a map column.
875- * <p>
871+ * <p/>
876872 * This will generate: {@code name = name + map}.
877873 *
878874 * @param name the column name (must be of type map).
879- * @param map a bind marker representing the map of key/value pairs to put
875+ * @param map a bind marker representing the map of key/value pairs to put
880876 * @return the correspond assignment (to use in an update query)
881877 */
882878 public static Assignment putAll(String name, BindMarker map) {
@@ -885,7 +881,7 @@
885881
886882 /**
887883 * An object representing an anonymous bind marker (a question mark).
888- * <p>
884+ * <p/>
889885 * This can be used wherever a value is expected. For instance, one can do:
890886 * <pre>
891887 * {@code
@@ -903,7 +899,7 @@
903899
904900 /**
905901 * An object representing a named bind marker.
906- * <p>
902+ * <p/>
907903 * This can be used wherever a value is expected. For instance, one can do:
908904 * <pre>
909905 * {@code
@@ -912,7 +908,7 @@
912908 * PreparedState p = session.prepare(i.toString());
913909 * }
914910 * </pre>
915- * <p>
911+ * <p/>
916912 * Please note that named bind makers are only supported starting with Cassandra 2.0.1.
917913 *
918914 * @param name the name for the bind marker.
@@ -924,19 +920,19 @@
924920
925921 /**
926922 * Protects a value from any interpretation by the query builder.
927- * <p>
923+ * <p/>
928924 * The following table exemplify the behavior of this function:
929925 * <table border=1>
930- * <caption>Examples of use</caption>
931- * <tr><th>Code</th><th>Resulting query string</th></tr>
932- * <tr><td>{@code select().from("t").where(eq("c", "C'est la vie!")); }</td><td>{@code "SELECT * FROM t WHERE c='C''est la vie!';"}</td></tr>
933- * <tr><td>{@code select().from("t").where(eq("c", raw("C'est la vie!"))); }</td><td>{@code "SELECT * FROM t WHERE c=C'est la vie!;"}</td></tr>
934- * <tr><td>{@code select().from("t").where(eq("c", raw("'C'est la vie!'"))); }</td><td>{@code "SELECT * FROM t WHERE c='C'est la vie!';"}</td></tr>
935- * <tr><td>{@code select().from("t").where(eq("c", "now()")); }</td><td>{@code "SELECT * FROM t WHERE c='now()';"}</td></tr>
936- * <tr><td>{@code select().from("t").where(eq("c", raw("now()"))); }</td><td>{@code "SELECT * FROM t WHERE c=now();"}</td></tr>
926+ * <caption>Examples of use</caption>
927+ * <tr><th>Code</th><th>Resulting query string</th></tr>
928+ * <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>
929+ * <tr><td>{@code select().from("t").where(eq("c", raw("C'est la vie!"))); }</td><td>{@code "SELECT * FROM t WHERE c=C'est la vie!;"}</td></tr>
930+ * <tr><td>{@code select().from("t").where(eq("c", raw("'C'est la vie!'"))); }</td><td>{@code "SELECT * FROM t WHERE c='C'est la vie!';"}</td></tr>
931+ * <tr><td>{@code select().from("t").where(eq("c", "now()")); }</td><td>{@code "SELECT * FROM t WHERE c='now()';"}</td></tr>
932+ * <tr><td>{@code select().from("t").where(eq("c", raw("now()"))); }</td><td>{@code "SELECT * FROM t WHERE c=now();"}</td></tr>
937933 * </table>
938934 * <i>Note: the 2nd and 3rd examples in this table are not a valid CQL3 queries.</i>
939- * <p>
935+ * <p/>
940936 * The use of that method is generally discouraged since it lead to security risks. However,
941937 * if you know what you are doing, it allows to escape the interpretations done by the
942938 * QueryBuilder.
@@ -951,7 +947,7 @@
951947 /**
952948 * Creates a function call.
953949 *
954- * @param name the name of the function to call.
950+ * @param name the name of the function to call.
955951 * @param parameters the parameters for the function.
956952 * @return the function call.
957953 */
@@ -979,7 +975,7 @@
979975
980976 /**
981977 * Declares that the name in argument should be treated as a column name.
982- * <p>
978+ * <p/>
983979 * This mainly meant for use with {@link Select.Selection#fcall} when a
984980 * function should apply to a column name, not a string value.
985981 *
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +27 −37
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.CodecRegistry;
19+import com.datastax.driver.core.TableMetadata;
20+
1821 import java.util.ArrayList;
1922 import java.util.Arrays;
2023 import java.util.Collections;
2124 import java.util.List;
2225
23-import com.datastax.driver.core.CodecRegistry;
24-import com.datastax.driver.core.TableMetadata;
25-
2626 /**
2727 * A built SELECT statement.
2828 */
@@ -94,7 +94,7 @@
9494
9595 /**
9696 * Adds a WHERE clause to this statement.
97- *
97+ * <p/>
9898 * This is a shorter/more readable version for {@code where().and(clause)}.
9999 *
100100 * @param clause the clause to add.
@@ -118,9 +118,8 @@
118118 *
119119 * @param orderings the orderings to define for this query.
120120 * @return this statement.
121- *
122121 * @throws IllegalStateException if an ORDER BY clause has already been
123- * provided.
122+ * provided.
124123 */
125124 public Select orderBy(Ordering... orderings) {
126125 if (this.orderings != null)
@@ -137,10 +136,9 @@
137136 *
138137 * @param limit the limit to set.
139138 * @return this statement.
140- *
141139 * @throws IllegalArgumentException if {@code limit &gte; 0}.
142- * @throws IllegalStateException if a LIMIT clause has already been
143- * provided.
140+ * @throws IllegalStateException if a LIMIT clause has already been
141+ * provided.
144142 */
145143 public Select limit(int limit) {
146144 if (limit <= 0)
@@ -159,9 +157,8 @@
159157 *
160158 * @param marker the marker to use for the limit.
161159 * @return this statement.
162- *
163160 * @throws IllegalStateException if a LIMIT clause has already been
164- * provided.
161+ * provided.
165162 */
166163 public Select limit(BindMarker marker) {
167164 if (this.limit != null)
@@ -212,9 +209,8 @@
212209 *
213210 * @param orderings the orderings to add.
214211 * @return the select statement this Where clause if part of.
215- *
216212 * @throws IllegalStateException if an ORDER BY clause has already been
217- * provided.
213+ * provided.
218214 */
219215 public Select orderBy(Ordering... orderings) {
220216 return statement.orderBy(orderings);
@@ -226,10 +222,9 @@
226222 *
227223 * @param limit the limit to set.
228224 * @return the select statement this Where clause if part of.
229- *
230225 * @throws IllegalArgumentException if {@code limit &gte; 0}.
231- * @throws IllegalStateException if a LIMIT clause has already been
232- * provided.
226+ * @throws IllegalStateException if a LIMIT clause has already been
227+ * provided.
233228 */
234229 public Select limit(int limit) {
235230 return statement.limit(limit);
@@ -241,9 +236,8 @@
241236 *
242237 * @param limit the bind marker to use as limit.
243238 * @return the select statement this Where clause if part of.
244- *
245239 * @throws IllegalStateException if a LIMIT clause has already been
246- * provided.
240+ * provided.
247241 */
248242 public Select limit(BindMarker limit) {
249243 return statement.limit(limit);
@@ -289,7 +283,7 @@
289283 * Adds the table to select from.
290284 *
291285 * @param keyspace the name of the keyspace to select from.
292- * @param table the name of the table to select from.
286+ * @param table the name of the table to select from.
293287 * @return a newly built SELECT statement that selects from {@code keyspace.table}.
294288 */
295289 public Select from(String keyspace, String table) {
@@ -326,7 +320,6 @@
326320 * Selects all columns (i.e. "SELECT * ...")
327321 *
328322 * @return an in-build SELECT statement.
329- *
330323 * @throws IllegalStateException if some columns had already been selected for this builder.
331324 */
332325 public abstract Builder all();
@@ -335,7 +328,6 @@
335328 * Selects the count of all returned rows (i.e. "SELECT count(*) ...").
336329 *
337330 * @return an in-build SELECT statement.
338- *
339331 * @throws IllegalStateException if some columns had already been selected for this builder.
340332 */
341333 public abstract Builder countAll();
@@ -350,7 +342,7 @@
350342
351343 /**
352344 * Selects the write time of provided column.
353- * <p>
345+ * <p/>
354346 * This is a shortcut for {@code fcall("writetime", QueryBuilder.column(name))}.
355347 *
356348 * @param name the name of the column to select the write time of.
@@ -360,7 +352,7 @@
360352
361353 /**
362354 * Selects the ttl of provided column.
363- * <p>
355+ * <p/>
364356 * This is a shortcut for {@code fcall("ttl", QueryBuilder.column(name))}.
365357 *
366358 * @param name the name of the column to select the ttl of.
@@ -370,16 +362,16 @@
370362
371363 /**
372364 * Creates a function call.
373- * <p>
365+ * <p/>
374366 * Please note that the parameters are interpreted as values, and so
375367 * {@code fcall("textToBlob", "foo")} will generate the string
376368 * {@code "textToBlob('foo')"}. If you want to generate
377369 * {@code "textToBlob(foo)"}, i.e. if the argument must be interpreted
378370 * as a column name (in a select clause), you will need to use the
379- * {@link QueryBuilder#column} method, and so
371+ * {@link QueryBuilder#column} method, and so
380372 * {@code fcall("textToBlob", QueryBuilder.column(foo)}.
381373 *
382- * @param name the name of the function.
374+ * @param name the name of the function.
383375 * @param parameters the parameters for the function call.
384376 * @return this in-build SELECT statement
385377 */
@@ -388,7 +380,7 @@
388380
389381 /**
390382 * An Selection clause for an in-construction SELECT statement.
391- * <p>
383+ * <p/>
392384 * This only differs from {@link Selection} in that you can add an
393385 * alias for the previously selected item through {@link SelectionOrAlias#as}.
394386 */
@@ -430,7 +422,6 @@
430422 * Selects all columns (i.e. "SELECT * ...")
431423 *
432424 * @return an in-build SELECT statement.
433- *
434425 * @throws IllegalStateException if some columns had already been selected for this builder.
435426 */
436427 public Builder all() {
@@ -439,14 +430,13 @@
439430 if (previousSelection != null)
440431 throw new IllegalStateException(String.format("Some columns ([%s]) have already been selected.", previousSelection));
441432
442- return (Builder)this;
433+ return (Builder) this;
443434 }
444435
445436 /**
446437 * Selects the count of all returned rows (i.e. "SELECT count(*) ...").
447438 *
448439 * @return an in-build SELECT statement.
449- *
450440 * @throws IllegalStateException if some columns had already been selected for this builder.
451441 */
452442 public Builder countAll() {
@@ -456,7 +446,7 @@
456446 throw new IllegalStateException(String.format("Some columns ([%s]) have already been selected.", previousSelection));
457447
458448 columnNames = COUNT_ALL;
459- return (Builder)this;
449+ return (Builder) this;
460450 }
461451
462452 /**
@@ -471,7 +461,7 @@
471461
472462 /**
473463 * Selects the provided raw expression.
474- *
464+ * <p/>
475465 * This method is used internally by the mapper module. It is not exposed on the parent class {@link Selection} to
476466 * avoid breaking binary compatibility. This means that it is not accessible directly via the fluent API (you need
477467 * a cast). This shouldn't be a problem for regular clients because they will use other methods of the DSL
@@ -486,7 +476,7 @@
486476
487477 /**
488478 * Selects the write time of provided column.
489- * <p>
479+ * <p/>
490480 * This is a shortcut for {@code fcall("writetime", QueryBuilder.column(name))}.
491481 *
492482 * @param name the name of the column to select the write time of.
@@ -498,7 +488,7 @@
498488
499489 /**
500490 * Selects the ttl of provided column.
501- * <p>
491+ * <p/>
502492 * This is a shortcut for {@code fcall("ttl", QueryBuilder.column(name))}.
503493 *
504494 * @param name the name of the column to select the ttl of.
@@ -510,13 +500,13 @@
510500
511501 /**
512502 * Creates a function call.
513- * <p>
503+ * <p/>
514504 * Please note that the parameters are interpreted as values, and so
515505 * {@code fcall("textToBlob", "foo")} will generate the string
516506 * {@code "textToBlob('foo')"}. If you want to generate
517507 * {@code "textToBlob(foo)"}, i.e. if the argument must be interpreted
518508 * as a column name (in a select clause), you will need to use the
519- * {@link QueryBuilder#column} method, and so
509+ * {@link QueryBuilder#column} method, and so
520510 * {@code fcall("textToBlob", QueryBuilder.column(foo)}.
521511 */
522512 public SelectionOrAlias fcall(String name, Object... parameters) {
@@ -527,7 +517,7 @@
527517 * Adds the table to select from.
528518 *
529519 * @param keyspace the name of the keyspace to select from.
530- * @param table the name of the table to select from.
520+ * @param table the name of the table to select from.
531521 * @return a newly built SELECT statement that selects from {@code keyspace.table}.
532522 */
533523 @Override
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java +2 −2
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.List;
19-
2018 import com.datastax.driver.core.CodecRegistry;
2119 import com.datastax.driver.core.TableMetadata;
2220
21+import java.util.List;
22+
2323 /**
2424 * A built TRUNCATE statement.
2525 */
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +13 −13
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.ArrayList;
19-import java.util.List;
20-
2118 import com.datastax.driver.core.CodecRegistry;
2219 import com.datastax.driver.core.TableMetadata;
2320 import com.datastax.driver.core.querybuilder.Assignment.CounterAssignment;
2421
22+import java.util.ArrayList;
23+import java.util.List;
24+
2525 /**
2626 * A built UPDATE statement.
2727 */
@@ -92,7 +92,7 @@
9292
9393 /**
9494 * Adds an assignment to this UPDATE statement.
95- *
95+ * <p/>
9696 * This is a shorter/more readable version for {@code with().and(assignment)}.
9797 *
9898 * @param assignment the assignment to add.
@@ -113,7 +113,7 @@
113113
114114 /**
115115 * Adds a WHERE clause to this statement.
116- *
116+ * <p/>
117117 * This is a shorter/more readable version for {@code where().and(clause)}.
118118 *
119119 * @param clause the clause to add.
@@ -134,7 +134,7 @@
134134
135135 /**
136136 * Adds a conditions clause (IF) to this statement.
137- * <p>
137+ * <p/>
138138 * This is a shorter/more readable version for {@code onlyIf().and(condition)}.
139139 *
140140 * @param condition the condition to add.
@@ -274,11 +274,11 @@
274274 public Conditions onlyIf(Clause condition) {
275275 return statement.onlyIf(condition);
276276 }
277-
277+
278278 /**
279279 * Sets the 'IF EXISTS' option for the UPDATE statement this WHERE clause
280280 * is part of.
281- *
281+ * <p/>
282282 * <p>
283283 * An update with that option will report whether the statement actually
284284 * resulted in data being updated. The existence check and update are
@@ -354,10 +354,10 @@
354354
355355 /**
356356 * Conditions for an UPDATE statement.
357- * <p>
357+ * <p/>
358358 * When provided some conditions, an update will not apply unless the
359359 * provided conditions applies.
360- * <p>
360+ * <p/>
361361 * Please keep in mind that provided conditions has a non negligible
362362 * performance impact and should be avoided when possible.
363363 */
@@ -371,7 +371,7 @@
371371
372372 /**
373373 * Adds the provided condition for the update.
374- * <p>
374+ * <p/>
375375 * Note that while the query builder accept any type of {@code Clause}
376376 * as conditions, Cassandra currently only allow equality ones.
377377 *
@@ -413,9 +413,9 @@
413413 public Options using(Using using) {
414414 return statement.using(using);
415415 }
416-
416+
417417 }
418-
418+
419419 public static class IfExists extends BuiltStatement.ForwardingStatement<Update> {
420420 IfExists(Update statement) {
421421 super(statement);
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java +2 −2
@@ -15,10 +15,10 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.util.List;
19-
2018 import com.datastax.driver.core.CodecRegistry;
2119
20+import java.util.List;
21+
2222 public abstract class Using extends Utils.Appendeable {
2323
2424 final String optionName;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +47 −45
@@ -15,6 +15,12 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.CodecRegistry;
19+import com.datastax.driver.core.ProtocolVersion;
20+import com.datastax.driver.core.Token;
21+import com.datastax.driver.core.TypeCodec;
22+import com.datastax.driver.core.exceptions.InvalidTypeException;
23+
1824 import java.math.BigDecimal;
1925 import java.math.BigInteger;
2026 import java.nio.ByteBuffer;
@@ -26,12 +32,6 @@
2632
2733 import static com.google.common.base.Preconditions.checkNotNull;
2834
29-import com.datastax.driver.core.CodecRegistry;
30-import com.datastax.driver.core.ProtocolVersion;
31-import com.datastax.driver.core.Token;
32-import com.datastax.driver.core.TypeCodec;
33-import com.datastax.driver.core.exceptions.InvalidTypeException;
34-
3535 // Static utilities private to the query builder
3636 abstract class Utils {
3737
@@ -70,7 +70,7 @@
7070 } else if (value instanceof BindMarker) {
7171 sb.append(value);
7272 } else if (value instanceof FCall) {
73- FCall fcall = (FCall)value;
73+ FCall fcall = (FCall) value;
7474 sb.append(fcall.name).append('(');
7575 for (int i = 0; i < fcall.parameters.length; i++) {
7676 if (i > 0)
@@ -79,18 +79,18 @@
7979 }
8080 sb.append(')');
8181 } else if (value instanceof CName) {
82- appendName(((CName)value).name, codecRegistry, sb);
82+ appendName(((CName) value).name, codecRegistry, sb);
8383 } else if (value instanceof RawString) {
8484 sb.append(value.toString());
85- } else if(value instanceof List && !isSerializable(value)) {
85+ } else if (value instanceof List && !isSerializable(value)) {
8686 // bind variables are not supported inside collection literals
87- appendList((List<?>)value, codecRegistry, sb, null);
88- } else if(value instanceof Set && !isSerializable(value)) {
87+ appendList((List<?>) value, codecRegistry, sb, null);
88+ } else if (value instanceof Set && !isSerializable(value)) {
8989 // bind variables are not supported inside collection literals
90- appendSet((Set<?>)value, codecRegistry, sb, null);
91- } else if(value instanceof Map && !isSerializable(value)) {
90+ appendSet((Set<?>) value, codecRegistry, sb, null);
91+ } else if (value instanceof Map && !isSerializable(value)) {
9292 // bind variables are not supported inside collection literals
93- appendMap((Map<?,?>)value, codecRegistry, sb, null);
93+ appendMap((Map<?, ?>) value, codecRegistry, sb, null);
9494 } else if (variables == null || !isSerializable(value)) {
9595 // we are not collecting statement values (variables == null)
9696 // or the value is meant to be forcefully appended to the query string:
@@ -123,7 +123,8 @@
123123 sb.append('{');
124124 boolean first = true;
125125 for (Object elt : s) {
126- if (first) first = false; else sb.append(',');
126+ if (first) first = false;
127+ else sb.append(',');
127128 appendValue(elt, codecRegistry, sb, variables);
128129 }
129130 sb.append('}');
@@ -150,15 +151,15 @@
150151 if (value instanceof BindMarker)
151152 return true;
152153 if (value instanceof FCall)
153- for (Object param : ((FCall)value).parameters)
154- if (containsBindMarker(param))
155- return true;
154+ for (Object param : ((FCall) value).parameters)
155+ if (containsBindMarker(param))
156+ return true;
156157 if (value instanceof Collection)
157- for (Object elt : (Collection)value)
158+ for (Object elt : (Collection) value)
158159 if (containsBindMarker(elt))
159160 return true;
160161 if (value instanceof Map)
161- for (Map.Entry<?,?> entry : ((Map<?,?>)value).entrySet())
162+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet())
162163 if (containsBindMarker(entry.getKey()) || containsBindMarker(entry.getValue()))
163164 return true;
164165 return false;
@@ -168,11 +169,11 @@
168169 if (value instanceof BindMarker || value instanceof FCall || value instanceof CName || value instanceof RawString)
169170 return true;
170171 if (value instanceof Collection)
171- for (Object elt : (Collection)value)
172+ for (Object elt : (Collection) value)
172173 if (containsSpecialValue(elt))
173174 return true;
174175 if (value instanceof Map)
175- for (Map.Entry<?,?> entry : ((Map<?,?>)value).entrySet())
176+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet())
176177 if (containsSpecialValue(entry.getKey()) || containsSpecialValue(entry.getValue()))
177178 return true;
178179 return false;
@@ -197,34 +198,34 @@
197198 if (value instanceof Number && !(value instanceof BigInteger || value instanceof BigDecimal))
198199 return false;
199200 if (value instanceof Collection)
200- for (Object elt : (Collection)value)
201+ for (Object elt : (Collection) value)
201202 if (!isSerializable(elt))
202203 return false;
203204 if (value instanceof Map)
204- for (Map.Entry<?,?> entry : ((Map<?,?>)value).entrySet())
205+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet())
205206 if (!isSerializable(entry.getKey()) || !isSerializable(entry.getValue()))
206207 return false;
207208 return true;
208209 }
209210
210211 static boolean isIdempotent(Object value) {
211- if(value == null) {
212+ if (value == null) {
212213 return true;
213214 } else if (value instanceof Assignment) {
214- Assignment assignment = (Assignment)value;
215+ Assignment assignment = (Assignment) value;
215216 return assignment.isIdempotent();
216217 } else if (value instanceof FCall) {
217218 return false;
218219 } else if (value instanceof RawString) {
219220 return false;
220- } else if(value instanceof Collection) {
221- for (Object elt : ((Collection)value)) {
222- if(!isIdempotent(elt))
221+ } else if (value instanceof Collection) {
222+ for (Object elt : ((Collection) value)) {
223+ if (!isIdempotent(elt))
223224 return false;
224225 }
225226 return true;
226227 } else if (value instanceof Map) {
227- for (Map.Entry<?, ?> entry : ((Map<?, ?>)value).entrySet()) {
228+ for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
228229 if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue()))
229230 return false;
230231 }
@@ -244,11 +245,11 @@
244245
245246 static StringBuilder appendName(Object name, CodecRegistry codecRegistry, StringBuilder sb) {
246247 if (name instanceof String) {
247- appendName((String)name, sb);
248+ appendName((String) name, sb);
248249 } else if (name instanceof CName) {
249- appendName(((CName)name).name, codecRegistry, sb);
250+ appendName(((CName) name).name, codecRegistry, sb);
250251 } else if (name instanceof FCall) {
251- FCall fcall = (FCall)name;
252+ FCall fcall = (FCall) name;
252253 sb.append(fcall.name).append('(');
253254 for (int i = 0; i < fcall.parameters.length; i++) {
254255 if (i > 0)
@@ -257,11 +258,11 @@
257258 }
258259 sb.append(')');
259260 } else if (name instanceof Alias) {
260- Alias alias = (Alias)name;
261+ Alias alias = (Alias) name;
261262 appendName(alias.column, codecRegistry, sb);
262263 sb.append(" AS ").append(alias.alias);
263264 } else if (name instanceof RawString) {
264- sb.append(((RawString)name).str);
265+ sb.append(((RawString) name).str);
265266 } else {
266267 throw new IllegalArgumentException(String.format("Invalid column %s of type unknown of the query builder", name));
267268 }
@@ -270,23 +271,23 @@
270271
271272 /**
272273 * This method is a copy of the one declared in {@link com.datastax.driver.core.SimpleStatement}.
273- * <p>
274+ * <p/>
274275 * Utility method to serialize user-provided values.
275- * <p>
276+ * <p/>
276277 * This method is useful in situations where there is no metadata available and the underlying CQL
277278 * type for the values is not known.
278- * <p>
279+ * <p/>
279280 * This situation happens when a {@link com.datastax.driver.core.SimpleStatement}
280281 * or a {@link com.datastax.driver.core.querybuilder.BuiltStatement} (Query Builder) contain values;
281282 * in these places, the driver has no way to determine the right CQL type to use.
282- * <p>
283+ * <p/>
283284 * This method performs a best-effort heuristic to guess which codec to use.
284285 * Note that this is not particularly efficient as the codec registry needs to iterate over
285286 * the registered codecs until it finds a suitable one.
286287 *
287- * @param values The values to convert.
288+ * @param values The values to convert.
288289 * @param protocolVersion The protocol version to use.
289- * @param codecRegistry The {@link CodecRegistry} to use.
290+ * @param codecRegistry The {@link CodecRegistry} to use.
290291 * @return The converted values.
291292 */
292293 public static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
@@ -300,7 +301,7 @@
300301 } else {
301302 if (value instanceof Token) {
302303 // bypass CodecRegistry for Token instances
303- serializedValues[i] = ((Token)value).serialize(protocolVersion);
304+ serializedValues[i] = ((Token) value).serialize(protocolVersion);
304305 } else {
305306 try {
306307 TypeCodec<Object> codec = codecRegistry.codecFor(value);
@@ -336,19 +337,20 @@
336337 ByteBuffer bb = buffer.duplicate();
337338 putShortLength(out, bb.remaining());
338339 out.put(bb);
339- out.put((byte)0);
340+ out.put((byte) 0);
340341 }
341342 out.flip();
342343 return out;
343344 }
344345
345346 static void putShortLength(ByteBuffer bb, int length) {
346- bb.put((byte)((length >> 8) & 0xFF));
347- bb.put((byte)(length & 0xFF));
347+ bb.put((byte) ((length >> 8) & 0xFF));
348+ bb.put((byte) (length & 0xFF));
348349 }
349350
350351 static abstract class Appendeable {
351352 abstract void appendTo(StringBuilder sb, List<Object> values, CodecRegistry codecRegistry);
353+
352354 abstract boolean containsBindMarker();
353355 }
354356
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/package-info.java +1 −1
@@ -15,7 +15,7 @@
1515 */
1616 /**
1717 * A CQL3 query builder.
18- * <p>
18+ * <p/>
1919 * The main entry for this package is the {@code QueryBuilder} class.
2020 */
2121 package com.datastax.driver.core.querybuilder;
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AbstractCreateStatement.java +23 −25
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import java.util.LinkedHashMap;
19-import java.util.Map;
20-
18+import com.datastax.driver.core.DataType;
2119 import com.google.common.base.Optional;
2220
23-import com.datastax.driver.core.DataType;
21+import java.util.LinkedHashMap;
22+import java.util.Map;
2423
2524 public abstract class AbstractCreateStatement<T extends AbstractCreateStatement<T>> extends SchemaStatement {
2625
@@ -29,7 +28,7 @@
2928 protected Map<String, ColumnType> simpleColumns = new LinkedHashMap<String, ColumnType>();
3029
3130 @SuppressWarnings("unchecked")
32- private T self = (T)this;
31+ private T self = (T) this;
3332
3433 /**
3534 * Add the 'IF NOT EXISTS' condition to this CREATE statement.
@@ -43,25 +42,25 @@
4342
4443 /**
4544 * Add a column definition to this CREATE statement.
46- *
47- * <p>
45+ * <p/>
46+ * <p/>
4847 * To add a list column:
4948 * <pre class="code"><code class="java">
50- * addColumn("myList",DataType.list(DataType.text()))
49+ * addColumn("myList",DataType.list(DataType.text()))
5150 * </code></pre>
52- *
51+ * <p/>
5352 * To add a set column:
5453 * <pre class="code"><code class="java">
55- * addColumn("mySet",DataType.set(DataType.text()))
54+ * addColumn("mySet",DataType.set(DataType.text()))
5655 * </code></pre>
57- *
56+ * <p/>
5857 * To add a map column:
5958 * <pre class="code"><code class="java">
60- * addColumn("myMap",DataType.map(DataType.cint(),DataType.text()))
59+ * addColumn("myMap",DataType.map(DataType.cint(),DataType.text()))
6160 * </code></pre>
6261 *
6362 * @param columnName the name of the column to be added.
64- * @param dataType the data type of the column to be added.
63+ * @param dataType the data type of the column to be added.
6564 * @return this CREATE statement.
6665 */
6766 public T addColumn(String columnName, DataType dataType) {
@@ -76,7 +75,7 @@
7675 * Add a column definition to this CREATE statement, when the type contains a UDT.
7776 *
7877 * @param columnName the name of the column to be added.
79- * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
78+ * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
8079 * @return this CREATE statement.
8180 */
8281 public T addUDTColumn(String columnName, UDTType udtType) {
@@ -91,7 +90,7 @@
9190 * Shorthand to add a column definition to this CREATE statement, when the type is a list of UDT.
9291 *
9392 * @param columnName the name of the column to be added
94- * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
93+ * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
9594 * @return this CREATE statement.
9695 */
9796 public T addUDTListColumn(String columnName, UDTType udtType) {
@@ -106,7 +105,7 @@
106105 * Shorthand to add a column definition to this CREATE statement, when the type is a set of UDT.
107106 *
108107 * @param columnName the name of the column to be added
109- * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
108+ * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
110109 * @return this CREATE statement.
111110 */
112111 public T addUDTSetColumn(String columnName, UDTType udtType) {
@@ -119,14 +118,14 @@
119118
120119 /**
121120 * Shorthand to add a column definition to this CREATE statement, when the type is a map with a UDT value type.
122- * <p>
121+ * <p/>
123122 * Example:
124123 * <pre>
125124 * addUDTMapColumn("addresses", DataType.text(), frozen("address"));
126125 * </pre>
127126 *
128- * @param columnName the name of the column to be added.
129- * @param keyType the key type of the column to be added.
127+ * @param columnName the name of the column to be added.
128+ * @param keyType the key type of the column to be added.
130129 * @param valueUdtType the value UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
131130 * @return this CREATE statement.
132131 */
@@ -141,7 +140,7 @@
141140
142141 /**
143142 * Shorthand to add a column definition to this CREATE statement, when the type is a map with a UDT key type.
144- * <p>
143+ * <p/>
145144 * Example:
146145 * <pre>
147146 * addUDTMapColumn("roles", frozen("user"), DataType.text());
@@ -149,7 +148,7 @@
149148 *
150149 * @param columnName the name of the column to be added.
151150 * @param udtKeyType the key UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
152- * @param valueType the value raw type of the column to be added.
151+ * @param valueType the value raw type of the column to be added.
153152 * @return this CREATE statement.
154153 */
155154 public T addUDTMapColumn(String columnName, UDTType udtKeyType, DataType valueType) {
@@ -163,17 +162,16 @@
163162
164163 /**
165164 * Shorthand to add a column definition to this CREATE statement, when the type is a map with UDT key and value types.
166- * <p>
165+ * <p/>
167166 * Example:
168167 * <pre>
169168 * addUDTMapColumn("users", frozen("user"), frozen("address"));
170169 * </pre>
171170 *
172- * @param columnName the name of the column to be added.
173- * @param udtKeyType the key UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
171+ * @param columnName the name of the column to be added.
172+ * @param udtKeyType the key UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
174173 * @param udtValueType the value UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
175174 * @return this CREATE statement.
176- *
177175 */
178176 public T addUDTMapColumn(String columnName, UDTType udtKeyType, UDTType udtValueType) {
179177 validateNotEmpty(columnName, "Column name");
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Alter.java +15 −16
@@ -15,11 +15,10 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import java.util.List;
19-
18+import com.datastax.driver.core.DataType;
2019 import com.google.common.base.Optional;
2120
22-import com.datastax.driver.core.DataType;
21+import java.util.List;
2322
2423 import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotEmpty;
2524 import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotKeyWord;
@@ -49,7 +48,7 @@
4948
5049 /**
5150 * Add an ALTER column clause (to change the column type) to this ALTER TABLE statement.
52-
51+ *
5352 * @param columnName the name of the column to be altered.
5453 * @return a new {@link Alter.AlterColumn} instance.
5554 */
@@ -85,9 +84,9 @@
8584
8685 /**
8786 * Add a new DROP column clause to this ALTER TABLE statement.
88- * <p>
87+ * <p/>
8988 * Note that you cannot drop a column that is part of the primary key.
90-
89+ *
9190 * @param columnName the name of the column to be dropped.
9291 * @return the final ALTER TABLE DROP COLUMN statement.
9392 */
@@ -99,7 +98,7 @@
9998
10099 /**
101100 * Add a new RENAME column clause to this ALTER TABLE statement.
102- * <p>
101+ * <p/>
103102 * Note that you can only rename a column that is part of the primary key.
104103 *
105104 * @param columnName the name of the column to be renamed.
@@ -141,7 +140,7 @@
141140 */
142141 public SchemaStatement type(DataType type) {
143142 return SchemaStatement.fromQueryString(
144- alter.buildInternal() + " ALTER " + columnName + " TYPE " + type.toString());
143+ alter.buildInternal() + " ALTER " + columnName + " TYPE " + type.toString());
145144 }
146145
147146 /**
@@ -152,7 +151,7 @@
152151 */
153152 public SchemaStatement udtType(UDTType udtType) {
154153 return SchemaStatement.fromQueryString(
155- alter.buildInternal() + " ALTER " + columnName + " TYPE " + udtType.asCQLString());
154+ alter.buildInternal() + " ALTER " + columnName + " TYPE " + udtType.asCQLString());
156155 }
157156 }
158157
@@ -179,8 +178,8 @@
179178 */
180179 public SchemaStatement type(DataType type) {
181180 return SchemaStatement.fromQueryString(
182- alter.buildInternal() + " ADD " + columnName + " " + type.toString()
183- + (staticColumn ? " static" : ""));
181+ alter.buildInternal() + " ADD " + columnName + " " + type.toString()
182+ + (staticColumn ? " static" : ""));
184183 }
185184
186185 /**
@@ -191,8 +190,8 @@
191190 */
192191 public SchemaStatement udtType(UDTType udtType) {
193192 return SchemaStatement.fromQueryString(
194- alter.buildInternal() + " ADD " + columnName + " " + udtType.asCQLString()
195- + (staticColumn ? " static" : ""));
193+ alter.buildInternal() + " ADD " + columnName + " " + udtType.asCQLString()
194+ + (staticColumn ? " static" : ""));
196195 }
197196 }
198197
@@ -219,7 +218,7 @@
219218 validateNotEmpty(newColumnName, "New column name");
220219 validateNotKeyWord(newColumnName, String.format("The new column name '%s' is not allowed because it is a reserved keyword", newColumnName));
221220 return SchemaStatement.fromQueryString(
222- alter.buildInternal() + " RENAME " + columnName + " TO " + newColumnName);
221+ alter.buildInternal() + " RENAME " + columnName + " TO " + newColumnName);
223222 }
224223 }
225224
@@ -241,8 +240,8 @@
241240 @Override
242241 public String buildInternal() {
243242 String tableSpec = keyspaceName.isPresent()
244- ? keyspaceName.get() + "." + tableName
245- : tableName;
243+ ? keyspaceName.get() + "." + tableName
244+ : tableName;
246245
247246 return SchemaStatement.STATEMENT_START + "ALTER TABLE " + tableSpec;
248247 }
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/ColumnType.java +1 −3
@@ -15,11 +15,9 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import com.datastax.driver.core.DataType;
19-
2018 /**
2119 * Wrapper around UDT and non-UDT types.
22- * <p>
20+ * <p/>
2321 * The reason for this interface is that the core API doesn't let us build {@link com.datastax.driver.core.DataType}s representing UDTs, we have to obtain
2422 * them from the cluster metadata. Since we want to use SchemaBuilder without a Cluster instance, UDT types will be provided via
2523 * {@link UDTType} instances.
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Create.java +25 −26
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import java.util.*;
19-
20-import static java.util.Map.Entry;
21-
18+import com.datastax.driver.core.DataType;
2219 import com.google.common.base.Joiner;
2320 import com.google.common.base.Objects;
2421 import com.google.common.base.Optional;
2522 import com.google.common.collect.Lists;
2623
27-import com.datastax.driver.core.DataType;
24+import java.util.*;
25+
26+import static java.util.Map.Entry;
2827
2928 /**
3029 * A built CREATE TABLE statement.
@@ -53,13 +52,13 @@
5352
5453 /**
5554 * Add a partition key column definition to this CREATE TABLE statement.
56- * <p>
55+ * <p/>
5756 * This includes the column declaration (you don't need an additional {@code addColumn} call).
58- * <p>
57+ * <p/>
5958 * Partition key columns are added in the order of their declaration.
6059 *
6160 * @param columnName the name of the partition key column to be added.
62- * @param dataType the data type of the partition key column to be added.
61+ * @param dataType the data type of the partition key column to be added.
6362 * @return this CREATE statement.
6463 */
6564 public Create addPartitionKey(String columnName, DataType dataType) {
@@ -72,13 +71,13 @@
7271
7372 /**
7473 * Add a partition key column definition to this CREATE TABLE statement, when its type contains a UDT.
75- * <p>
74+ * <p/>
7675 * This includes the column declaration (you don't need an additional {@code addColumn} call).
77- * <p>
76+ * <p/>
7877 * Partition key columns are added in the order of their declaration.
7978 *
8079 * @param columnName the name of the partition key column to be added.
81- * @param udtType the UDT type of the partition key column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
80+ * @param udtType the UDT type of the partition key column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
8281 * @return this CREATE statement.
8382 */
8483 public Create addUDTPartitionKey(String columnName, UDTType udtType) {
@@ -91,13 +90,13 @@
9190
9291 /**
9392 * Add a clustering column definition to this CREATE TABLE statement.
94- * <p>
93+ * <p/>
9594 * This includes the column declaration (you don't need an additional {@code addColumn} call).
96- * <p>
95+ * <p/>
9796 * Clustering columns are added in the order of their declaration.
9897 *
9998 * @param columnName the name of the clustering column to be added.
100- * @param dataType the data type of the clustering column to be added.
99+ * @param dataType the data type of the clustering column to be added.
101100 * @return this CREATE statement.
102101 */
103102 public Create addClusteringColumn(String columnName, DataType dataType) {
@@ -110,13 +109,13 @@
110109
111110 /**
112111 * Add a clustering column definition to this CREATE TABLE statement, when its type contains a UDT.
113- * <p>
112+ * <p/>
114113 * This includes the column declaration (you don't need an additional {@code addColumn} call).
115- * <p>
114+ * <p/>
116115 * Clustering columns are added in the order of their declaration.
117116 *
118117 * @param columnName the name of the clustering column to be added.
119- * @param udtType the UDT type of the clustering column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
118+ * @param udtType the UDT type of the clustering column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
120119 * @return this CREATE statement.
121120 */
122121 public Create addUDTClusteringColumn(String columnName, UDTType udtType) {
@@ -131,7 +130,7 @@
131130 * Add a static column definition to this CREATE TABLE statement.
132131 *
133132 * @param columnName the name of the column to be added.
134- * @param dataType the data type of the column to be added.
133+ * @param dataType the data type of the column to be added.
135134 * @return this CREATE statement.
136135 */
137136 public Create addStaticColumn(String columnName, DataType dataType) {
@@ -146,7 +145,7 @@
146145 * Add a static column definition to this CREATE TABLE statement, when its type contains a UDT.
147146 *
148147 * @param columnName the name of the column to be added.
149- * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
148+ * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
150149 * @return this CREATE statement.
151150 */
152151 public Create addUDTStaticColumn(String columnName, UDTType udtType) {
@@ -184,11 +183,11 @@
184183
185184 /**
186185 * Add a clustering order for this table.
187- * <p>
186+ * <p/>
188187 * To define the order on multiple columns, call this method repeatedly. The columns will be declared in the call order.
189188 *
190189 * @param columnName the clustering column name.
191- * @param direction the clustering direction (DESC/ASC).
190+ * @param direction the clustering direction (DESC/ASC).
192191 * @return this {@code Options} object.
193192 */
194193 public Options clusteringOrder(String columnName, SchemaBuilder.Direction direction) {
@@ -238,7 +237,7 @@
238237 return true;
239238 }
240239 if (o instanceof ClusteringOrder) {
241- ClusteringOrder that = (ClusteringOrder)o;
240+ ClusteringOrder that = (ClusteringOrder) o;
242241 return Objects.equal(this.clusteringColumnName, that.clusteringColumnName) && Objects.equal(this.direction, that.direction);
243242 }
244243 return false;
@@ -306,12 +305,12 @@
306305 }
307306
308307 String partitionKeyPart = partitionKeyColumns.size() == 1 ?
309- partitionKeyColumns.get(0)
310- : "(" + Joiner.on(", ").join(partitionKeyColumns) + ")";
308+ partitionKeyColumns.get(0)
309+ : "(" + Joiner.on(", ").join(partitionKeyColumns) + ")";
311310
312311 String primaryKeyPart = clusteringKeyColumns.size() == 0 ?
313- partitionKeyPart
314- : partitionKeyPart + ", " + Joiner.on(", ").join(clusteringKeyColumns);
312+ partitionKeyPart
313+ : partitionKeyPart + ", " + Joiner.on(", ").join(clusteringKeyColumns);
315314
316315 createStatement.append("(").append(COLUMN_FORMATTING);
317316 createStatement.append(Joiner.on("," + COLUMN_FORMATTING).join(allColumns));
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateIndex.java +3 −4
@@ -17,9 +17,7 @@
1717
1818 import com.google.common.base.Optional;
1919
20-import static com.datastax.driver.core.schemabuilder.SchemaStatement.STATEMENT_START;
21-import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotEmpty;
22-import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotKeyWord;
20+import static com.datastax.driver.core.schemabuilder.SchemaStatement.*;
2321
2422 /**
2523 * A built CREATE INDEX statement.
@@ -53,7 +51,7 @@
5351 * Specify the keyspace and table to create the index on.
5452 *
5553 * @param keyspaceName the keyspace name.
56- * @param tableName the table name.
54+ * @param tableName the table name.
5755 * @return a {@link CreateIndexOn} that will allow the specification of the column.
5856 */
5957 public CreateIndexOn onTable(String keyspaceName, String tableName) {
@@ -95,6 +93,7 @@
9593
9694 /**
9795 * Create an index on the keys of the given map column.
96+ *
9897 * @param columnName the column name.
9998 * @return the final CREATE INDEX statement.
10099 */
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateType.java +4 −3
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18+import com.google.common.base.Joiner;
19+import com.google.common.base.Optional;
20+
1821 import java.util.ArrayList;
1922 import java.util.List;
2023 import java.util.Map;
2124
22-import com.google.common.base.Joiner;
23-import com.google.common.base.Optional;
24-
2525 /**
2626 * A built CREATE TYPE statement.
2727 */
@@ -46,6 +46,7 @@
4646
4747 /**
4848 * Generate the script for custom type creation
49+ *
4950 * @return a CREATE TYPE statement
5051 */
5152 public String build() {
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Drop.java +1 −0
@@ -72,6 +72,7 @@
7272
7373 /**
7474 * Generate a DROP TABLE statement
75+ *
7576 * @return the final DROP TABLE statement
7677 */
7778 public String build() {
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/NativeColumnType.java +2 −1
@@ -27,7 +27,8 @@
2727 asCQLString = nativeType.toString();
2828 }
2929
30- @Override public String asCQLString() {
30+ @Override
31+ public String asCQLString() {
3132 return asCQLString;
3233 }
3334 }
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaBuilder.java +14 −13
@@ -19,16 +19,17 @@
1919
2020 /**
2121 * Static methods to build a CQL3 DDL statement.
22- * <p>
22+ * <p/>
2323 * The provided builders perform very little validation of the built query.
2424 * There is thus no guarantee that a built query is valid, and it is
2525 * definitively possible to create invalid queries.
26- * <p>
26+ * <p/>
2727 * Note that it could be convenient to use an 'import static' to use the methods of this class.
2828 */
2929 public final class SchemaBuilder {
3030
31- private SchemaBuilder() {}
31+ private SchemaBuilder() {
32+ }
3233
3334 /**
3435 * Start building a new CREATE TABLE statement.
@@ -44,7 +45,7 @@
4445 * Start building a new CREATE TABLE statement.
4546 *
4647 * @param keyspaceName the name of the keyspace to be used.
47- * @param tableName the name of the table to create.
48+ * @param tableName the name of the table to create.
4849 * @return an in-construction CREATE TABLE statement.
4950 */
5051 public static Create createTable(String keyspaceName, String tableName) {
@@ -65,7 +66,7 @@
6566 * Start building a new ALTER TABLE statement.
6667 *
6768 * @param keyspaceName the name of the keyspace to be used.
68- * @param tableName the name of the table to be altered.
69+ * @param tableName the name of the table to be altered.
6970 * @return an in-construction ALTER TABLE statement.
7071 */
7172 public static Alter alterTable(String keyspaceName, String tableName) {
@@ -86,7 +87,7 @@
8687 * Start building a new DROP TABLE statement.
8788 *
8889 * @param keyspaceName the name of the keyspace to be used.
89- * @param tableName the name of the table to be dropped.
90+ * @param tableName the name of the table to be dropped.
9091 * @return an in-construction DROP TABLE statement.
9192 */
9293 public static Drop dropTable(String keyspaceName, String tableName) {
@@ -117,7 +118,7 @@
117118 * Start building a new DROP INDEX statement.
118119 *
119120 * @param keyspaceName the name of the keyspace to be used.
120- * @param indexName the name of the index to be dropped.
121+ * @param indexName the name of the index to be dropped.
121122 * @return an in-construction DROP INDEX statement.
122123 */
123124 public static Drop dropIndex(String keyspaceName, String indexName) {
@@ -138,7 +139,7 @@
138139 * Start building a new CREATE TYPE statement.
139140 *
140141 * @param keyspaceName the name of the keyspace to be used.
141- * @param typeName the name of the custom type to create.
142+ * @param typeName the name of the custom type to create.
142143 * @return an in-construction CREATE TYPE statement.
143144 */
144145 public static CreateType createType(String keyspaceName, String typeName) {
@@ -159,7 +160,7 @@
159160 * Start building a new DROP TYPE statement.
160161 *
161162 * @param keyspaceName the name of the keyspace to be used.
162- * @param typeName the name of the type to be dropped.
163+ * @param typeName the name of the type to be dropped.
163164 * @return an in-construction DROP TYPE statement.
164165 */
165166 public static Drop dropType(String keyspaceName, String typeName) {
@@ -172,7 +173,7 @@
172173
173174 /**
174175 * Build the datatype representation of a frozen UDT, to include in a schema builder statement.
175- * <p>
176+ * <p/>
176177 * <code>frozen("foo")</code> will produce <code>frozen&lt;foo&gt;</code>.
177178 *
178179 * @param udtName the name of the UDT.
@@ -184,7 +185,7 @@
184185
185186 /**
186187 * Build the datatype representation of a complex UDT type, to include in a schema builder statement.
187- * <p>
188+ * <p/>
188189 * As of Cassandra 2.1, this method is not strictly necessary because {@link Create} and {@link Alter}
189190 * provide specialized methods to express simple collections of UDTs, but future versions will make it
190191 * possible to use types such as <code>map&lt;text, map&lt;text, frozen&lt;user&gt;&gt;&gt;</code>.
@@ -216,7 +217,7 @@
216217
217218 /**
218219 * Create options for the date-tiered compaction strategy, to use in a CREATE or ALTER TABLE statement.
219- * <p>
220+ * <p/>
220221 * This strategy was introduced in Cassandra 2.1.1.
221222 *
222223 * @return the options.
@@ -357,7 +358,7 @@
357358
358359 /**
359360 * Return the row caching strategy that caches all rows ({@code all}), to use in a CREATE or ALTER TABLE statement.
360- * <p>
361+ * <p/>
361362 * <strong>Be careful when choosing this option, you can starve Cassandra memory quickly if your partition is very large.</strong>
362363 *
363364 * @return the strategy.
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +14 −13
@@ -15,15 +15,14 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Arrays;
20-import java.util.List;
21-
22-import com.google.common.base.Strings;
23-
2418 import com.datastax.driver.core.CodecRegistry;
2519 import com.datastax.driver.core.ProtocolVersion;
2620 import com.datastax.driver.core.RegularStatement;
21+import com.google.common.base.Strings;
22+
23+import java.nio.ByteBuffer;
24+import java.util.Arrays;
25+import java.util.List;
2726
2827 /**
2928 * A DDL statement generated by {@link SchemaBuilder}.
@@ -34,10 +33,10 @@
3433 static final String COLUMN_FORMATTING = "\n\t\t";
3534
3635 static final List<String> RESERVED_KEYWORDS = Arrays.asList(
37- ("add,allow,alter,and,any,apply,asc,authorize,batch,begin,by,columnfamily,create,delete,desc,drop,each_quorum,from,grant,in,index,inet,infinity," +
38- "insert,into,keyspace,keyspaces,limit,local_one,local_quorum,modify,nan,norecursive,of,on,order,password,primary,quorum,rename,revoke,schema," +
39- "select,set,table,three,to,token,truncate,two,unlogged,update,use,using,where,with")
40- .split(","));
36+ ("add,allow,alter,and,any,apply,asc,authorize,batch,begin,by,columnfamily,create,delete,desc,drop,each_quorum,from,grant,in,index,inet,infinity," +
37+ "insert,into,keyspace,keyspaces,limit,local_one,local_quorum,modify,nan,norecursive,of,on,order,password,primary,quorum,rename,revoke,schema," +
38+ "select,set,table,three,to,token,truncate,two,unlogged,update,use,using,where,with")
39+ .split(","));
4140
4241 private volatile String cache;
4342
@@ -73,7 +72,7 @@
7372 * {@inheritDoc}
7473 *
7574 * @param protocolVersion unused by this implementation (the key is always null for schema statements).
76- * @param codecRegistry unused by this implementation (the key is always null for schema statements).
75+ * @param codecRegistry unused by this implementation (the key is always null for schema statements).
7776 */
7877 @Override
7978 public ByteBuffer getRoutingKey(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
@@ -100,7 +99,8 @@
10099
101100 static SchemaStatement fromQueryString(final String queryString) {
102101 return new SchemaStatement() {
103- @Override public String buildInternal() {
102+ @Override
103+ public String buildInternal() {
104104 return queryString;
105105 }
106106 };
@@ -108,7 +108,8 @@
108108
109109 StatementStart asStatementStart() {
110110 return new StatementStart() {
111- @Override public String buildInternal() {
111+ @Override
112+ public String buildInternal() {
112113 return SchemaStatement.this.buildInternal();
113114 }
114115 };
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/TableOptions.java +78 −82
@@ -15,21 +15,20 @@
1515 */
1616 package com.datastax.driver.core.schemabuilder;
1717
18-import java.util.ArrayList;
19-import java.util.List;
20-
2118 import com.google.common.base.Joiner;
2219 import com.google.common.base.Optional;
2320 import com.google.common.base.Strings;
2421
22+import java.util.ArrayList;
23+import java.util.List;
24+
2525 /**
2626 * The table options used in a CREATE TABLE or ALTER TABLE statement.
27- * <p>
27+ * <p/>
2828 * Implementation notes: this class is abstract and not meant to use directly.
2929 * The type parameter {@code T} allows usage of <strong>covariant return type</strong> and makes the builder pattern work for different sub-classes.
3030 *
3131 * @param <T> the concrete sub-class of {@link com.datastax.driver.core.schemabuilder.TableOptions}
32- *
3332 * @see <a href="http://docs.datastax.com/en/cql/3.1/cql/cql_reference/tabProp.html" target="_blank">details on table options</a>
3433 */
3534 public abstract class TableOptions<T extends TableOptions> extends SchemaStatement {
@@ -71,15 +70,15 @@
7170 private List<String> customOptions = new ArrayList<String>();
7271
7372 @SuppressWarnings("unchecked")
74- private final T self = (T)this;
73+ private final T self = (T) this;
7574
76- TableOptions(StatementStart statementStart) {
75+ TableOptions(StatementStart statementStart) {
7776 this.statementStart = statementStart;
7877 }
7978
8079 /**
8180 * Define the caching type for Cassandra 2.0.x.
82- * <p>
81+ * <p/>
8382 * If no call is made to this method, the default value set by Cassandra is {@link SchemaBuilder.Caching#KEYS_ONLY}.
8483 *
8584 * @param caching the caching type (all enum values are allowed).
@@ -92,11 +91,11 @@
9291
9392 /**
9493 * Define the caching options for Cassandra 2.1.x.
95- * <p>
94+ * <p/>
9695 * If no call is made to this method, the default values set by Cassandra are keys = {@link SchemaBuilder.Caching#ALL} and
9796 * rows_per_partition = {@link com.datastax.driver.core.schemabuilder.SchemaBuilder#noRows()}.
98-
99- * @param keys the key cache type.
97+ *
98+ * @param keys the key cache type.
10099 * @param rowsPerPartition defines the number of rows to be cached per partition when Row Caching is enabled.
101100 * To create instances, use
102101 * {@link SchemaBuilder#noRows()},
@@ -112,11 +111,11 @@
112111
113112 /**
114113 * Define the desired false-positive probability for SSTable Bloom filters.
115- * <p>
114+ * <p/>
116115 * If no call is made to this method, the default value set by Cassandra is:
117116 * <ul>
118- * <li><strong>0.01</strong> for the size-tiered compaction strategy;</li>
119- * <li><strong>0.1</strong> for the leveled compaction strategy.</li>
117+ * <li><strong>0.01</strong> for the size-tiered compaction strategy;</li>
118+ * <li><strong>0.1</strong> for the leveled compaction strategy.</li>
120119 * </ul>
121120 *
122121 * @param fpChance the false positive change. This value should be between 0 and 1.0.
@@ -141,7 +140,7 @@
141140
142141 /**
143142 * Define the compression options.
144- * <p>
143+ * <p/>
145144 * If no call is made to this method, the default value set by Cassandra is {@link SchemaBuilder#lz4()}.
146145 *
147146 * @param compressionOptions the compression options. To create instances, use
@@ -158,7 +157,7 @@
158157
159158 /**
160159 * Define the compaction options.
161- * <p>
160+ * <p/>
162161 * If no call is made to this method, the default value set by Cassandra is {@link SchemaBuilder#sizedTieredStategy()}.
163162 *
164163 * @param compactionOptions the compaction options. To create instances, use
@@ -174,7 +173,7 @@
174173
175174 /**
176175 * Define the probability of read repairs being invoked over all replicas in the current data center.
177- * <p>
176+ * <p/>
178177 * If no call is made to this method, the default value set by Cassandra is 0.0.
179178 *
180179 * @param dcLocalReadRepairChance the probability.
@@ -188,10 +187,10 @@
188187
189188 /**
190189 * Define the default expiration time in seconds for a table.
191- *
192- * <p>
190+ * <p/>
191+ * <p/>
193192 * Used in MapReduce/Hive scenarios when you have no control of TTL.
194- * <p>
193+ * <p/>
195194 * If no call is made to this method, the default value set by Cassandra is 0.
196195 *
197196 * @param defaultTimeToLive the default time to live in seconds for a table.
@@ -204,10 +203,10 @@
204203
205204 /**
206205 * Define the time to wait before garbage collecting tombstones (deletion markers).
207- *
206+ * <p/>
208207 * The default value allows a great deal of time for consistency to be achieved prior to deletion.
209208 * In many deployments this interval can be reduced, and in a single-node cluster it can be safely set to zero.
210- * <p>
209+ * <p/>
211210 * If no call is made to this method, the default value set by Cassandra is 864000 secs (10 days).
212211 *
213212 * @param gcGraceSeconds the grace period.
@@ -220,7 +219,7 @@
220219
221220 /**
222221 * Define the index interval for Cassandra 2.0.
223- *
222+ * <p/>
224223 * To control the sampling of entries from the primary row index, configure sample frequency of the partition summary by changing the index interval.
225224 * After changing the index interval, SSTables are written to disk with new information. The interval corresponds to the number of index entries that
226225 * are skipped between taking each sample. By default, Cassandra samples one row key out of every 128. The larger the interval, the smaller and less
@@ -228,7 +227,7 @@
228227 * best trade off between memory usage and performance is a value between 128 and 512 in combination with a large table key cache. However, if you have
229228 * small rows (many to an OS page), you may want to increase the sample size, which often lowers memory usage without an impact on performance. For
230229 * large rows, decreasing the sample size may improve read performance.
231- * <p>
230+ * <p/>
232231 * If no call is made to this method, the default value set by Cassandra is 128.
233232 *
234233 * @param indexInterval the index interval.
@@ -241,12 +240,11 @@
241240
242241 /**
243242 * Define the minimum index interval for Cassandra 2.1.
244- * <p>
243+ * <p/>
245244 * If no call is made to this method, the default value set by Cassandra is 128.
246245 *
247246 * @param minIndexInterval the minimum index interval.
248247 * @return this {@code TableOptions} object.
249- *
250248 * @see #indexInterval(Integer)
251249 */
252250 public T minIndexInterval(Integer minIndexInterval) {
@@ -256,12 +254,11 @@
256254
257255 /**
258256 * Define the maximum index interval for Cassandra 2.1.
259- * <p>
257+ * <p/>
260258 * If no call is made to this method, the default value set by Cassandra is 2048.
261259 *
262260 * @param maxIndexInterval the maximum index interval.
263261 * @return this {@code TableOptions} object.
264- *
265262 * @see #indexInterval(Integer)
266263 */
267264 public T maxIndexInterval(Integer maxIndexInterval) {
@@ -271,9 +268,9 @@
271268
272269 /**
273270 * Define the memtable flush period.
274- *
271+ * <p/>
275272 * If set, this forces flushing of the memtable after the specified time elapses.
276- * <p>
273+ * <p/>
277274 * If no call is made to this method, the default value set by Cassandra is 0.
278275 *
279276 * @param memtableFlushPeriodInMillis the memtable flush period in milliseconds.
@@ -286,15 +283,14 @@
286283
287284 /**
288285 * Define whether to populate IO cache on flush of sstables.
289- *
286+ * <p/>
290287 * If set, Cassandra adds newly flushed or compacted sstables to the operating system page cache, potentially evicting other cached data to make room.
291288 * Enable when all data in the table is expected to fit in memory.
292- * <p>
289+ * <p/>
293290 * If no call is made to this method, the default value set by Cassandra is {@code false}.
294291 *
295292 * @param populateIOOnCacheFlush whether to populate IO cache on flush of sstables.
296293 * @return this {@code TableOptions} object.
297- *
298294 * @see <a href="http://docs.datastax.com/en/cassandra/2.0/cassandra/configuration/configCassandra_yaml_r.html?scroll=reference_ds_qfg_n1r_1k__compaction_preheat_key_cache">the global option compaction_preheat_key_cache</a>
299295 */
300296 public T populateIOCacheOnFlush(Boolean populateIOOnCacheFlush) {
@@ -304,7 +300,7 @@
304300
305301 /**
306302 * Define the probability with which read repairs should be invoked on non-quorum reads. The value must be between 0 and 1.
307- * <p>
303+ * <p/>
308304 * If no call is made to this method, the default value set by Cassandra is 0.1.
309305 *
310306 * @param readRepairChance the read repair chance.
@@ -318,10 +314,10 @@
318314
319315 /**
320316 * Define whether to replicate data on write (Cassandra 2.0.x only).
321- *
317+ * <p/>
322318 * When set to {@code true}, replicates writes to all affected replicas regardless of the consistency level specified by the client for a write request.
323319 * For counter tables, this should always be set to {@code true}.
324- * <p>
320+ * <p/>
325321 * If no call is made to this method, the default value set by Cassandra is {@code true}.
326322 *
327323 * @param replicateOnWrite whether to replicate data on write.
@@ -336,17 +332,17 @@
336332 * To override normal read timeout when read_repair_chance is not 1.0, sending another request to read, choose one of these values and use the property to create
337333 * or alter the table:
338334 * <ul>
339- * <li>ALWAYS: Retry reads of all replicas.</li>
340- * <li>Xpercentile: Retry reads based on the effect on throughput and latency.</li>
341- * <li>Yms: Retry reads after specified milliseconds.</li>
342- * <li>NONE: Do not retry reads.</li>
335+ * <li>ALWAYS: Retry reads of all replicas.</li>
336+ * <li>Xpercentile: Retry reads based on the effect on throughput and latency.</li>
337+ * <li>Yms: Retry reads after specified milliseconds.</li>
338+ * <li>NONE: Do not retry reads.</li>
343339 * </ul>
344- *
340+ * <p/>
345341 * Using the speculative retry property, you can configure rapid read protection in Cassandra 2.0.2 and later.
346342 * Use this property to retry a request after some milliseconds have passed or after a percentile of the typical read latency has been reached,
347343 * which is tracked per table.
348- *
349- * <p>
344+ * <p/>
345+ * <p/>
350346 * If no call is made to this method, the default value set by Cassandra is {code 99percentile}.
351347 *
352348 * @param speculativeRetry the speculative retry. To create instances, use
@@ -363,10 +359,10 @@
363359
364360 /**
365361 * Define a free-form option as a key/value pair.
366- * <p>
362+ * <p/>
367363 * This method is provided as a fallback if the SchemaBuilder is used with a more recent version of Cassandra that has new, unsupported options.
368364 *
369- * @param key the name of the option.
365+ * @param key the name of the option.
370366 * @param value the value of the option. If it's a {@code String}, it will be included in single quotes, otherwise the result of invoking its
371367 * {@code toString} method will be used unquoted.
372368 * @return this {@code TableOptions} object.
@@ -381,10 +377,10 @@
381377
382378 private static String buildCustomOption(String key, Object value) {
383379 return String.format("%s = %s",
384- key,
385- (value instanceof String)
386- ? "'" + value + "'"
387- : value.toString());
380+ key,
381+ (value instanceof String)
382+ ? "'" + value + "'"
383+ : value.toString());
388384 }
389385
390386 private List<String> buildCommonOptions() {
@@ -460,8 +456,7 @@
460456 private void buildCachingOptions(List<String> options) {
461457 if (cassandra20Caching.isPresent() && cassandra21KeyCaching.isPresent()) {
462458 throw new IllegalStateException("Can't use Cassandra 2.0 and 2.1 caching at the same time, you must call only one version of caching()");
463- }
464- else if (cassandra20Caching.isPresent()) {
459+ } else if (cassandra20Caching.isPresent()) {
465460 options.add("caching = " + cassandra20Caching.get().value());
466461 } else if (cassandra21KeyCaching.isPresent() && cassandra21RowCaching.isPresent()) {
467462 options.add(String.format("caching = {'keys' : %s, 'rows_per_partition' : %s}",
@@ -476,7 +471,7 @@
476471 List<String> options = buildCommonOptions();
477472 addSpecificOptions(options);
478473 return statementStart.buildInternal() + STATEMENT_START +
479- "WITH " + Joiner.on(" AND ").join(options);
474+ "WITH " + Joiner.on(" AND ").join(options);
480475 }
481476
482477 static void validateRateValue(Double rateValue, String property) {
@@ -487,7 +482,7 @@
487482
488483 /**
489484 * Compaction options for a CREATE or ALTER TABLE statement.
490- * <p>
485+ * <p/>
491486 * To create instances, use
492487 * {@link SchemaBuilder#sizedTieredStategy()},
493488 * {@link SchemaBuilder#leveledStrategy()} or
@@ -508,7 +503,7 @@
508503 private List<String> customOptions = new ArrayList<String>();
509504
510505 @SuppressWarnings("unchecked")
511- private final T self = (T)this;
506+ private final T self = (T) this;
512507
513508 CompactionOptions(Strategy compactionStrategy) {
514509 this.strategy = compactionStrategy;
@@ -516,7 +511,7 @@
516511
517512 /**
518513 * Enable or disable background compaction.
519- * <p>
514+ * <p/>
520515 * If no call is made to this method, the default value set by Cassandra is {code true}.
521516 *
522517 * @param enabled whether to enable background compaction for the table.
@@ -530,7 +525,7 @@
530525 /**
531526 * Define the minimum number of days to wait after an SSTable creation time before considering the SSTable for tombstone compaction.
532527 * Tombstone compaction is the compaction triggered if the SSTable has more garbage-collectable tombstones than tombstone_threshold.
533- * <p>
528+ * <p/>
534529 * If no call is made to this method, the default value set by Cassandra is 1.
535530 *
536531 * @param tombstoneCompactionInterval the tombstone compaction interval in day.
@@ -544,7 +539,7 @@
544539 /**
545540 * Define the ratio of garbage-collectable tombstones to all contained columns,
546541 * which if exceeded by the SSTable triggers compaction (with no other SSTables) for the purpose of purging the tombstones.
547- * <p>
542+ * <p/>
548543 * If no call is made to this method, the default value set by Cassandra is 0.2.
549544 *
550545 * @param tombstoneThreshold the threshold.
@@ -559,7 +554,7 @@
559554 /**
560555 * Enables more aggressive than normal tombstone compactions. A single SSTable tombstone compaction runs without
561556 * checking the likelihood of success (Cassandra 2.0.9 and later).
562- * <p>
557+ * <p/>
563558 * If no call is made to this method, the default value set by Cassandra is {code false}.
564559 *
565560 * @param uncheckedTombstoneCompaction whether to enable the feature.
@@ -572,10 +567,10 @@
572567
573568 /**
574569 * Define a free-form option as a key/value pair.
575- * <p>
570+ * <p/>
576571 * This method is provided as a fallback if the SchemaBuilder is used with a more recent version of Cassandra that has new, unsupported options.
577572 *
578- * @param key the name of the option.
573+ * @param key the name of the option.
579574 * @param value the value of the option. If it's a {@code CharSequence}, it will be included in single quotes, otherwise the result of invoking its
580575 * {@code toString} method will be used unquoted.
581576 * @return this object (for call chaining).
@@ -590,10 +585,10 @@
590585
591586 private static String buildCustomOption(String key, Object value) {
592587 return String.format("'%s' : %s",
593- key,
594- (value instanceof CharSequence)
595- ? "'" + value + "'"
596- : value.toString());
588+ key,
589+ (value instanceof CharSequence)
590+ ? "'" + value + "'"
591+ : value.toString());
597592 }
598593
599594 List<String> buildCommonOptions() {
@@ -648,7 +643,7 @@
648643 /**
649644 * Size-tiered compaction strategy (STCS) considers SSTables to be within the same bucket if the SSTable size diverges by 50%
650645 * or less from the default bucket_low and default bucket_high values: [average-size × bucket_low, average-size × bucket_high].
651- * <p>
646+ * <p/>
652647 * If no call is made to this method, the default value set by Cassandra is 1.5.
653648 *
654649 * @param bucketHigh the new value.
@@ -662,7 +657,7 @@
662657 /**
663658 * Size-tiered compaction strategy (STCS) considers SSTables to be within the same bucket if the SSTable size diverges by 50%
664659 * or less from the default bucket_low and default bucket_high values: [average-size × bucket_low, average-size × bucket_high].
665- * <p>
660+ * <p/>
666661 * If no call is made to this method, the default value set by Cassandra is 0.5.
667662 *
668663 * @param bucketLow the new value.
@@ -679,7 +674,7 @@
679674 * In Cassandra 2.0.3 and later, you can enable the cold_reads_to_omit property to tune performace per table.
680675 * The <a href="http://www.datastax.com/dev/blog/optimizations-around-cold-sstables">Optimizations around Cold SSTables</a> blog includes detailed information tuning performance using this property,
681676 * which avoids compacting cold SSTables. Use the ALTER TABLE command to configure cold_reads_to_omit.
682- * <p>
677+ * <p/>
683678 * If no call is made to this method, the default value set by Cassandra is 0.0 (disabled).
684679 *
685680 * @param coldReadsRatio the new value.
@@ -693,7 +688,7 @@
693688
694689 /**
695690 * Sets the minimum number of SSTables to trigger a minor compaction
696- * <p>
691+ * <p/>
697692 * If no call is made to this method, the default value set by Cassandra is 4.
698693 *
699694 * @param minThreshold the new value.
@@ -707,7 +702,7 @@
707702 /**
708703 * Sets the maximum number of SSTables to allow in a minor compaction.
709704 * In LeveledCompactionStrategy (LCS), it applies to L0 when L0 gets behind, that is, when L0 accumulates more than MAX_COMPACTING_L0 SSTables.
710- * <p>
705+ * <p/>
711706 * If no call is made to this method, the default value set by Cassandra is 32.
712707 *
713708 * @param maxThreshold the new value.
@@ -722,7 +717,7 @@
722717 * The SizeTieredCompactionStrategy groups SSTables for compaction into buckets.
723718 * The bucketing process groups SSTables that differ in size by less than 50%. This results in a bucketing process that is too fine grained for small SSTables.
724719 * If your SSTables are small, use min_sstable_size to define a size threshold (in bytes) below which all SSTables belong to one unique bucket
725- * <p>
720+ * <p/>
726721 * If no call is made to this method, the default value set by Cassandra is 52428800 (50 MB).
727722 *
728723 * @param minSSTableSize the new value.
@@ -781,7 +776,7 @@
781776 * The target size for SSTables that use the leveled compaction strategy.
782777 * Although SSTable sizes should be less or equal to sstable_size_in_mb, it is possible to have a larger SSTable during compaction.
783778 * This occurs when data for a given partition key is exceptionally large. The data is not split into two SSTables
784- * <p>
779+ * <p/>
785780 * If no call is made to this method, the default value set by Cassandra is 160.
786781 *
787782 * @param ssTableSizeInMB the new value.
@@ -829,7 +824,7 @@
829824
830825 /**
831826 * Sets the size of the first window.
832- * <p>
827+ * <p/>
833828 * If no call is made to this method, the default value set by Cassandra is 3600 (1 hour).
834829 *
835830 * @param baseTimeSeconds the size of the first window.
@@ -842,7 +837,7 @@
842837
843838 /**
844839 * Stop compacting SSTables only having data older than these specified days.
845- * <p>
840+ * <p/>
846841 * If no call is made to this method, the default value set by Cassandra is 365.
847842 *
848843 * @param maxSSTableAgeDays the maximum age of the SSTables to compact.
@@ -855,7 +850,7 @@
855850
856851 /**
857852 * Sets the minimum number of SSTables to trigger a minor compaction
858- * <p>
853+ * <p/>
859854 * If no call is made to this method, the default value set by Cassandra is 4.
860855 *
861856 * @param minThreshold the new value.
@@ -869,7 +864,7 @@
869864 /**
870865 * Sets the maximum number of SSTables to allow in a minor compaction.
871866 * In LeveledCompactionStrategy (LCS), it applies to L0 when L0 gets behind, that is, when L0 accumulates more than MAX_COMPACTING_L0 SSTables.
872- * <p>
867+ * <p/>
873868 * If no call is made to this method, the default value set by Cassandra is 32.
874869 *
875870 * @param maxThreshold the new value.
@@ -882,7 +877,7 @@
882877
883878 /**
884879 * Sets the timestamp resolution, depending on the timestamp unit of the data you insert.
885- * <p>
880+ * <p/>
886881 * If no call is made to this method, the default value set by Cassandra is {@code MICROSECONDS}.
887882 *
888883 * @param timestampResolution {@link TimeStampResolution#MICROSECONDS} or {@link TimeStampResolution#MILLISECONDS}.
@@ -893,7 +888,8 @@
893888 return this;
894889 }
895890
896- @Override public String build() {
891+ @Override
892+ public String build() {
897893 final List<String> generalOptions = super.buildCommonOptions();
898894
899895 List<String> options = new ArrayList<String>(generalOptions);
@@ -948,7 +944,7 @@
948944
949945 /**
950946 * The compression options for a CREATE or ALTER TABLE statement.
951- * <p>
947+ * <p/>
952948 * To create instances, use
953949 * {@link SchemaBuilder#noCompression()},
954950 * {@link SchemaBuilder#lz4()},
@@ -973,7 +969,7 @@
973969 * Values larger than the default value might improve the compression rate, but increases the minimum size of data to be read from disk when a read occurs.
974970 * The default value is a good middle-ground for compressing tables.
975971 * Adjust compression size to account for read/write access patterns (how much data is typically requested at once) and the average size of rows in the table.
976- * <p>
972+ * <p/>
977973 * If no call is made to this method, the default value set by Cassandra is 54.
978974 *
979975 * @param chunkLengthInKb the new value.
@@ -988,7 +984,7 @@
988984 * When compression is enabled, each compressed block includes a checksum of that block for the purpose of detecting disk bitrate and avoiding the propagation
989985 * of corruption to other replica. This option defines the probability with which those checksums are checked during read.
990986 * By default they are always checked. Set to 0 to disable checksum checking and to 0.5, for instance, to check them on every other read.
991- * <p>
987+ * <p/>
992988 * If no call is made to this method, the default value set by Cassandra is 1.0 (always check).
993989 *
994990 * @param crcCheckChance the new value.
@@ -1054,7 +1050,7 @@
10541050
10551051 /**
10561052 * The speculative retry options.
1057- * <p>
1053+ * <p/>
10581054 * To create instances, use
10591055 * {@link SchemaBuilder#noSpeculativeRetry()},
10601056 * {@link SchemaBuilder#always()},
@@ -1077,7 +1073,7 @@
10771073 /**
10781074 * Define the number of rows to be cached per partition when row caching is enabled
10791075 * (this feature is only applicable to Cassandra 2.1.x).
1080- * <p>
1076+ * <p/>
10811077 * To create instances, use
10821078 * {@link SchemaBuilder#noRows()},
10831079 * {@link SchemaBuilder#allRows()} or
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/UDTType.java +3 −2
@@ -19,7 +19,7 @@
1919
2020 /**
2121 * Represents a CQL type containing a user-defined type (UDT) in a SchemaBuilder statement.
22- * <p>
22+ * <p/>
2323 * Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)} to build instances of this type.
2424 */
2525 public final class UDTType implements ColumnType {
@@ -29,7 +29,8 @@
2929 this.asCQLString = asCQLString;
3030 }
3131
32- @Override public String asCQLString() {
32+ @Override
33+ public String asCQLString() {
3334 return asCQLString;
3435 }
3536
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/package-info.java +1 −1
@@ -15,7 +15,7 @@
1515 */
1616 /**
1717 * A CQL3 schema builder.
18- * <p>
18+ * <p/>
1919 * The main entry for this package is the {@code SchemaBuilder} class.
2020 */
2121 package com.datastax.driver.core.schemabuilder;
modified driver-core/src/main/java/com/datastax/driver/core/utils/Bytes.java +20 −19
@@ -24,20 +24,22 @@
2424 */
2525 public final class Bytes {
2626
27- private Bytes() {}
27+ private Bytes() {
28+ }
2829
2930 private static final byte[] charToByte = new byte[256];
3031 private static final char[] byteToChar = new char[16];
32+
3133 static {
3234 for (char c = 0; c < charToByte.length; ++c) {
3335 if (c >= '0' && c <= '9')
34- charToByte[c] = (byte)(c - '0');
36+ charToByte[c] = (byte) (c - '0');
3537 else if (c >= 'A' && c <= 'F')
36- charToByte[c] = (byte)(c - 'A' + 10);
38+ charToByte[c] = (byte) (c - 'A' + 10);
3739 else if (c >= 'a' && c <= 'f')
38- charToByte[c] = (byte)(c - 'a' + 10);
40+ charToByte[c] = (byte) (c - 'a' + 10);
3941 else
40- charToByte[c] = (byte)-1;
42+ charToByte[c] = (byte) -1;
4143 }
4244
4345 for (int i = 0; i < 16; ++i) {
@@ -51,6 +53,7 @@
5153 * That's stolen from Cassandra's code.
5254 */
5355 private static final Constructor<String> stringConstructor;
56+
5457 static {
5558 Constructor<String> c;
5659 try {
@@ -79,7 +82,7 @@
7982
8083 /**
8184 * Converts a blob to its CQL hex string representation.
82- * <p>
85+ * <p/>
8386 * A CQL blob string representation consist of the hexadecimal
8487 * representation of the blob bytes prefixed by "0x".
8588 *
@@ -102,7 +105,7 @@
102105
103106 /**
104107 * Converts a blob to its CQL hex string representation.
105- * <p>
108+ * <p/>
106109 * A CQL blob string representation consist of the hexadecimal
107110 * representation of the blob bytes.
108111 *
@@ -125,7 +128,7 @@
125128
126129 /**
127130 * Converts a blob to its CQL hex string representation.
128- * <p>
131+ * <p/>
129132 * A CQL blob string representation consist of the hexadecimal
130133 * representation of the blob bytes prefixed by "0x".
131134 *
@@ -139,7 +142,7 @@
139142
140143 /**
141144 * Parse an hex string representing a CQL blob.
142- * <p>
145+ * <p/>
143146 * The input should be a valid representation of a CQL blob, i.e. it
144147 * must start by "0x" followed by the hexadecimal representation of the
145148 * blob bytes.
@@ -147,9 +150,8 @@
147150 * @param str the CQL blob string representation to parse.
148151 * @return the bytes corresponding to {@code str}. If {@code str}
149152 * is {@code null}, this method returns {@code null}.
150- *
151153 * @throws IllegalArgumentException if {@code str} is not a valid CQL
152- * blob string.
154+ * blob string.
153155 */
154156 public static ByteBuffer fromHexString(String str) {
155157 if ((str.length() & 1) == 1)
@@ -163,7 +165,7 @@
163165
164166 /**
165167 * Extract the content of the provided {@code ByteBuffer} as a byte array.
166- * <p>
168+ * <p/>
167169 * This method work with any type of {@code ByteBuffer} (direct and non-direct
168170 * ones), but when the {@code ByteBuffer} is backed by an array, this method
169171 * will try to avoid copy when possible. As a consequence, changes to the
@@ -188,13 +190,13 @@
188190 bytes.duplicate().get(array);
189191 return array;
190192 }
191-
193+
192194 private static String toRawHexString(ByteBuffer bytes, char[] array, int offset) {
193195 int size = bytes.remaining();
194196 int bytesOffset = bytes.position();
195- assert array.length >= offset + 2*size;
197+ assert array.length >= offset + 2 * size;
196198 for (int i = 0; i < size; i++) {
197- int bint = bytes.get(i+bytesOffset);
199+ int bint = bytes.get(i + bytesOffset);
198200 array[offset + i * 2] = byteToChar[(bint & 0xf0) >> 4];
199201 array[offset + 1 + i * 2] = byteToChar[bint & 0x0f];
200202 }
@@ -203,13 +205,12 @@
203205
204206 /**
205207 * Converts a CQL hex string representation into a byte array.
206- * <p>
208+ * <p/>
207209 * A CQL blob string representation consist of the hexadecimal
208210 * representation of the blob bytes.
209211 *
210- * @param str the string converted in hex representation.
212+ * @param str the string converted in hex representation.
211213 * @param strOffset he offset for starting the string conversion
212- *
213214 * @return the byte array which the String was representing.
214215 */
215216
@@ -220,7 +221,7 @@
220221 byte halfByte2 = charToByte[str.charAt(strOffset + i * 2 + 1)];
221222 if (halfByte1 == -1 || halfByte2 == -1)
222223 throw new IllegalArgumentException("Non-hex characters in " + str);
223- bytes[i] = (byte)((halfByte1 << 4) | halfByte2);
224+ bytes[i] = (byte) ((halfByte1 << 4) | halfByte2);
224225 }
225226 return bytes;
226227 }
modified driver-core/src/main/java/com/datastax/driver/core/utils/UUIDs.java +20 −18
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.utils;
1717
18+import com.google.common.base.Charsets;
19+
1820 import java.net.InetAddress;
1921 import java.net.NetworkInterface;
2022 import java.net.SocketException;
@@ -24,15 +26,16 @@
2426 import java.util.*;
2527 import java.util.concurrent.atomic.AtomicLong;
2628
27-import com.google.common.base.Charsets;
28-
2929 /**
3030 * Utility methods to work with UUID and most specifically with time-based ones
3131 * (version 1).
3232 */
3333 public final class UUIDs {
3434
35- private UUIDs() {};
35+ private UUIDs() {
36+ }
37+
38+ ;
3639
3740 // http://www.ietf.org/rfc/rfc4122.txt
3841 private static final long START_EPOCH = makeEpoch();
@@ -96,7 +99,7 @@
9699
97100 long node = 0;
98101 for (int i = 0; i < 6; i++)
99- node |= (0x00000000000000ffL & (long)hash[i]) << (i*8);
102+ node |= (0x00000000000000ffL & (long) hash[i]) << (i * 8);
100103 // Since we don't use the mac address, the spec says that multicast
101104 // bit (least significant bit of the first byte of the node ID) must be 1.
102105 return node | 0x0000010000000000L;
@@ -123,7 +126,7 @@
123126
124127 /**
125128 * Creates a new random (version 4) UUID.
126- * <p>
129+ * <p/>
127130 * This method is just a convenience for {@code UUID.randomUUID()}.
128131 *
129132 * @return a newly generated, pseudo random, version 4 UUID.
@@ -134,7 +137,7 @@
134137
135138 /**
136139 * Creates a new time-based (version 1) UUID.
137- * <p>
140+ * <p/>
138141 * UUID generated by this method are suitable for use with the
139142 * {@code timeuuid} Cassandra type. In particular the generated UUID
140143 * includes the timestamp of its generation.
@@ -148,27 +151,27 @@
148151 /**
149152 * Creates a "fake" time-based UUID that sorts as the smallest possible
150153 * version 1 UUID generated at the provided timestamp.
151- * <p>
154+ * <p/>
152155 * Such created UUID are useful in queries to select a time range of a
153156 * {@code timeuuid} column.
154- * <p>
157+ * <p/>
155158 * The UUID created by this method <b>are not unique</b> and as such are
156159 * <b>not</b> suitable for anything else than querying a specific time
157160 * range. In particular, you should not insert such UUID.
158- * <p>
161+ * <p/>
159162 * Also, the timestamp to provide as parameter must be a unix timestamp (as
160163 * returned by {@link System#currentTimeMillis} or {@link java.util.Date#getTime}),
161164 * not a UUID 100-nanoseconds intervals since 15 October 1582. In other
162165 * words, given a UUID {@code uuid}, you should never do
163166 * {@code startOf(uuid.timestamp())} but rather
164167 * {@code startOf(unixTimestamp(uuid.timestamp()))}.
165- * <p>
168+ * <p/>
166169 * Lastly, please note that Cassandra's timeuuid sorting is not compatible
167170 * with {@link UUID#compareTo} and hence the UUID created by this method
168171 * are not necessarily lower bound for that latter method.
169172 *
170173 * @param timestamp the unix timestamp for which the created UUID must be a
171- * lower bound.
174+ * lower bound.
172175 * @return the smallest (for Cassandra timeuuid sorting) UUID of {@code timestamp}.
173176 */
174177 public static UUID startOf(long timestamp) {
@@ -178,27 +181,27 @@
178181 /**
179182 * Creates a "fake" time-based UUID that sorts as the biggest possible
180183 * version 1 UUID generated at the provided timestamp.
181- * <p>
184+ * <p/>
182185 * Such created UUID are useful in queries to select a time range of a
183186 * {@code timeuuid} column.
184- * <p>
187+ * <p/>
185188 * The UUID created by this method <b>are not unique</b> and as such are
186189 * <b>not</b> suitable for anything else than querying a specific time
187190 * range. In particular, you should not insert such UUID.
188- * <p>
191+ * <p/>
189192 * Also, the timestamp to provide as parameter must be a unix timestamp (as
190193 * returned by {@link System#currentTimeMillis} or {@link java.util.Date#getTime}),
191194 * not a UUID 100-nanoseconds intervals since 15 October 1582. In other
192195 * words, given a UUID {@code uuid}, you should never do
193196 * {@code startOf(uuid.timestamp())} but rather
194197 * {@code startOf(unixTimestamp(uuid.timestamp()))}.
195- * <p>
198+ * <p/>
196199 * Lastly, please note that Cassandra's timeuuid sorting is not compatible
197200 * with {@link UUID#compareTo} and hence the UUID created by this method
198201 * are not necessarily upper bound for that latter method.
199202 *
200203 * @param timestamp the unix timestamp for which the created UUID must be an
201- * upper bound.
204+ * upper bound.
202205 * @return the biggest (for Cassandra timeuuid sorting) UUID of {@code timestamp}.
203206 */
204207 public static UUID endOf(long timestamp) {
@@ -208,7 +211,7 @@
208211
209212 /**
210213 * Return the unix timestamp contained by the provided time-based UUID.
211- * <p>
214+ * <p/>
212215 * This method is not equivalent to {@code uuid.timestamp()}. More
213216 * precisely, a version 1 UUID stores a timestamp that represents the
214217 * number of 100-nanoseconds intervals since midnight, 15 October 1582 and
@@ -221,7 +224,6 @@
221224 *
222225 * @param uuid the UUID to return the timestamp of.
223226 * @return the unix timestamp of {@code uuid}.
224- *
225227 * @throws IllegalArgumentException if {@code uuid} is not a version 1 UUID.
226228 */
227229 public static long unixTimestamp(UUID uuid) {
modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +6 −10
@@ -20,16 +20,10 @@
2020 import java.util.HashMap;
2121 import java.util.Map;
2222
23-import static org.testng.Assert.assertEquals;
24-import static org.testng.Assert.assertTrue;
25-import static org.testng.Assert.fail;
26-
27-import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_GENERIC_FORMAT;
28-import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
29-import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
30-import static com.datastax.driver.core.TestUtils.SIMPLE_TABLE;
23+import static com.datastax.driver.core.TestUtils.*;
3124 import static com.datastax.driver.core.querybuilder.QueryBuilder.batch;
3225 import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
26+import static org.testng.Assert.*;
3327
3428 public abstract class AbstractPoliciesTest {
3529 private static final boolean DEBUG = false;
@@ -112,7 +106,9 @@
112106 }
113107 }
114108
115- /** 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+ */
116112 protected void assertOneNodeQueried(int n, String... hosts) {
117113 try {
118114 boolean found = false;
@@ -185,7 +181,7 @@
185181 if (batch)
186182 // BUG: WriteType == SIMPLE
187183 c.session.execute(batch()
188- .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}))
189185 .setConsistencyLevel(cl));
190186 else
191187 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 +20 −21
@@ -15,13 +15,11 @@
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.exceptions.ConnectionException;
21+import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
22+import com.datastax.driver.core.policies.ReconnectionPolicy.ReconnectionSchedule;
2523 import com.google.common.util.concurrent.Futures;
2624 import com.google.common.util.concurrent.ListenableFuture;
2725 import com.google.common.util.concurrent.SettableFuture;
@@ -32,18 +30,17 @@
3230 import org.testng.annotations.BeforeMethod;
3331 import org.testng.annotations.Test;
3432
33+import java.net.InetSocketAddress;
34+import java.util.concurrent.CyclicBarrier;
35+import java.util.concurrent.Executors;
36+import java.util.concurrent.ScheduledExecutorService;
37+import java.util.concurrent.TimeUnit;
38+import java.util.concurrent.atomic.AtomicReference;
39+
3540 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;
41+import static org.mockito.Mockito.*;
3942 import static org.testng.Assert.fail;
4043
41-import com.datastax.driver.core.AbstractReconnectionHandler.HandlerFuture;
42-import com.datastax.driver.core.AbstractReconnectionHandlerTest.MockReconnectionWork.ReconnectBehavior;
43-import com.datastax.driver.core.exceptions.ConnectionException;
44-import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
45-import com.datastax.driver.core.policies.ReconnectionPolicy.ReconnectionSchedule;
46-
4744 public class AbstractReconnectionHandlerTest {
4845 private static final Logger logger = LoggerFactory.getLogger(AbstractReconnectionHandlerTest.class);
4946
@@ -171,7 +168,7 @@
171168 // The future will be marked cancelled and thus not executed.
172169 ListenableFuture<?> currentAttempt = future.get();
173170 assertThat(currentAttempt).isInstanceOf(HandlerFuture.class);
174- HandlerFuture handlerFuture = (HandlerFuture)currentAttempt;
171+ HandlerFuture handlerFuture = (HandlerFuture) currentAttempt;
175172 assertThat(handlerFuture.isCancelled());
176173
177174 // The next try should also be cancelled.
@@ -278,7 +275,7 @@
278275
279276 /**
280277 * A reconnection schedule that allows manually setting the delay.
281- *
278+ * <p/>
282279 * To make testing easier, nextDelay blocks until tick() is called from the main thread.
283280 */
284281 static class MockReconnectionSchedule implements ReconnectionSchedule {
@@ -323,14 +320,16 @@
323320
324321 /**
325322 * Simulates the work done by the overridable methods of the handler.
326- *
323+ * <p/>
327324 * Allows choosing whether the next reconnect will succeed or throw an exception.
328325 * To make testing easier, tryReconnect blocks until tick() is called from the main thread.
329326 */
330327 static class MockReconnectionWork {
331328 enum ReconnectBehavior {
332329 SUCCEED, THROW_EXCEPTION
333- };
330+ }
331+
332+ ;
334333
335334 private final CyclicBarrier barrier = new CyclicBarrier(2);
336335
@@ -355,7 +354,7 @@
355354 case THROW_EXCEPTION:
356355 logger.debug("simulate reconnection error");
357356 throw new ConnectionException(new InetSocketAddress(8888),
358- "Simulated exception from mock reconnection");
357+ "Simulated exception from mock reconnection");
359358 default:
360359 throw new AssertionError();
361360 }
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/AggregateMetadataTest.java +28 −30
@@ -15,17 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.utils.CassandraVersion;
2019 import org.testng.annotations.Test;
2120
22-import static com.google.common.collect.Lists.newArrayList;
23-
24-import com.datastax.driver.core.utils.CassandraVersion;
21+import java.util.Collection;
2522
2623 import static com.datastax.driver.core.Assertions.assertThat;
2724 import static com.datastax.driver.core.DataType.cint;
2825 import static com.datastax.driver.core.DataType.text;
26+import static com.google.common.collect.Lists.newArrayList;
2927
3028 @CassandraVersion(major = 2.2)
3129 public class AggregateMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -53,8 +51,8 @@
5351 assertThat(aggregate.getStateType()).isEqualTo(text());
5452 assertThat(aggregate.toString()).isEqualTo(cqlAggregate);
5553 assertThat(aggregate.exportAsString()).isEqualTo(String.format("CREATE AGGREGATE %s.cat_tos(int)\n"
56- + "SFUNC cat STYPE text\n"
57- + "INITCOND '0';", this.keyspace));
54+ + "SFUNC cat STYPE text\n"
55+ + "INITCOND '0';", this.keyspace));
5856 }
5957
6058 @Test(groups = "short")
@@ -80,8 +78,8 @@
8078 assertThat(aggregate.getStateType()).isEqualTo(cint());
8179 assertThat(aggregate.toString()).isEqualTo(cqlAggregate);
8280 assertThat(aggregate.exportAsString()).isEqualTo(String.format("CREATE AGGREGATE %s.mycount()\n"
83- + "SFUNC inc STYPE int\n"
84- + "INITCOND 0;", this.keyspace));
81+ + "SFUNC inc STYPE int\n"
82+ + "INITCOND 0;", this.keyspace));
8583 }
8684
8785 @Test(groups = "short")
@@ -110,9 +108,9 @@
110108 assertThat(aggregate.getStateType()).isEqualTo(cint());
111109 assertThat(aggregate.toString()).isEqualTo(cqlAggregate);
112110 assertThat(aggregate.exportAsString()).isEqualTo(String.format("CREATE AGGREGATE %s.prettysum(int)\n"
113- + "SFUNC plus STYPE int\n"
114- + "FINALFUNC announce\n"
115- + "INITCOND 0;", this.keyspace));
111+ + "SFUNC plus STYPE int\n"
112+ + "FINALFUNC announce\n"
113+ + "INITCOND 0;", this.keyspace));
116114 }
117115
118116 @Test(groups = "short")
@@ -138,23 +136,23 @@
138136 assertThat(aggregate.getStateType()).isEqualTo(cint());
139137 assertThat(aggregate.toString()).isEqualTo(cqlAggregate);
140138 assertThat(aggregate.exportAsString()).isEqualTo(String.format("CREATE AGGREGATE %s.sum(int)\n"
141- + "SFUNC plus2 STYPE int;", this.keyspace));
139+ + "SFUNC plus2 STYPE int;", this.keyspace));
142140 }
143141
144142 @Test(groups = "short")
145143 public void should_parse_and_format_aggregate_with_udts() {
146144 // given
147145 String cqlFunction = String.format(
148- "CREATE FUNCTION %s.\"MY_FUNC\"(address1 \"Address\", address2 \"Address\") "
149- + "CALLED ON NULL INPUT "
150- + "RETURNS \"Address\" "
151- + "LANGUAGE java "
152- + "AS 'return address1;'", keyspace);
146+ "CREATE FUNCTION %s.\"MY_FUNC\"(address1 \"Address\", address2 \"Address\") "
147+ + "CALLED ON NULL INPUT "
148+ + "RETURNS \"Address\" "
149+ + "LANGUAGE java "
150+ + "AS 'return address1;'", keyspace);
153151 String cqlAggregate = String.format(
154- "CREATE AGGREGATE %s.\"MY_AGGREGATE\"(\"Address\") "
155- + "SFUNC \"MY_FUNC\" "
156- + "STYPE \"Address\";",
157- keyspace);
152+ "CREATE AGGREGATE %s.\"MY_AGGREGATE\"(\"Address\") "
153+ + "SFUNC \"MY_FUNC\" "
154+ + "STYPE \"Address\";",
155+ keyspace);
158156 // when
159157 session.execute(cqlFunction);
160158 session.execute(cqlAggregate);
@@ -178,14 +176,14 @@
178176 @Override
179177 protected Collection<String> getTableDefinitions() {
180178 return newArrayList(
181- String.format("CREATE TYPE IF NOT EXISTS %s.phone (number text)", keyspace),
182- String.format("CREATE TYPE IF NOT EXISTS %s.\"Address\" ("
183- + " street text,"
184- + " city text,"
185- + " zip int,"
186- + " phones frozen<set<frozen<phone>>>,"
187- + " location frozen<tuple<float, float>>"
188- + ")", keyspace)
179+ String.format("CREATE TYPE IF NOT EXISTS %s.phone (number text)", keyspace),
180+ String.format("CREATE TYPE IF NOT EXISTS %s.\"Address\" ("
181+ + " street text,"
182+ + " city text,"
183+ + " zip int,"
184+ + " phones frozen<set<frozen<phone>>>,"
185+ + " location frozen<tuple<float, float>>"
186+ + ")", keyspace)
189187 );
190188 }
191189
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/AsyncResultSetTest.java +11 −10
@@ -15,10 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.Set;
20-import java.util.concurrent.ConcurrentSkipListSet;
21-
18+import com.datastax.driver.core.utils.CassandraVersion;
2219 import com.google.common.collect.Lists;
2320 import com.google.common.util.concurrent.AsyncFunction;
2421 import com.google.common.util.concurrent.Futures;
@@ -26,16 +23,18 @@
2623 import org.testng.annotations.BeforeMethod;
2724 import org.testng.annotations.Test;
2825
29-import static org.assertj.core.api.Assertions.assertThat;
26+import java.util.Collection;
27+import java.util.Set;
28+import java.util.concurrent.ConcurrentSkipListSet;
3029
31-import com.datastax.driver.core.utils.CassandraVersion;
30+import static org.assertj.core.api.Assertions.assertThat;
3231
3332 @CassandraVersion(major = 2.0, description = "uses paging")
3433 public class AsyncResultSetTest extends CCMBridge.PerClassSingleNodeCluster {
3534 @Override
3635 protected Collection<String> getTableDefinitions() {
3736 return Lists.newArrayList(
38- "create table ints (i int primary key)");
37+ "create table ints (i int primary key)");
3938 }
4039
4140 @BeforeMethod(groups = "short")
@@ -61,15 +60,17 @@
6160 ResultsAccumulator results = new ResultsAccumulator();
6261
6362 ListenableFuture<ResultSet> future = Futures.transform(
64- session.executeAsync(statement),
65- results);
63+ session.executeAsync(statement),
64+ results);
6665
6766 Futures.getUnchecked(future);
6867
6968 assertThat(results.all.size()).isEqualTo(totalCount);
7069 }
7170
72- /** Dummy tranformation that accumulates all traversed results */
71+ /**
72+ * Dummy tranformation that accumulates all traversed results
73+ */
7374 static class ResultsAccumulator implements AsyncFunction<ResultSet, ResultSet> {
7475 final Set<Integer> all = new ConcurrentSkipListSet<Integer>();
7576
modified driver-core/src/test/java/com/datastax/driver/core/AtomicMonotonicTimestampGeneratorTest.java +15 −15
@@ -15,13 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.SortedSet;
20-import java.util.concurrent.ConcurrentSkipListSet;
21-import java.util.concurrent.ExecutionException;
22-import java.util.concurrent.Executors;
23-import java.util.concurrent.TimeUnit;
24-
2518 import com.google.common.collect.Lists;
2619 import com.google.common.util.concurrent.Futures;
2720 import com.google.common.util.concurrent.ListenableFuture;
@@ -29,6 +22,13 @@
2922 import com.google.common.util.concurrent.MoreExecutors;
3023 import org.testng.annotations.Test;
3124
25+import java.util.List;
26+import java.util.SortedSet;
27+import java.util.concurrent.ConcurrentSkipListSet;
28+import java.util.concurrent.ExecutionException;
29+import java.util.concurrent.Executors;
30+import java.util.concurrent.TimeUnit;
31+
3232 import static org.testng.Assert.assertEquals;
3333 import static org.testng.Assert.fail;
3434
@@ -49,13 +49,13 @@
4949 List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(testThreadsCount);
5050 for (int i = 0; i < testThreadsCount; i++) {
5151 futures.add(executor.submit(
52- new Runnable() {
53- @Override
54- public void run() {
55- for (int i = 0; i < 1000 / testThreadsCount; i++)
56- allTimestamps.add(generator.next());
57- }
58- }));
52+ new Runnable() {
53+ @Override
54+ public void run() {
55+ for (int i = 0; i < 1000 / testThreadsCount; i++)
56+ allTimestamps.add(generator.next());
57+ }
58+ }));
5959 }
6060 executor.shutdown();
6161 executor.awaitTermination(1, TimeUnit.SECONDS);
@@ -65,7 +65,7 @@
6565 } catch (ExecutionException e) {
6666 Throwable cause = e.getCause();
6767 if (cause instanceof AssertionError)
68- throw (AssertionError)cause;
68+ throw (AssertionError) cause;
6969 else
7070 fail("Error in a test thread", cause);
7171 }
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +9 −13
@@ -15,22 +15,18 @@
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 static org.mockito.Mockito.atLeastOnce;
27-import static org.mockito.Mockito.spy;
28-import static org.mockito.Mockito.verify;
29-
30-import com.datastax.driver.core.exceptions.AuthenticationException;
31-import com.datastax.driver.core.exceptions.NoHostAvailableException;
26+import java.util.concurrent.TimeUnit;
3227
3328 import static com.datastax.driver.core.TestUtils.findHost;
29+import static org.mockito.Mockito.*;
3430
3531 /**
3632 * Tests for authenticated cluster access
@@ -44,12 +40,12 @@
4440 /**
4541 * creates a cluster and turns on password authentication before starting it.
4642 */
47- @BeforeClass (groups = "short")
43+ @BeforeClass(groups = "short")
4844 public void setupClusterWithAuthentication() throws InterruptedException {
4945 ccm = CCMBridge.builder("test")
50- .withCassandraConfiguration("authenticator", "PasswordAuthenticator")
51- .notStarted()
52- .build();
46+ .withCassandraConfiguration("authenticator", "PasswordAuthenticator")
47+ .notStarted()
48+ .build();
5349 ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
5450
5551 // Even though we've override the default user setup delay, still wait
@@ -57,7 +53,7 @@
5753 TimeUnit.SECONDS.sleep(1);
5854 }
5955
60- @AfterClass (groups = "short")
56+ @AfterClass(groups = "short")
6157 public void shutdownCluster() {
6258 if (ccm != null)
6359 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.CodecNotFoundException;
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.CodecNotFoundException;
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
@@ -85,11 +83,11 @@
8583 * The environment variables to use when invoking CCM. Inherits the current processes environment, but will also
8684 * prepend to the PATH variable the value of the 'ccm.path' property and set JAVA_HOME variable to the
8785 * 'ccm.java.home' variable.
88- *
86+ * <p/>
8987 * At times it is necessary to use a separate java install for CCM then what is being used for running tests.
9088 * For example, if you want to run tests with JDK 6 but against Cassandra 2.0, which requires JDK 7.
9189 */
92- private static final Map<String,String> ENVIRONMENT_MAP;
90+ private static final Map<String, String> ENVIRONMENT_MAP;
9391
9492 /**
9593 * The command to use to launch CCM
@@ -102,7 +100,7 @@
102100 String branch = System.getProperty("cassandra.branch");
103101 if (installDirectory != null && !installDirectory.trim().isEmpty()) {
104102 CASSANDRA_INSTALL_ARGS = "--install-dir=" + new File(installDirectory).getAbsolutePath();
105- } else if(branch != null && !branch.trim().isEmpty()) {
103+ } else if (branch != null && !branch.trim().isEmpty()) {
106104 CASSANDRA_INSTALL_ARGS = "-v " + branch.replaceAll("\"", "");
107105 } else {
108106 CASSANDRA_INSTALL_ARGS = "-v " + CASSANDRA_VERSION;
@@ -115,12 +113,12 @@
115113 IP_PREFIX = ip_prefix;
116114
117115 // Inherit the current environment.
118- Map<String,String> envMap = Maps.newHashMap(new ProcessBuilder().environment());
116+ Map<String, String> envMap = Maps.newHashMap(new ProcessBuilder().environment());
119117 // If ccm.path is set, override the PATH variable with it.
120118 String ccmPath = System.getProperty("ccm.path");
121- if(ccmPath != null) {
119+ if (ccmPath != null) {
122120 String existingPath = envMap.get("PATH");
123- if(existingPath == null) {
121+ if (existingPath == null) {
124122 existingPath = "";
125123 }
126124 envMap.put("PATH", ccmPath + File.pathSeparator + existingPath);
@@ -134,7 +132,7 @@
134132
135133 // If ccm.java.home is set, override the JAVA_HOME variable with it.
136134 String ccmJavaHome = System.getProperty("ccm.java.home");
137- if(ccmJavaHome != null) {
135+ if (ccmJavaHome != null) {
138136 envMap.put("JAVA_HOME", ccmJavaHome);
139137 }
140138 ENVIRONMENT_MAP = ImmutableMap.copyOf(envMap);
@@ -142,6 +140,7 @@
142140
143141 /**
144142 * Checks if the operating system is a Windows one
143+ *
145144 * @return <code>true</code> if the operating system is a Windows one, <code>false</code> otherwise.
146145 */
147146 private static boolean isWindows() {
@@ -160,11 +159,12 @@
160159 * <p>
161160 * Extracts a keystore from the classpath into a temporary file.
162161 * </p>
163- *
162+ * <p/>
164163 * <p>
165164 * This is needed as the keystore could be part of a built test jar used by other
166165 * projects, and they need to be extracted to a file system so cassandra may use them.
167166 * </p>
167+ *
168168 * @param storePath Path in classpath where the keystore exists.
169169 * @return The generated File.
170170 */
@@ -232,7 +232,7 @@
232232
233233 public void stop(String clusterName) {
234234 logger.info("Stopping Cluster : " + clusterName);
235- execute(CCM_COMMAND + " stop "+clusterName);
235+ execute(CCM_COMMAND + " stop " + clusterName);
236236 }
237237
238238 public void forceStop(int n) {
@@ -273,8 +273,8 @@
273273 String binaryItf = IP_PREFIX + n + ":" + binaryPort;
274274 String remoteLogItf = IP_PREFIX + n + ":" + remoteDebugPort;
275275 execute(CCM_COMMAND + " add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s",
276- n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf);
277- if(option == null) start(n);
276+ n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf);
277+ if (option == null) start(n);
278278 else start(n, option);
279279 }
280280
@@ -299,12 +299,14 @@
299299 Executor executor = new DefaultExecutor();
300300
301301 LogOutputStream outStream = new LogOutputStream() {
302- @Override protected void processLine(String line, int logLevel) {
302+ @Override
303+ protected void processLine(String line, int logLevel) {
303304 logger.debug("ccmout> " + line);
304305 }
305306 };
306307 LogOutputStream errStream = new LogOutputStream() {
307- @Override protected void processLine(String line, int logLevel) {
308+ @Override
309+ protected void processLine(String line, int logLevel) {
308310 logger.error("ccmerr> " + line);
309311 }
310312 };
@@ -413,7 +415,7 @@
413415
414416 private static CCMBridge ccmBridge;
415417 private static boolean erroredOut;
416- private static boolean clusterInitialized=false;
418+ private static boolean clusterInitialized = false;
417419 private static AtomicLong ksNumber;
418420 private static final String jvmArgs = "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler";
419421 protected String keyspace;
@@ -423,7 +425,7 @@
423425
424426 protected static Cluster cluster;
425427 protected static Session session;
426-
428+
427429 protected final VersionNumber cassandraVersion = VersionNumber.parse(System.getProperty("cassandra.version"));
428430
429431 protected abstract Collection<String> getTableDefinitions();
@@ -437,25 +439,25 @@
437439 erroredOut = true;
438440 }
439441
440- @BeforeClass(groups = { "isolated", "short", "long" })
442+ @BeforeClass(groups = {"isolated", "short", "long"})
441443 public void beforeClass() {
442444 maybeInitCluster();
443445 initKeyspace();
444446 }
445447
446- @AfterClass(groups = { "isolated", "short", "long" })
448+ @AfterClass(groups = {"isolated", "short", "long"})
447449 public void afterClass() {
448450 try {
449451 clearSimpleKeyspace();
450452 } finally {
451- if(cluster != null) {
453+ if (cluster != null) {
452454 cluster.close();
453455 }
454456 }
455457 }
456458
457- private void maybeInitCluster(){
458- if (!clusterInitialized){
459+ private void maybeInitCluster() {
460+ if (!clusterInitialized) {
459461 try {
460462 ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
461463
@@ -463,7 +465,7 @@
463465 .withoutNodes()
464466 .notStarted();
465467
466- if(protocolVersion.compareTo(ProtocolVersion.V4) >= 0) {
468+ if (protocolVersion.compareTo(ProtocolVersion.V4) >= 0) {
467469 builder = builder.withCassandraConfiguration("enable_user_defined_functions", "true");
468470 }
469471 ccmBridge = builder.build();
@@ -523,7 +525,7 @@
523525 }
524526
525527 private void clearSimpleKeyspace() {
526- if(keyspace != null) {
528+ if (keyspace != null) {
527529 // Temporarily extend read timeout to 1 minute to accommodate keyspaces with many tables.
528530 // This should be more than enough although some tests create many tables, so dropping a keyspace
529531 // could take as long as 12 seconds on restricted hardware.
@@ -618,10 +620,12 @@
618620 }
619621 }
620622
621- /** use {@link #builder(String)} to get an instance */
623+ /**
624+ * use {@link #builder(String)} to get an instance
625+ */
622626 public static class Builder {
623627 private final String clusterName;
624- private Integer[] nodes = { 1 };
628+ private Integer[] nodes = {1};
625629 private boolean start = true;
626630 private String cassandraInstallArgs = CASSANDRA_INSTALL_ARGS;
627631 private String[] startOptions = new String[0];
@@ -632,7 +636,9 @@
632636 this.clusterName = clusterName;
633637 }
634638
635- /** Number of nodes for each DC. Defaults to [1] (1 DC with 1 node) */
639+ /**
640+ * Number of nodes for each DC. Defaults to [1] (1 DC with 1 node)
641+ */
636642 public Builder withNodes(Integer... nodes) {
637643 this.nodes = nodes;
638644 return this;
@@ -655,25 +661,33 @@
655661 return this;
656662 }
657663
658- /** Whether to start the cluster immediately (defaults to true if this is never called) */
664+ /**
665+ * Whether to start the cluster immediately (defaults to true if this is never called)
666+ */
659667 public Builder notStarted() {
660668 this.start = false;
661669 return this;
662670 }
663671
664- /** Defaults to system property cassandra.version */
672+ /**
673+ * Defaults to system property cassandra.version
674+ */
665675 public Builder withCassandraVersion(String cassandraVersion) {
666676 this.cassandraInstallArgs = "-v " + cassandraVersion;
667677 return this;
668678 }
669679
670- /** Free-form options that will be added at the end of the start command */
680+ /**
681+ * Free-form options that will be added at the end of the start command
682+ */
671683 public Builder withStartOptions(String... options) {
672684 this.startOptions = options;
673685 return this;
674686 }
675687
676- /** Customizes entries in cassandra.yaml (can be called multiple times) */
688+ /**
689+ * Customizes entries in cassandra.yaml (can be called multiple times)
690+ */
677691 public Builder withCassandraConfiguration(String key, String value) {
678692 this.cassandraConfiguration.put(key, value);
679693 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/ClusterAssert.java +15 −14
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.Iterators;
19+import org.assertj.core.api.AbstractAssert;
20+
1821 import java.util.Iterator;
1922 import java.util.Set;
2023 import java.util.TreeSet;
2124 import java.util.concurrent.TimeUnit;
2225
23-import com.google.common.collect.Iterators;
24-import org.assertj.core.api.AbstractAssert;
25-
2626 import static org.assertj.core.api.Assertions.assertThat;
2727
2828 public class ClusterAssert extends AbstractAssert<ClusterAssert, Cluster> {
@@ -56,26 +56,27 @@
5656 // Wait for the node to be added if it's not already known.
5757 // In 2.2+ C* does not send an added event until the node is ready so we wait a long time.
5858 Host host = TestUtils.findOrWaitForHost(actual, hostNumber,
59- 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
59+ 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
6060 return new HostAssert(host, actual);
6161 }
6262
6363 public HostAssert host(String hostAddress) {
6464 Host host = TestUtils.findOrWaitForHost(actual, hostAddress,
65- 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
65+ 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
6666 return new HostAssert(host, actual);
6767 }
6868
6969 /**
7070 * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s with the given keyspace.
71- *
71+ * <p/>
7272 * Ensures that no ranges intersect and that they cover the entire ring.
73+ *
7374 * @param keyspace Keyspace to grab {@link TokenRange}s from.
7475 */
7576 public ClusterAssert hasValidTokenRanges(String keyspace) {
7677 // Sort the token ranges so they are in order (needed for vnodes).
7778 Set<TokenRange> ranges = new TreeSet<TokenRange>();
78- for(Host host : actual.getMetadata().getAllHosts()) {
79+ for (Host host : actual.getMetadata().getAllHosts()) {
7980 ranges.addAll(actual.getMetadata().getTokenRanges(keyspace, host));
8081 }
8182 return hasValidTokenRanges(ranges);
@@ -83,7 +84,7 @@
8384
8485 /**
8586 * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s.
86- *
87+ * <p/>
8788 * Ensures that no ranges intersect and that they cover the entire ring.
8889 */
8990 public ClusterAssert hasValidTokenRanges() {
@@ -94,13 +95,13 @@
9495
9596 /**
9697 * Asserts that given Set of {@link TokenRange}s are valid.
97- *
98+ * <p/>
9899 * Ensures that no ranges intersect and that they cover the entire ring.
99100 */
100101 private ClusterAssert hasValidTokenRanges(Set<TokenRange> ranges) {
101102 // Ensure no ranges intersect.
102103 Iterator<TokenRange> it = ranges.iterator();
103- while(it.hasNext()) {
104+ while (it.hasNext()) {
104105 TokenRange range = it.next();
105106 Assertions.assertThat(range).doesNotIntersect(Iterators.toArray(it, TokenRange.class));
106107 }
@@ -108,15 +109,15 @@
108109 // Ensure the defined ranges cover the entire ring.
109110 it = ranges.iterator();
110111 TokenRange mergedRange = it.next();
111- while(it.hasNext()) {
112+ while (it.hasNext()) {
112113 TokenRange next = it.next();
113114 mergedRange = mergedRange.mergeWith(next);
114115 }
115116 boolean isFullRing = mergedRange.getStart().equals(mergedRange.getEnd())
116- && !mergedRange.isEmpty();
117+ && !mergedRange.isEmpty();
117118 assertThat(isFullRing)
118- .as("Ring is not fully defined for Cluster.")
119- .isTrue();
119+ .as("Ring is not fully defined for Cluster.")
120+ .isTrue();
120121
121122 return this;
122123 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterDelegateTest.java +2 −2
@@ -15,11 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
2018 import com.google.common.collect.Lists;
2119 import org.testng.annotations.Test;
2220
21+import java.util.Collection;
22+
2323 import static org.assertj.core.api.Assertions.assertThat;
2424
2525 public class ClusterDelegateTest extends CCMBridge.PerClassSingleNodeCluster {
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +58 −64
@@ -15,19 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-import java.net.UnknownHostException;
21-import java.util.Collections;
22-import java.util.List;
23-import java.util.Map;
24-import java.util.concurrent.TimeUnit;
25-import java.util.concurrent.TimeoutException;
26-
18+import com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
2720 import com.google.common.collect.ImmutableMap;
2821 import com.google.common.collect.ImmutableSet;
2922 import com.google.common.collect.Lists;
30-import com.google.common.collect.Maps;
3123 import com.google.common.util.concurrent.Uninterruptibles;
3224 import org.scassandra.Scassandra;
3325 import org.scassandra.http.client.PrimingClient;
@@ -37,13 +29,14 @@
3729 import org.testng.SkipException;
3830 import org.testng.annotations.Test;
3931
40-import static org.mockito.Mockito.atLeast;
41-import static org.mockito.Mockito.atMost;
42-import static org.mockito.Mockito.spy;
43-import static org.mockito.Mockito.verify;
44-
45-import com.datastax.driver.core.exceptions.NoHostAvailableException;
46-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
32+import java.net.InetAddress;
33+import java.net.InetSocketAddress;
34+import java.net.UnknownHostException;
35+import java.util.Collections;
36+import java.util.List;
37+import java.util.Map;
38+import java.util.concurrent.TimeUnit;
39+import java.util.concurrent.TimeoutException;
4740
4841 import static com.datastax.driver.core.Assertions.assertThat;
4942 import static com.datastax.driver.core.Assertions.fail;
@@ -51,6 +44,7 @@
5144 import static com.datastax.driver.core.HostDistance.LOCAL;
5245 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
5346 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
47+import static org.mockito.Mockito.*;
5448
5549 public class ClusterInitTest {
5650 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -104,19 +98,19 @@
10498 PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(LOCAL, 1, 1);
10599
106100 cluster = Cluster.builder()
107- .withPort(scassandra.getBinaryPort())
108- .addContactPoints(
109- realHostAddress,
110- failingHosts.get(0).address, failingHosts.get(1).address,
111- failingHosts.get(2).address, failingHosts.get(3).address,
112- missingHostAddress
113- )
114- .withSocketOptions(socketOptions)
115- .withReconnectionPolicy(reconnectionPolicy)
116- .withPoolingOptions(poolingOptions)
117- .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
118- .withQueryOptions(nonDebouncingQueryOptions())
119- .build();
101+ .withPort(scassandra.getBinaryPort())
102+ .addContactPoints(
103+ realHostAddress,
104+ failingHosts.get(0).address, failingHosts.get(1).address,
105+ failingHosts.get(2).address, failingHosts.get(3).address,
106+ missingHostAddress
107+ )
108+ .withSocketOptions(socketOptions)
109+ .withReconnectionPolicy(reconnectionPolicy)
110+ .withPoolingOptions(poolingOptions)
111+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
112+ .withQueryOptions(nonDebouncingQueryOptions())
113+ .build();
120114 cluster.connect();
121115
122116 // For information only:
@@ -142,7 +136,7 @@
142136 // There is a possible race here in that the host is marked down in a separate Executor in onDown
143137 // and then starts a periodic reconnection attempt shortly after. Since setDown is called before
144138 // startPeriodicReconnectionAttempt, we add a slight delay here if the future isn't set yet.
145- if(host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) {
139+ if (host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) {
146140 logger.warn("Periodic Reconnection Attempt hasn't started yet for {}, waiting 1 second and then checking.", host);
147141 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
148142 }
@@ -168,19 +162,19 @@
168162 * @jira_ticket JAVA-954
169163 * @expected_result No reconnection scheduled.
170164 */
171- @Test(groups="short", expectedExceptions = NoHostAvailableException.class)
165+ @Test(groups = "short", expectedExceptions = NoHostAvailableException.class)
172166 public void should_not_schedule_reconnections_before_init_complete() {
173167 // Both contact points time out so we're sure we'll try both of them and init will never complete.
174168 List<FakeHost> hosts = Lists.newArrayList(
175- new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS),
176- new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS));
169+ new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS),
170+ new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS));
177171 // Use a low reconnection interval and keep the default connect timeout (5 seconds). So if a reconnection was scheduled,
178172 // we would see a call to the reconnection policy.
179173 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(100));
180174 Cluster cluster = Cluster.builder()
181- .addContactPoints(hosts.get(0).address, hosts.get(1).address)
182- .withReconnectionPolicy(reconnectionPolicy)
183- .build();
175+ .addContactPoints(hosts.get(0).address, hosts.get(1).address)
176+ .withReconnectionPolicy(reconnectionPolicy)
177+ .build();
184178 try {
185179 cluster.init();
186180 } finally {
@@ -205,9 +199,9 @@
205199 @Test(groups = "short")
206200 public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
207201 Cluster cluster = Cluster.builder()
208- .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
209- .withNettyOptions(nonQuietClusterCloseOptions)
210- .build();
202+ .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
203+ .withNettyOptions(nonQuietClusterCloseOptions)
204+ .build();
211205 try {
212206 cluster.connect();
213207 fail("Should not have been able to connect.");
@@ -228,23 +222,23 @@
228222 * @jira_ticket JAVA-854
229223 * @test_category host:state
230224 */
231- @Test(groups="short")
225+ @Test(groups = "short")
232226 public void should_not_abort_init_if_host_does_not_support_protocol_version() {
233227 ScassandraCluster scassandraCluster = ScassandraCluster.builder()
234- .withIpPrefix(CCMBridge.IP_PREFIX)
235- .withNodes(5)
236- // For node 2, report an older version which uses protocol v1.
237- .forcePeerInfo(1, 2, "release_version", "1.2.19")
238- .build();
228+ .withIpPrefix(CCMBridge.IP_PREFIX)
229+ .withNodes(5)
230+ // For node 2, report an older version which uses protocol v1.
231+ .forcePeerInfo(1, 2, "release_version", "1.2.19")
232+ .build();
239233 Cluster cluster = Cluster.builder()
240- .addContactPoints(scassandraCluster.address(1))
241- .withNettyOptions(nonQuietClusterCloseOptions)
242- .build();
234+ .addContactPoints(scassandraCluster.address(1))
235+ .withNettyOptions(nonQuietClusterCloseOptions)
236+ .build();
243237
244238 try {
245239 scassandraCluster.init();
246240 cluster.init();
247- for(int i = 1; i <= 5; i++) {
241+ for (int i = 1; i <= 5; i++) {
248242 String hostAddress = scassandraCluster.address(i);
249243 if (i == 2) {
250244 // As this host is at an older protocol version, it should be ignored and not marked up.
@@ -263,8 +257,8 @@
263257
264258 private void primePeerRows(Scassandra scassandra, List<FakeHost> otherHosts) throws UnknownHostException {
265259 PrimingClient primingClient = PrimingClient.builder()
266- .withHost("localhost").withPort(scassandra.getAdminPort())
267- .build();
260+ .withHost("localhost").withPort(scassandra.getAdminPort())
261+ .build();
268262
269263 List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(5);
270264
@@ -272,20 +266,20 @@
272266 for (FakeHost otherHost : otherHosts) {
273267 InetAddress address = InetAddress.getByName(otherHost.address);
274268 rows.add(ImmutableMap.<String, Object>builder()
275- .put("peer", address)
276- .put("rpc_address", address)
277- .put("data_center", "datacenter1")
278- .put("rack", "rack1")
279- .put("release_version", "2.0.1")
280- .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++)))
281- .build());
269+ .put("peer", address)
270+ .put("rpc_address", address)
271+ .put("data_center", "datacenter1")
272+ .put("rack", "rack1")
273+ .put("release_version", "2.0.1")
274+ .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++)))
275+ .build());
282276 }
283277
284278 primingClient.prime(
285- PrimingRequest.queryBuilder()
286- .withQuery("SELECT * FROM system.peers")
287- .withColumnTypes(ScassandraCluster.SELECT_PEERS)
288- .withRows(rows)
289- .build());
279+ PrimingRequest.queryBuilder()
280+ .withQuery("SELECT * FROM system.peers")
281+ .withColumnTypes(ScassandraCluster.SELECT_PEERS)
282+ .withRows(rows)
283+ .build());
290284 }
291285 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +5 −5
@@ -108,7 +108,7 @@
108108 if (error == null) {
109109 Throwable cause = e.getCause();
110110 if (cause instanceof AssertionError)
111- error = (AssertionError)cause;
111+ error = (AssertionError) cause;
112112 else
113113 error = assertionError("Error while creating a cluster", cause);
114114 }
@@ -136,7 +136,7 @@
136136 if (error == null) {
137137 Throwable cause = e.getCause();
138138 if (cause instanceof AssertionError)
139- error = (AssertionError)cause;
139+ error = (AssertionError) cause;
140140 else
141141 error = assertionError("Error while closing a cluster", cause);
142142 }
@@ -169,19 +169,19 @@
169169 // There should be 1 control connection after initializing.
170170 cluster.init();
171171 assertEquals(cluster.manager.sessions.size(), 0);
172- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
172+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
173173 assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
174174
175175 // The first session initializes the cluster and its control connection
176176 Session session = cluster.connect();
177177 assertEquals(cluster.manager.sessions.size(), 1);
178- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
178+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
179179 assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
180180
181181 // Closing the session keeps the control connection opened
182182 session.close();
183183 assertEquals(cluster.manager.sessions.size(), 0);
184- assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
184+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
185185 assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
186186
187187 return this;
modified driver-core/src/test/java/com/datastax/driver/core/CodecRegistryTest.java +5 −6
@@ -15,17 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-
2018 import com.google.common.reflect.TypeToken;
2119 import org.apache.log4j.Level;
2220 import org.apache.log4j.Logger;
2321 import org.testng.annotations.Test;
2422
25-import static org.mockito.Mockito.mock;
26-import static org.mockito.Mockito.when;
23+import java.util.List;
2724
2825 import static com.datastax.driver.core.Assertions.assertThat;
26+import static org.mockito.Mockito.mock;
27+import static org.mockito.Mockito.when;
2928
3029 public class CodecRegistryTest {
3130 TypeToken<List<Integer>> LIST_OF_INT_TOKEN = new TypeToken<List<Integer>>() {
@@ -46,7 +45,7 @@
4645
4746 assertThat(logs.getNext()).contains("Ignoring codec newCodec");
4847 assertThat(
49- registry.codecFor(DataType.cint(), Integer.class)
48+ registry.codecFor(DataType.cint(), Integer.class)
5049 ).isNotSameAs(newCodec);
5150
5251 stopCapturingLogs(logs);
@@ -70,7 +69,7 @@
7069
7170 assertThat(logs.getNext()).contains("Ignoring codec newCodec");
7271 assertThat(
73- registry.codecFor(DataType.list(DataType.cint()), LIST_OF_INT_TOKEN)
72+ registry.codecFor(DataType.list(DataType.cint()), LIST_OF_INT_TOKEN)
7473 ).isNotSameAs(newCodec);
7574
7675 stopCapturingLogs(logs);
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 }, CodecRegistry.DEFAULT_INSTANCE);
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 }, CodecRegistry.DEFAULT_INSTANCE);
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 }, CodecRegistry.DEFAULT_INSTANCE);
6869
6970 assertTrue(defs.getType("column").equals(DataType.text()));
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +6 −5
@@ -15,18 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.CassandraVersion;
19+import org.testng.annotations.Test;
20+
1821 import java.util.Collection;
1922 import java.util.Collections;
2023
21-import org.testng.annotations.Test;
22-import static org.testng.Assert.*;
23-
24-import com.datastax.driver.core.utils.CassandraVersion;
24+import static org.testng.Assert.assertFalse;
25+import static org.testng.Assert.assertTrue;
2526
2627 /**
2728 * Test {@link ResultSet#wasApplied()} for conditional updates.
2829 */
29-@CassandraVersion(major=2.0, description="Conditional Updates requires 2.0+.")
30+@CassandraVersion(major = 2.0, description = "Conditional Updates requires 2.0+.")
3031 public class ConditionalUpdateTest extends CCMBridge.PerClassSingleNodeCluster {
3132
3233 @Override
modified driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java +16 −16
@@ -34,32 +34,32 @@
3434 public class ConnectionReleaseTest extends ScassandraTestBase {
3535
3636 /**
37- * <p>
37+ * <p/>
3838 * Validates that when a future is set that the stream associated with the future's request is released.
3939 * This prevents situations where a user may not be specifying a separate executor on a callback/
4040 * transform to a ResultSetFuture, which is not recommended, causing executeAsync to block in borrowConnection
4141 * until stream ids become available.
42- *
42+ * <p/>
4343 * Executes the following:
44- *
44+ * <p/>
4545 * <ol>
46- * <li>Sets # of connections per host to 1.</li>
47- * <li>Sends MAX_STREAM_PER_CONNECTION-1 requests that take 10 seconds to execute.</li>
48- * <li>Calls executeAsync to retrieve records from test1 with k=1.</li>
49- * <li>Transforms executeAsync to take the 'c' column from the result and query test2.
50- * This is done without an executor to ensure the netty worker is used and has to wait for the function
51- * completion.</li>
52- * <li>Asserts that the transformed future completes within pool timeout and the value is as expected.</li>
46+ * <li>Sets # of connections per host to 1.</li>
47+ * <li>Sends MAX_STREAM_PER_CONNECTION-1 requests that take 10 seconds to execute.</li>
48+ * <li>Calls executeAsync to retrieve records from test1 with k=1.</li>
49+ * <li>Transforms executeAsync to take the 'c' column from the result and query test2.
50+ * This is done without an executor to ensure the netty worker is used and has to wait for the function
51+ * completion.</li>
52+ * <li>Asserts that the transformed future completes within pool timeout and the value is as expected.</li>
5353 * </ol>
5454 *
5555 * @jira_ticket JAVA-666
5656 * @expected_result Are able to transform a Future without hanging in executeAsync as connection should be freed
57- * before the transform function is called.
57+ * before the transform function is called.
5858 * @test_category queries:async
5959 * @since 2.0.10, 2.1.6
6060 */
6161 @SuppressWarnings("unchecked")
62- @Test(groups="short")
62+ @Test(groups = "short")
6363 public void should_release_connection_before_completing_future() throws Exception {
6464 Cluster cluster = null;
6565 Collection<ResultSetFuture> mockFutures = Lists.newArrayList();
@@ -93,7 +93,7 @@
9393
9494 final Session session = cluster.connect("ks");
9595 // Consume all stream ids except one.
96- for(int i = 0; i < StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2-1; i++)
96+ for (int i = 0; i < StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2 - 1; i++)
9797 mockFutures.add(session.executeAsync("mock query"));
9898
9999
@@ -115,15 +115,15 @@
115115 try {
116116 ResultSet result = future.get(waitTimeInMs, TimeUnit.MILLISECONDS);
117117 assertThat(result.one().getString("n")).isEqualTo("world");
118- } catch (TimeoutException e) {
118+ } catch (TimeoutException e) {
119119 fail("Future timed out after " + waitTimeInMs + "ms. " +
120120 "There is a strong possibility connection is not being released.");
121121 }
122122 } finally {
123123 // Cancel all pending requests.
124- for(ResultSetFuture future : mockFutures)
124+ for (ResultSetFuture future : mockFutures)
125125 future.cancel(true);
126- if(cluster != null)
126+ if (cluster != null)
127127 cluster.close();
128128 }
129129 }
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +91 −92
@@ -15,15 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.EnumSet;
20-import java.util.List;
21-import java.util.Set;
22-
23-import org.slf4j.Logger;
24-import org.slf4j.LoggerFactory;
25-import org.testng.annotations.Test;
26-
2718 import com.datastax.driver.core.exceptions.InvalidQueryException;
2819 import com.datastax.driver.core.exceptions.ReadTimeoutException;
2920 import com.datastax.driver.core.exceptions.UnavailableException;
@@ -32,6 +23,14 @@
3223 import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
3324 import com.datastax.driver.core.policies.RoundRobinPolicy;
3425 import com.datastax.driver.core.policies.TokenAwarePolicy;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+import org.testng.annotations.Test;
29+
30+import java.util.Arrays;
31+import java.util.EnumSet;
32+import java.util.List;
33+import java.util.Set;
3534
3635 import static com.datastax.driver.core.TestUtils.stopAndWait;
3736 import static org.testng.Assert.assertTrue;
@@ -61,13 +60,13 @@
6160 List<ConsistencyLevel> acceptedList = Arrays.asList(ConsistencyLevel.ANY);
6261
6362 List<ConsistencyLevel> failList = Arrays.asList(
64- ConsistencyLevel.ONE,
65- ConsistencyLevel.TWO,
66- ConsistencyLevel.THREE,
67- ConsistencyLevel.QUORUM,
68- ConsistencyLevel.ALL,
69- ConsistencyLevel.LOCAL_QUORUM,
70- ConsistencyLevel.EACH_QUORUM);
63+ ConsistencyLevel.ONE,
64+ ConsistencyLevel.TWO,
65+ ConsistencyLevel.THREE,
66+ ConsistencyLevel.QUORUM,
67+ ConsistencyLevel.ALL,
68+ ConsistencyLevel.LOCAL_QUORUM,
69+ ConsistencyLevel.EACH_QUORUM);
7170
7271 // Test successful writes
7372 for (ConsistencyLevel cl : acceptedList) {
@@ -84,7 +83,7 @@
8483 query(c, 12, cl);
8584 } catch (InvalidQueryException e) {
8685 List<String> acceptableErrorMessages = Arrays.asList(
87- "ANY ConsistencyLevel is only supported for writes");
86+ "ANY ConsistencyLevel is only supported for writes");
8887 assertTrue(acceptableErrorMessages.contains(e.getMessage()));
8988 }
9089 }
@@ -96,8 +95,8 @@
9695 fail(String.format("Test passed at CL.%s.", cl));
9796 } catch (InvalidQueryException e) {
9897 List<String> acceptableErrorMessages = Arrays.asList(
99- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
100- "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
98+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
99+ "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
101100 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
102101 } catch (UnavailableException e) {
103102 // expected to fail when the client has already marked the
@@ -115,8 +114,8 @@
115114 fail(String.format("Test passed at CL.%s.", cl));
116115 } catch (InvalidQueryException e) {
117116 List<String> acceptableErrorMessages = Arrays.asList(
118- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
119- "EACH_QUORUM ConsistencyLevel is only supported for writes");
117+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
118+ "EACH_QUORUM ConsistencyLevel is only supported for writes");
120119 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
121120 } catch (ReadTimeoutException e) {
122121 // expected to fail when the client hasn't marked the
@@ -154,17 +153,17 @@
154153 stopAndWait(c, 2);
155154
156155 List<ConsistencyLevel> acceptedList = Arrays.asList(
157- ConsistencyLevel.ANY,
158- ConsistencyLevel.ONE
159- );
156+ ConsistencyLevel.ANY,
157+ ConsistencyLevel.ONE
158+ );
160159
161160 List<ConsistencyLevel> failList = Arrays.asList(
162- ConsistencyLevel.TWO,
163- ConsistencyLevel.QUORUM,
164- ConsistencyLevel.THREE,
165- ConsistencyLevel.ALL,
166- ConsistencyLevel.LOCAL_QUORUM,
167- ConsistencyLevel.EACH_QUORUM);
161+ ConsistencyLevel.TWO,
162+ ConsistencyLevel.QUORUM,
163+ ConsistencyLevel.THREE,
164+ ConsistencyLevel.ALL,
165+ ConsistencyLevel.LOCAL_QUORUM,
166+ ConsistencyLevel.EACH_QUORUM);
168167
169168 // Test successful writes
170169 for (ConsistencyLevel cl : acceptedList) {
@@ -181,7 +180,7 @@
181180 query(c, 12, cl);
182181 } catch (InvalidQueryException e) {
183182 List<String> acceptableErrorMessages = Arrays.asList(
184- "ANY ConsistencyLevel is only supported for writes");
183+ "ANY ConsistencyLevel is only supported for writes");
185184 assertTrue(acceptableErrorMessages.contains(e.getMessage()));
186185 }
187186 }
@@ -193,8 +192,8 @@
193192 fail(String.format("Test passed at CL.%s.", cl));
194193 } catch (InvalidQueryException e) {
195194 List<String> acceptableErrorMessages = Arrays.asList(
196- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
197- "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
195+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
196+ "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)");
198197 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
199198 } catch (UnavailableException e) {
200199 // expected to fail when the client has already marked the
@@ -212,8 +211,8 @@
212211 fail(String.format("Test passed at CL.%s.", cl));
213212 } catch (InvalidQueryException e) {
214213 List<String> acceptableErrorMessages = Arrays.asList(
215- "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
216- "EACH_QUORUM ConsistencyLevel is only supported for writes");
214+ "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
215+ "EACH_QUORUM ConsistencyLevel is only supported for writes");
217216 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
218217 } catch (ReadTimeoutException e) {
219218 // expected to fail when the client hasn't marked the
@@ -256,18 +255,18 @@
256255 cls.remove(ConsistencyLevel.LOCAL_SERIAL);
257256
258257 List<ConsistencyLevel> acceptedList = Arrays.asList(
259- ConsistencyLevel.ANY,
260- ConsistencyLevel.ONE,
261- ConsistencyLevel.TWO,
262- ConsistencyLevel.QUORUM,
263- ConsistencyLevel.LOCAL_QUORUM,
264- ConsistencyLevel.EACH_QUORUM
265- );
258+ ConsistencyLevel.ANY,
259+ ConsistencyLevel.ONE,
260+ ConsistencyLevel.TWO,
261+ ConsistencyLevel.QUORUM,
262+ ConsistencyLevel.LOCAL_QUORUM,
263+ ConsistencyLevel.EACH_QUORUM
264+ );
266265
267266 List<ConsistencyLevel> failList = Arrays.asList(
268- ConsistencyLevel.THREE,
269- ConsistencyLevel.ALL
270- );
267+ ConsistencyLevel.THREE,
268+ ConsistencyLevel.ALL
269+ );
271270
272271
273272 // Test successful writes
@@ -285,8 +284,8 @@
285284 query(c, 12, cl);
286285 } catch (InvalidQueryException e) {
287286 List<String> acceptableErrorMessages = Arrays.asList(
288- "ANY ConsistencyLevel is only supported for writes",
289- "EACH_QUORUM ConsistencyLevel is only supported for writes"
287+ "ANY ConsistencyLevel is only supported for writes",
288+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
290289 );
291290 assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
292291 }
@@ -348,17 +347,17 @@
348347 stopAndWait(c, 2);
349348
350349 List<ConsistencyLevel> acceptedList = Arrays.asList(
351- ConsistencyLevel.ANY
352- );
350+ ConsistencyLevel.ANY
351+ );
353352
354353 List<ConsistencyLevel> failList = Arrays.asList(
355- ConsistencyLevel.ONE,
356- ConsistencyLevel.TWO,
357- ConsistencyLevel.THREE,
358- ConsistencyLevel.QUORUM,
359- ConsistencyLevel.ALL,
360- ConsistencyLevel.LOCAL_QUORUM,
361- ConsistencyLevel.EACH_QUORUM);
354+ ConsistencyLevel.ONE,
355+ ConsistencyLevel.TWO,
356+ ConsistencyLevel.THREE,
357+ ConsistencyLevel.QUORUM,
358+ ConsistencyLevel.ALL,
359+ ConsistencyLevel.LOCAL_QUORUM,
360+ ConsistencyLevel.EACH_QUORUM);
362361
363362 // Test successful writes
364363 for (ConsistencyLevel cl : acceptedList) {
@@ -375,7 +374,7 @@
375374 query(c, 12, cl);
376375 } catch (InvalidQueryException e) {
377376 List<String> acceptableErrorMessages = Arrays.asList(
378- "ANY ConsistencyLevel is only supported for writes");
377+ "ANY ConsistencyLevel is only supported for writes");
379378 assertTrue(acceptableErrorMessages.contains(e.getMessage()));
380379 }
381380 }
@@ -401,7 +400,7 @@
401400 fail(String.format("Test passed at CL.%s.", cl));
402401 } catch (InvalidQueryException e) {
403402 List<String> acceptableErrorMessages = Arrays.asList(
404- "EACH_QUORUM ConsistencyLevel is only supported for writes"
403+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
405404 );
406405 assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
407406 } catch (ReadTimeoutException e) {
@@ -425,8 +424,8 @@
425424 @Test(groups = "long")
426425 public void testRFTwoDowngradingCL() throws Throwable {
427426 Cluster.Builder builder = Cluster.builder()
428- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
429- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
427+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
428+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
430429 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
431430 try {
432431
@@ -461,8 +460,8 @@
461460 query(c, 12, cl);
462461 } catch (InvalidQueryException e) {
463462 List<String> acceptableErrorMessages = Arrays.asList(
464- "ANY ConsistencyLevel is only supported for writes",
465- "EACH_QUORUM ConsistencyLevel is only supported for writes"
463+ "ANY ConsistencyLevel is only supported for writes",
464+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
466465 );
467466 assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
468467 }
@@ -486,8 +485,8 @@
486485 @Test(groups = "long")
487486 public void testRFThreeTokenAwareDowngradingCL() throws Throwable {
488487 Cluster.Builder builder = Cluster.builder()
489- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
490- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
488+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
489+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
491490 testRFThreeDowngradingCL(builder);
492491 }
493492
@@ -535,8 +534,8 @@
535534 query(c, 12, cl);
536535 } catch (InvalidQueryException e) {
537536 List<String> acceptableErrorMessages = Arrays.asList(
538- "ANY ConsistencyLevel is only supported for writes",
539- "EACH_QUORUM ConsistencyLevel is only supported for writes"
537+ "ANY ConsistencyLevel is only supported for writes",
538+ "EACH_QUORUM ConsistencyLevel is only supported for writes"
540539 );
541540 assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage());
542541 }
@@ -554,8 +553,8 @@
554553 @Test(groups = "long")
555554 public void testRFThreeDowngradingCLTwoDCs() throws Throwable {
556555 Cluster.Builder builder = Cluster.builder()
557- .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
558- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
556+ .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
557+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
559558 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder);
560559 try {
561560
@@ -576,15 +575,15 @@
576575 logger.info("Node 3 stopped.");
577576
578577 List<ConsistencyLevel> acceptedList = Arrays.asList(
579- ConsistencyLevel.ANY,
580- ConsistencyLevel.ONE,
581- ConsistencyLevel.TWO,
582- ConsistencyLevel.QUORUM,
583- ConsistencyLevel.THREE,
584- ConsistencyLevel.ALL,
585- ConsistencyLevel.LOCAL_QUORUM,
586- ConsistencyLevel.EACH_QUORUM
587- );
578+ ConsistencyLevel.ANY,
579+ ConsistencyLevel.ONE,
580+ ConsistencyLevel.TWO,
581+ ConsistencyLevel.QUORUM,
582+ ConsistencyLevel.THREE,
583+ ConsistencyLevel.ALL,
584+ ConsistencyLevel.LOCAL_QUORUM,
585+ ConsistencyLevel.EACH_QUORUM
586+ );
588587
589588 List<ConsistencyLevel> failList = Arrays.asList();
590589
@@ -605,8 +604,8 @@
605604 query(c, 12, cl);
606605 } catch (InvalidQueryException e) {
607606 List<String> acceptableErrorMessages = Arrays.asList(
608- "EACH_QUORUM ConsistencyLevel is only supported for writes",
609- "ANY ConsistencyLevel is only supported for writes");
607+ "EACH_QUORUM ConsistencyLevel is only supported for writes",
608+ "ANY ConsistencyLevel is only supported for writes");
610609 assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage()));
611610 }
612611 }
@@ -653,8 +652,8 @@
653652 @Test(groups = "long")
654653 public void testRFThreeDowngradingCLTwoDCsDCAware() throws Throwable {
655654 Cluster.Builder builder = Cluster.builder()
656- .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build(), false))
657- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
655+ .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build(), 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 +29 −32
@@ -15,29 +15,26 @@
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.*;
19+import com.datastax.driver.core.utils.CassandraVersion;
2520 import com.google.common.base.Function;
2621 import com.google.common.collect.HashMultiset;
27-import com.google.common.collect.Iterables;
2822 import com.google.common.collect.Maps;
2923 import org.slf4j.Logger;
3024 import org.slf4j.LoggerFactory;
3125 import org.testng.annotations.Test;
3226
33-import static com.google.common.collect.Lists.newArrayList;
27+import java.net.InetAddress;
28+import java.util.Collection;
29+import java.util.Iterator;
30+import java.util.Map;
31+import java.util.concurrent.TimeUnit;
32+import java.util.concurrent.atomic.AtomicInteger;
3433
3534 import static com.datastax.driver.core.Assertions.assertThat;
3635 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3736 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
38-
39-import com.datastax.driver.core.policies.*;
40-import com.datastax.driver.core.utils.CassandraVersion;
37+import static com.google.common.collect.Lists.newArrayList;
4138
4239 public class ControlConnectionTest {
4340
@@ -62,10 +59,10 @@
6259 ccm = CCMBridge.builder("test").withNodes(2).build();
6360 // We pass only the first host as contact point, so we know the control connection will be on this host
6461 cluster = Cluster.builder()
65- .addContactPoint(CCMBridge.ipOfNode(1))
66- .withReconnectionPolicy(reconnectionPolicy)
67- .withLoadBalancingPolicy(loadBalancingPolicy)
68- .build();
62+ .addContactPoint(CCMBridge.ipOfNode(1))
63+ .withReconnectionPolicy(reconnectionPolicy)
64+ .withLoadBalancingPolicy(loadBalancingPolicy)
65+ .build();
6966 cluster.init();
7067
7168 // Kill the control connection host, there should be exactly one reconnection attempt
@@ -87,12 +84,12 @@
8784
8885 /**
8986 * Test for JAVA-509: UDT definitions were not properly parsed when using the default protocol version.
90- *
87+ * <p/>
9188 * This did not appear with other tests because the UDT needs to already exist when the driver initializes.
9289 * Therefore we use two different driver instances in this test.
9390 */
9491 @Test(groups = "short")
95- @CassandraVersion(major=2.1)
92+ @CassandraVersion(major = 2.1)
9693 public void should_parse_UDT_definitions_when_using_default_protocol_version() {
9794 CCMBridge ccm = null;
9895 Cluster cluster = null;
@@ -119,15 +116,15 @@
119116 ccm.remove();
120117 }
121118 }
122-
119+
123120 /**
124121 * Ensures that if the host that the Control Connection is connected to is removed/decommissioned that the
125122 * Control Connection is reestablished to another host.
126123 *
127- * @since 2.0.9
128124 * @jira_ticket JAVA-597
129125 * @expected_result Control Connection is reestablished to another host.
130126 * @test_category control_connection
127+ * @since 2.0.9
131128 */
132129 @Test(groups = "long")
133130 public void should_reestablish_if_control_node_decommissioned() throws InterruptedException {
@@ -171,7 +168,7 @@
171168 *
172169 * @jira_ticket JAVA-618
173170 * @expected_result All 5 hosts were chosen within 100 attempts. There is a very small possibility
174- * that this may not be the case and this is not actually an error.
171+ * that this may not be the case and this is not actually an error.
175172 * @test_category control_connection
176173 * @since 2.0.11, 2.1.8, 2.2.0
177174 */
@@ -184,15 +181,15 @@
184181
185182 try {
186183 Collection<String> contactPoints = newArrayList();
187- for(int i = 1; i <= hostCount; i++) {
184+ for (int i = 1; i <= hostCount; i++) {
188185 contactPoints.add(scassandras.address(i));
189186 }
190187 final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount);
191- for(int i = 0; i < iterations; i++) {
188+ for (int i = 0; i < iterations; i++) {
192189 Cluster cluster = Cluster.builder()
193- .addContactPoints(contactPoints.toArray(new String[hostCount]))
194- .withNettyOptions(nonQuietClusterCloseOptions)
195- .build();
190+ .addContactPoints(contactPoints.toArray(new String[hostCount]))
191+ .withNettyOptions(nonQuietClusterCloseOptions)
192+ .build();
196193
197194 try {
198195 cluster.init();
@@ -201,7 +198,7 @@
201198 cluster.close();
202199 }
203200 }
204- if(logger.isDebugEnabled()) {
201+ if (logger.isDebugEnabled()) {
205202 Map<InetAddress, Integer> hostCounts = Maps.toMap(occurrencesByHost.elementSet(), new Function<InetAddress, Integer>() {
206203 @Override
207204 public Integer apply(InetAddress input) {
@@ -213,17 +210,17 @@
213210 // There is an incredibly low chance that a host may not be used based on randomness.
214211 // This probability is very low however.
215212 assertThat(occurrencesByHost.elementSet().size())
216- .as("Not all hosts were used as contact points. There is a very small chance"
217- + " of this happening based on randomness, investigate whether or not this"
218- + " is a bug.")
219- .isEqualTo(hostCount);
213+ .as("Not all hosts were used as contact points. There is a very small chance"
214+ + " of this happening based on randomness, investigate whether or not this"
215+ + " is a bug.")
216+ .isEqualTo(hostCount);
220217 } finally {
221218 scassandras.stop();
222219 }
223220
224221 }
225222
226- static class QueryPlanCountingPolicy extends DelegatingLoadBalancingPolicy {
223+ static class QueryPlanCountingPolicy extends DelegatingLoadBalancingPolicy {
227224
228225 final AtomicInteger counter = new AtomicInteger();
229226
modified driver-core/src/test/java/com/datastax/driver/core/CountingReconnectionPolicy.java +7 −4
@@ -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 */
@@ -50,9 +50,12 @@
5050 }
5151
5252 @Override
53- public void init(Cluster cluster) {}
53+ public void init(Cluster cluster) {
54+ }
5455
5556 @Override
56- public void close() { childPolicy.close(); }
57+ public void close() {
58+ childPolicy.close();
59+ }
5760
5861 }
modified driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java +38 −35
@@ -15,12 +15,9 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Collection;
20-import java.util.Collections;
21-import java.util.HashMap;
22-import java.util.Map;
23-
18+import com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
20+import com.datastax.driver.core.utils.CassandraVersion;
2421 import com.google.common.base.Throwables;
2522 import com.google.common.collect.ImmutableList;
2623 import com.google.common.collect.ImmutableMap;
@@ -29,17 +26,18 @@
2926 import org.testng.annotations.BeforeMethod;
3027 import org.testng.annotations.Test;
3128
32-import static org.apache.log4j.Level.TRACE;
33-import static org.assertj.core.api.Assertions.assertThat;
34-import static org.assertj.core.api.Fail.fail;
35-
36-import com.datastax.driver.core.exceptions.NoHostAvailableException;
37-import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
38-import com.datastax.driver.core.utils.CassandraVersion;
29+import java.nio.ByteBuffer;
30+import java.util.Collection;
31+import java.util.Collections;
32+import java.util.HashMap;
33+import java.util.Map;
3934
4035 import static com.datastax.driver.core.ProtocolVersion.V3;
4136 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
4237 import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
38+import static org.apache.log4j.Level.TRACE;
39+import static org.assertj.core.api.Assertions.assertThat;
40+import static org.assertj.core.api.Fail.fail;
4341
4442 @CassandraVersion(major = 2.2)
4543 public class CustomPayloadTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -48,15 +46,15 @@
4846
4947 private Map<String, ByteBuffer> payload2;
5048
51- @BeforeMethod(groups = { "short", "unit" })
49+ @BeforeMethod(groups = {"short", "unit"})
5250 public void initPayloads() {
5351 payload1 = ImmutableMap.of(
54- "k1", ByteBuffer.wrap(new byte[]{ 1, 2, 3 }),
55- "k2", ByteBuffer.wrap(new byte[]{ 4, 5, 6 })
52+ "k1", ByteBuffer.wrap(new byte[]{1, 2, 3}),
53+ "k2", ByteBuffer.wrap(new byte[]{4, 5, 6})
5654 );
5755 payload2 = ImmutableMap.of(
58- "k2", ByteBuffer.wrap(new byte[]{ 1, 2 }),
59- "k3", ByteBuffer.wrap(new byte[]{ 3, 4 })
56+ "k2", ByteBuffer.wrap(new byte[]{1, 2}),
57+ "k3", ByteBuffer.wrap(new byte[]{3, 4})
6058 );
6159 }
6260
@@ -92,6 +90,7 @@
9290
9391 /**
9492 * Ensures that an incoming payload is propagated from prepared to bound statements.
93+ *
9594 * @throws Exception
9695 */
9796 @Test(groups = "short")
@@ -119,6 +118,7 @@
119118 /**
120119 * Ensures that an incoming payload is overridden by an explicitly set outgoing payload
121120 * when propagated to bound statements.
121+ *
122122 * @throws Exception
123123 */
124124 @Test(groups = "short")
@@ -146,6 +146,7 @@
146146 /**
147147 * Ensures that payloads can still be set individually on bound statements
148148 * if the prepared statement does not have a default payload.
149+ *
149150 * @throws Exception
150151 */
151152 @Test(groups = "short")
@@ -175,6 +176,7 @@
175176
176177 /**
177178 * Ensures that a custom payload is propagated throughout pages.
179+ *
178180 * @throws Exception
179181 */
180182 @Test(groups = "short")
@@ -207,7 +209,7 @@
207209 @Test(groups = "unit", expectedExceptions = NullPointerException.class)
208210 public void should_throw_npe_when_null_key_on_regular_statement() throws Exception {
209211 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
210- payload.put(null, ByteBuffer.wrap(new byte[]{ 1 }));
212+ payload.put(null, ByteBuffer.wrap(new byte[]{1}));
211213 new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1).setOutgoingPayload(payload);
212214 }
213215
@@ -221,7 +223,7 @@
221223 @Test(groups = "short", expectedExceptions = NullPointerException.class)
222224 public void should_throw_npe_when_null_key_on_prepared_statement() throws Exception {
223225 Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>();
224- payload.put(null, ByteBuffer.wrap(new byte[]{ 1 }));
226+ payload.put(null, ByteBuffer.wrap(new byte[]{1}));
225227 session.prepare(new SimpleStatement("SELECT c2 FROM t1 where c1 = 1")).setOutgoingPayload(payload);
226228 }
227229
@@ -238,10 +240,10 @@
238240 Session v3session = null;
239241 try {
240242 v3cluster = Cluster.builder()
241- .addContactPointsWithPorts(ImmutableList.of(hostAddress))
242- .withProtocolVersion(V3)
243- .build()
244- .init();
243+ .addContactPointsWithPorts(ImmutableList.of(hostAddress))
244+ .withProtocolVersion(V3)
245+ .build()
246+ .init();
245247 v3session = v3cluster.connect();
246248 Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1);
247249 statement.setOutgoingPayload(payload1);
@@ -249,15 +251,15 @@
249251 fail("Should not send custom payloads with protocol V3");
250252 } catch (NoHostAvailableException nhae) {
251253 assertThat(nhae.getErrors().values())
252- .extracting(new Extractor<Throwable, Throwable>() {
253- @Override
254- public Throwable extract(Throwable input) {
255- return Throwables.getRootCause(input);
256- }
257- })
258- .hasOnlyElementsOfType(UnsupportedFeatureException.class)
259- .extracting("message")
260- .containsOnly("Unsupported feature with the native protocol V3 (which is currently in use): Custom payloads are only supported since native protocol V4");
254+ .extracting(new Extractor<Throwable, Throwable>() {
255+ @Override
256+ public Throwable extract(Throwable input) {
257+ return Throwables.getRootCause(input);
258+ }
259+ })
260+ .hasOnlyElementsOfType(UnsupportedFeatureException.class)
261+ .extracting("message")
262+ .containsOnly("Unsupported feature with the native protocol V3 (which is currently in use): Custom payloads are only supported since native protocol V4");
261263 } finally {
262264 if (v3session != null)
263265 v3session.close();
@@ -270,6 +272,7 @@
270272
271273 /**
272274 * Ensures that when debugging custom payloads, the driver will print appropriate log messages.
275+ *
273276 * @throws Exception
274277 */
275278 @Test(groups = "short")
@@ -284,8 +287,8 @@
284287 session.execute(statement);
285288 String logs = appender.waitAndGet(10000);
286289 assertThat(logs)
287- .contains("Sending payload: {k1:0x010203, k2:0x040506} (20 bytes total)")
288- .contains("Received payload: {k1:0x010203, k2:0x040506} (20 bytes total)");
290+ .contains("Sending payload: {k1:0x010203, k2:0x040506} (20 bytes total)")
291+ .contains("Received payload: {k1:0x010203, k2:0x040506} (20 bytes total)");
289292 } finally {
290293 logger.setLevel(null);
291294 logger.removeAppender(appender);
modified driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java +33 −34
@@ -15,16 +15,15 @@
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.nio.ByteBuffer;
1922 import java.util.ArrayList;
2023 import java.util.Collection;
2124 import java.util.Collections;
2225 import java.util.List;
2326
24-import org.testng.annotations.Test;
25-
26-import com.datastax.driver.core.utils.CassandraVersion;
27-
2827 import static com.datastax.driver.core.Assertions.assertThat;
2928 import static com.datastax.driver.core.DataType.cint;
3029 import static com.datastax.driver.core.DataType.custom;
@@ -35,25 +34,25 @@
3534 public class CustomTypeTest extends CCMBridge.PerClassSingleNodeCluster {
3635
3736 public static final DataType CUSTOM_DYNAMIC_COMPOSITE = custom(
38- "org.apache.cassandra.db.marshal.DynamicCompositeType("
39- + "s=>org.apache.cassandra.db.marshal.UTF8Type,"
40- + "i=>org.apache.cassandra.db.marshal.Int32Type)");
37+ "org.apache.cassandra.db.marshal.DynamicCompositeType("
38+ + "s=>org.apache.cassandra.db.marshal.UTF8Type,"
39+ + "i=>org.apache.cassandra.db.marshal.Int32Type)");
4140
4241 public static final DataType CUSTOM_COMPOSITE = custom(
43- "org.apache.cassandra.db.marshal.CompositeType("
44- + "org.apache.cassandra.db.marshal.UTF8Type,"
45- + "org.apache.cassandra.db.marshal.Int32Type)");
42+ "org.apache.cassandra.db.marshal.CompositeType("
43+ + "org.apache.cassandra.db.marshal.UTF8Type,"
44+ + "org.apache.cassandra.db.marshal.Int32Type)");
4645
4746 @Override
4847 protected Collection<String> getTableDefinitions() {
4948 return Collections.singleton(
50- "CREATE TABLE test ("
51- + " k int,"
52- + " c1 'DynamicCompositeType(s => UTF8Type, i => Int32Type)',"
53- + " c2 'ReversedType(CompositeType(UTF8Type, Int32Type))'," // reversed translates to CLUSTERING ORDER BY DESC
54- + " c3 'Int32Type'," // translates to int
55- + " PRIMARY KEY (k, c1, c2)"
56- + ") WITH COMPACT STORAGE"
49+ "CREATE TABLE test ("
50+ + " k int,"
51+ + " c1 'DynamicCompositeType(s => UTF8Type, i => Int32Type)',"
52+ + " c2 'ReversedType(CompositeType(UTF8Type, Int32Type))'," // reversed translates to CLUSTERING ORDER BY DESC
53+ + " c3 'Int32Type'," // translates to int
54+ + " PRIMARY KEY (k, c1, c2)"
55+ + ") WITH COMPACT STORAGE"
5756 );
5857 }
5958
@@ -61,9 +60,9 @@
6160 * Validates that columns using custom types are properly handled by the driver in the following ways:
6261 * <p/>
6362 * <ol>
64- * <li>The column metadata appropriately represents the types as {@link DataType#custom(String)}</li>
65- * <li>ReversedType is appropriately detected and the clustering order of that column is marked as descending.</li>
66- * <li>ColumnDefinitions for a column in a {@link Row} matches the custom type and that inserted data is read back properly.</li>
63+ * <li>The column metadata appropriately represents the types as {@link DataType#custom(String)}</li>
64+ * <li>ReversedType is appropriately detected and the clustering order of that column is marked as descending.</li>
65+ * <li>ColumnDefinitions for a column in a {@link Row} matches the custom type and that inserted data is read back properly.</li>
6766 * </ol>
6867 *
6968 * @jira_ticket JAVA-993
@@ -112,16 +111,16 @@
112111 * Validates that UDTs with fields using custom types are properly handled by the driver in the following ways:
113112 * <p/>
114113 * <ol>
115- * <li>The {@link UserType} metadata appropriately represents the types of fields with custom types as {@link DataType#custom(String)}</li>
116- * <li>{@link TableMetadata} with a column having a {@link UserType} is properly referenced.</li>
117- * <li>ColumnDefinitions for a column in a {@link Row} matches the {@link UserType} and that inserted data is read back properly.</li>
114+ * <li>The {@link UserType} metadata appropriately represents the types of fields with custom types as {@link DataType#custom(String)}</li>
115+ * <li>{@link TableMetadata} with a column having a {@link UserType} is properly referenced.</li>
116+ * <li>ColumnDefinitions for a column in a {@link Row} matches the {@link UserType} and that inserted data is read back properly.</li>
118117 * </ol>
119118 *
120119 * @jira_ticket JAVA-993
121120 * @test_category metadata
122121 */
123122 @Test(groups = "short")
124- @CassandraVersion(major=2.1)
123+ @CassandraVersion(major = 2.1)
125124 public void should_handle_udt_with_custom_type() {
126125 // Given: a UDT with custom types, and a table using it.
127126 session.execute("CREATE TYPE custom_udt (regular int, c1 'DynamicCompositeType(s => UTF8Type, i => Int32Type)', c2 'LongType')");
@@ -164,20 +163,20 @@
164163 for (Object p : params) {
165164 if (p instanceof Integer) {
166165 ByteBuffer elt = ByteBuffer.allocate(2 + 2 + 4 + 1);
167- elt.putShort((short)(0x8000 | 'i'));
166+ elt.putShort((short) (0x8000 | 'i'));
168167 elt.putShort((short) 4);
169- elt.putInt((Integer)p);
170- elt.put((byte)0);
168+ elt.putInt((Integer) p);
169+ elt.put((byte) 0);
171170 elt.flip();
172171 size += elt.remaining();
173172 l.add(elt);
174173 } else if (p instanceof String) {
175- ByteBuffer bytes = ByteBuffer.wrap(((String)p).getBytes());
174+ ByteBuffer bytes = ByteBuffer.wrap(((String) p).getBytes());
176175 ByteBuffer elt = ByteBuffer.allocate(2 + 2 + bytes.remaining() + 1);
177- elt.putShort((short)(0x8000 | 's'));
176+ elt.putShort((short) (0x8000 | 's'));
178177 elt.putShort((short) bytes.remaining());
179178 elt.put(bytes);
180- elt.put((byte)0);
179+ elt.put((byte) 0);
181180 elt.flip();
182181 size += elt.remaining();
183182 l.add(elt);
@@ -200,17 +199,17 @@
200199 if (p instanceof Integer) {
201200 ByteBuffer elt = ByteBuffer.allocate(2 + 4 + 1);
202201 elt.putShort((short) 4);
203- elt.putInt((Integer)p);
204- elt.put((byte)0);
202+ elt.putInt((Integer) p);
203+ elt.put((byte) 0);
205204 elt.flip();
206205 size += elt.remaining();
207206 l.add(elt);
208207 } else if (p instanceof String) {
209- ByteBuffer bytes = ByteBuffer.wrap(((String)p).getBytes());
208+ ByteBuffer bytes = ByteBuffer.wrap(((String) p).getBytes());
210209 ByteBuffer elt = ByteBuffer.allocate(2 + bytes.remaining() + 1);
211210 elt.putShort((short) bytes.remaining());
212211 elt.put(bytes);
213- elt.put((byte)0);
212+ elt.put((byte) 0);
214213 elt.flip();
215214 size += elt.remaining();
216215 l.add(elt);
modified driver-core/src/test/java/com/datastax/driver/core/DataProviders.java +9 −9
@@ -15,13 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.Iterator;
20-
2118 import com.google.common.base.Predicate;
2219 import com.google.common.collect.Iterables;
2320 import org.testng.annotations.DataProvider;
2421
22+import java.util.Arrays;
23+import java.util.Iterator;
24+
2525 public class DataProviders {
2626
2727 /**
@@ -37,7 +37,7 @@
3737 }
3838 }).iterator();
3939
40- return new Iterator<Object[]> () {
40+ return new Iterator<Object[]>() {
4141
4242 @Override
4343 public boolean hasNext() {
@@ -46,8 +46,8 @@
4646
4747 @Override
4848 public Object[] next() {
49- return new Object[] {
50- consistencyLevels.next()
49+ return new Object[]{
50+ consistencyLevels.next()
5151 };
5252 }
5353
@@ -63,9 +63,9 @@
6363 */
6464 @DataProvider(name = "serialConsistencyLevels")
6565 public static Object[][] serialConsistencyLevels() {
66- return new Object[][] {
67- { ConsistencyLevel.SERIAL },
68- { ConsistencyLevel.LOCAL_SERIAL }
66+ return new Object[][]{
67+ {ConsistencyLevel.SERIAL},
68+ {ConsistencyLevel.LOCAL_SERIAL}
6969 };
7070 }
7171
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +3 −3
@@ -31,7 +31,7 @@
3131
3232 public DataTypeAssert isUserType(String keyspaceName, String userTypeName) {
3333 assertThat(actual).isInstanceOf(UserType.class);
34- UserType userType = (UserType)this.actual;
34+ UserType userType = (UserType) this.actual;
3535 assertThat(userType.getKeyspace()).isEqualTo(keyspaceName);
3636 assertThat(userType.getTypeName()).isEqualTo(userTypeName);
3737 return this;
@@ -39,7 +39,7 @@
3939
4040 public DataTypeAssert isShallowUserType(String keyspaceName, String userTypeName) {
4141 assertThat(actual).isInstanceOf(UserType.Shallow.class);
42- UserType.Shallow shallow = (UserType.Shallow)actual;
42+ UserType.Shallow shallow = (UserType.Shallow) actual;
4343 assertThat(shallow.keyspaceName).isEqualTo(keyspaceName);
4444 assertThat(shallow.typeName).isEqualTo(userTypeName);
4545 return this;
@@ -67,7 +67,7 @@
6767
6868 public DataTypeAssert hasField(String name, DataType expected) {
6969 assertThat(actual).isInstanceOf(UserType.class);
70- UserType userType = (UserType)this.actual;
70+ UserType userType = (UserType) this.actual;
7171 assertThat(userType.getFieldType(name)).isEqualTo(expected);
7272 return this;
7373 }
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeClassNameParserTest.java +12 −16
@@ -15,17 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Arrays;
19-import java.util.Iterator;
20-
2118 import org.testng.annotations.Test;
2219
23-import static org.testng.Assert.assertEquals;
24-import static org.testng.Assert.assertFalse;
25-import static org.testng.Assert.assertNotNull;
26-import static org.testng.Assert.assertTrue;
20+import java.util.Arrays;
21+import java.util.Iterator;
2722
2823 import static com.datastax.driver.core.Assertions.assertThat;
24+import static org.testng.Assert.*;
2925
3026 public class DataTypeClassNameParserTest {
3127
@@ -73,7 +69,7 @@
7369 public void parseUserTypes() {
7470
7571 String s = "org.apache.cassandra.db.marshal.UserType(foo,61646472657373,737472656574:org.apache.cassandra.db.marshal.UTF8Type,7a6970636f6465:org.apache.cassandra.db.marshal.Int32Type,70686f6e6573:org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UserType(foo,70686f6e65,6e616d65:org.apache.cassandra.db.marshal.UTF8Type,6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)))";
76- UserType def = (UserType)DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry);
72+ UserType def = (UserType) DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry);
7773
7874 assertEquals(def.getKeyspace(), "foo");
7975 assertEquals(def.getTypeName(), "address");
@@ -93,7 +89,7 @@
9389
9490 DataType st = field3.getType();
9591 assertEquals(st.getName(), DataType.Name.SET);
96- UserType subDef = (UserType)st.getTypeArguments().get(0);
92+ UserType subDef = (UserType) st.getTypeArguments().get(0);
9793
9894 assertEquals(subDef.getKeyspace(), "foo");
9995 assertEquals(subDef.getTypeName(), "phone");
@@ -112,7 +108,7 @@
112108 @Test(groups = "unit")
113109 public void parseTupleTest() {
114110 String s = "org.apache.cassandra.db.marshal.TupleType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FloatType)";
115- TupleType type = (TupleType)DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry);
111+ TupleType type = (TupleType) DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry);
116112 assertNotNull(type);
117113 assertEquals(type.getComponentTypes().get(0), DataType.cint());
118114 assertEquals(type.getComponentTypes().get(1), DataType.text());
@@ -126,14 +122,14 @@
126122
127123 DataType parentMap = DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry);
128124 assertThat(parentMap)
129- .hasName(DataType.Name.MAP)
130- .isNotFrozen()
131- .hasTypeArgument(0, DataType.text());
125+ .hasName(DataType.Name.MAP)
126+ .isNotFrozen()
127+ .hasTypeArgument(0, DataType.text());
132128
133129 DataType childMap = parentMap.getTypeArguments().get(1);
134130 assertThat(childMap)
135- .hasName(DataType.Name.MAP)
136- .isFrozen()
137- .hasTypeArguments(DataType.cint(), DataType.cint());
131+ .hasName(DataType.Name.MAP)
132+ .isFrozen()
133+ .hasTypeArguments(DataType.cint(), DataType.cint());
138134 }
139135 }
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeCqlNameParserTest.java +5 −6
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.utils.CassandraVersion;
2019 import com.google.common.collect.Lists;
2120 import org.testng.annotations.Test;
2221
23-import com.datastax.driver.core.utils.CassandraVersion;
22+import java.util.Collection;
2423
2524 import static com.datastax.driver.core.Assertions.assertThat;
2625 import static com.datastax.driver.core.DataType.*;
@@ -92,7 +91,7 @@
9291 UserType keyType = keyspaceMetadata.getUserType(quote("Incr,edibly\" EvilTy<>><<><p\"e"));
9392 UserType valueType = keyspaceMetadata.getUserType(quote("A"));
9493 assertThat(parse("map<frozen<\"Incr,edibly\"\" EvilTy<>><<><p\"\"e\">,frozen<\"A\">>", cluster, keyspace, keyspaceMetadata.userTypes, null, false, false))
95- .isEqualTo(map(keyType, valueType, false));
94+ .isEqualTo(map(keyType, valueType, false));
9695 }
9796
9897 @Test(groups = "short")
@@ -122,8 +121,8 @@
122121 @Override
123122 protected Collection<String> getTableDefinitions() {
124123 return Lists.newArrayList(
125- String.format("CREATE TYPE %s.\"A\" (f1 int)", keyspace),
126- String.format("CREATE TYPE %s.\"Incr,edibly\"\" EvilTy<>><<><p\"\"e\" (a frozen<\"A\">)", keyspace)
124+ String.format("CREATE TYPE %s.\"A\" (f1 int)", keyspace),
125+ String.format("CREATE TYPE %s.\"Incr,edibly\"\" EvilTy<>><<><p\"\"e\" (a frozen<\"A\">)", keyspace)
127126 );
128127 }
129128
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +37 −39
@@ -15,24 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.*;
20-import java.util.concurrent.atomic.AtomicInteger;
21-
18+import com.datastax.driver.core.utils.CassandraVersion;
2219 import com.google.common.collect.*;
2320 import org.slf4j.Logger;
2421 import org.slf4j.LoggerFactory;
2522 import org.testng.annotations.AfterClass;
2623 import org.testng.annotations.Test;
2724
25+import java.nio.ByteBuffer;
26+import java.util.*;
27+import java.util.concurrent.atomic.AtomicInteger;
28+
2829 import static org.assertj.core.api.Assertions.assertThat;
2930 import static org.assertj.core.api.Assertions.fail;
3031
31-import com.datastax.driver.core.utils.CassandraVersion;
32-
3332 /**
3433 * The goal of this test is to cover the serialization and deserialization of datatypes.
35- *
34+ * <p/>
3635 * It creates a table with a column of a given type, inserts a value and then tries to retrieve it.
3736 * There are 3 variants for the insert query: a raw string, a simple statement with a parameter
3837 * (protocol > v2 only) and a prepared statement.
@@ -55,7 +54,7 @@
5554 for (TestTable table : tables) {
5655 if (cassandraVersion.compareTo(table.minCassandraVersion) < 0)
5756 logger.debug("Skipping table because it uses a feature not supported by Cassandra {}: {}",
58- cassandraVersion, table.createStatement);
57+ cassandraVersion, table.createStatement);
5958 else
6059 statements.add(table.createStatement);
6160 }
@@ -160,8 +159,8 @@
160159 ByteBuffer[] values = statement.getValues(protocolVersion, codecRegistry);
161160 assertThat(values.length).isEqualTo(1);
162161 assertThat(values[0])
163- .as("Value not serialized as expected for " + table.sampleValue)
164- .isEqualTo(codecRegistry.codecFor(table.testColumnType).serialize(table.sampleValue, protocolVersion));
162+ .as("Value not serialized as expected for " + table.sampleValue)
163+ .isEqualTo(codecRegistry.codecFor(table.testColumnType).serialize(table.sampleValue, protocolVersion));
165164 }
166165
167166 /**
@@ -229,7 +228,7 @@
229228 for (DataType dataType : DataType.allPrimitiveTypes(TestUtils.getDesiredProtocolVersion())) {
230229 Object expectedPrimitiveValue = null;
231230 Object expectedValue = null;
232- switch(dataType.getName()) {
231+ switch (dataType.getName()) {
233232 case BIGINT:
234233 case TIME:
235234 expectedPrimitiveValue = 0L;
@@ -244,17 +243,17 @@
244243 expectedPrimitiveValue = 0;
245244 break;
246245 case SMALLINT:
247- expectedPrimitiveValue = (short)0;
246+ expectedPrimitiveValue = (short) 0;
248247 break;
249248 case TINYINT:
250- expectedPrimitiveValue = (byte)0;
249+ expectedPrimitiveValue = (byte) 0;
251250 break;
252251 case BOOLEAN:
253252 expectedPrimitiveValue = false;
254253 break;
255254 }
256255
257- if(!dataType.getName().equals(DataType.Name.COUNTER)) {
256+ if (!dataType.getName().equals(DataType.Name.COUNTER)) {
258257 tables.add(new TestTable(dataType, null, expectedValue, expectedPrimitiveValue, "1.2.0"));
259258 }
260259 }
@@ -285,8 +284,8 @@
285284 Object valueSample = valueEntry.getValue();
286285
287286 tables.add(new TestTable(DataType.map(keyType, valueType),
288- ImmutableMap.builder().put(keySample, valueSample).build(),
289- "1.2.0"));
287+ ImmutableMap.builder().put(keySample, valueSample).build(),
288+ "1.2.0"));
290289 }
291290 }
292291 return tables;
@@ -300,10 +299,10 @@
300299
301300 // Types and samples for the inner collections like frozen<list<int>>
302301 Map<DataType, Object> childCollectionSamples = ImmutableMap.<DataType, Object>builder()
303- .put(DataType.frozenList(DataType.cint()), Lists.newArrayList(1, 1))
304- .put(DataType.frozenSet(DataType.cint()), Sets.newHashSet(1, 2))
305- .put(DataType.frozenMap(DataType.cint(), DataType.cint()), ImmutableMap.<Integer, Integer>builder().put(1, 2).put(3, 4).build())
306- .build();
302+ .put(DataType.frozenList(DataType.cint()), Lists.newArrayList(1, 1))
303+ .put(DataType.frozenSet(DataType.cint()), Sets.newHashSet(1, 2))
304+ .put(DataType.frozenMap(DataType.cint(), DataType.cint()), ImmutableMap.<Integer, Integer>builder().put(1, 2).put(3, 4).build())
305+ .build();
307306
308307 for (Map.Entry<DataType, Object> entry : childCollectionSamples.entrySet()) {
309308 DataType elementType = entry.getKey();
@@ -317,7 +316,7 @@
317316 Object valueSample = valueEntry.getValue();
318317
319318 tables.add(new TestTable(DataType.map(elementType, valueType),
320- ImmutableMap.builder().put(elementSample, valueSample).build(), "2.1.3"));
319+ ImmutableMap.builder().put(elementSample, valueSample).build(), "2.1.3"));
321320 }
322321 }
323322 return tables;
@@ -345,8 +344,8 @@
345344 DataType argument = type.getTypeArguments().get(typeIdx);
346345 boolean isAtBottom = !(argument instanceof DataType.CollectionType);
347346
348- if(isAtBottom) {
349- switch(type.getName()) {
347+ if (isAtBottom) {
348+ switch (type.getName()) {
350349 case LIST:
351350 return Lists.newArrayList(1, 2, 3);
352351 case SET:
@@ -358,24 +357,23 @@
358357 map.put(5, 6);
359358 return map;
360359 }
361- }
362- else {
363- switch(type.getName()) {
360+ } else {
361+ switch (type.getName()) {
364362 case LIST:
365363 List<Object> l = Lists.newArrayListWithExpectedSize(2);
366- for(int i = 0; i < 5; i++) {
364+ for (int i = 0; i < 5; i++) {
367365 l.add(nestedObject(argument));
368366 }
369367 return l;
370368 case SET:
371369 Set<Object> s = Sets.newHashSet();
372- for(int i = 0; i < 5; i++) {
370+ for (int i = 0; i < 5; i++) {
373371 s.add(nestedObject(argument));
374372 }
375373 return s;
376374 case MAP:
377375 Map<Integer, Object> map = Maps.newHashMap();
378- for(int i = 0; i < 5; i++) {
376+ for (int i = 0; i < 5; i++) {
379377 map.put(i, nestedObject(argument));
380378 }
381379 return map;
@@ -386,7 +384,7 @@
386384
387385 /**
388386 * @param baseType The base type to use, one of SET, MAP, LIST.
389- * @param depth How many subcollections to generate.
387+ * @param depth How many subcollections to generate.
390388 * @return a DataType that is a nested collection with the given baseType with the
391389 * given depth.
392390 */
@@ -396,16 +394,16 @@
396394
397395 for (int i = 1; i <= depth; i++) {
398396 int chooser = r.nextInt(3);
399- if(t == null) {
400- if(chooser == 0) {
397+ if (t == null) {
398+ if (chooser == 0) {
401399 t = DataType.frozenList(DataType.cint());
402- } else if(chooser == 1) {
400+ } else if (chooser == 1) {
403401 t = DataType.frozenSet(DataType.cint());
404402 } else {
405403 t = DataType.frozenMap(DataType.cint(), DataType.cint());
406404 }
407- } else if(i == depth) {
408- switch(baseType) {
405+ } else if (i == depth) {
406+ switch (baseType) {
409407 case LIST:
410408 return DataType.list(t);
411409 case SET:
@@ -414,9 +412,9 @@
414412 return DataType.map(DataType.cint(), t);
415413 }
416414 } else {
417- if(chooser == 0) {
415+ if (chooser == 0) {
418416 t = DataType.frozenList(t);
419- } else if(chooser == 1) {
417+ } else if (chooser == 1) {
420418 t = DataType.frozenSet(t);
421419 } else {
422420 t = DataType.frozenMap(DataType.cint(), t);
@@ -472,8 +470,8 @@
472470 return data.getSet(0, codecRegistry.codecFor(dataType.getTypeArguments().get(0)).getJavaType());
473471 case MAP:
474472 return data.getMap(0,
475- codecRegistry.codecFor(dataType.getTypeArguments().get(0)).getJavaType(),
476- codecRegistry.codecFor(dataType.getTypeArguments().get(1)).getJavaType());
473+ codecRegistry.codecFor(dataType.getTypeArguments().get(0)).getJavaType(),
474+ codecRegistry.codecFor(dataType.getTypeArguments().get(1)).getJavaType());
477475 case CUSTOM:
478476 case COUNTER:
479477 default:
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +81 −73
@@ -15,23 +15,21 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
19+import com.datastax.driver.core.utils.Bytes;
20+import org.testng.annotations.Test;
21+
1822 import java.math.BigDecimal;
1923 import java.math.BigInteger;
2024 import java.net.InetAddress;
2125 import java.nio.ByteBuffer;
2226 import java.util.*;
2327
24-import org.testng.annotations.Test;
25-
28+import static com.datastax.driver.core.Assertions.assertThat;
2629 import static com.google.common.collect.Lists.newArrayList;
2730 import static org.testng.Assert.assertEquals;
2831 import static org.testng.Assert.fail;
2932
30-import com.datastax.driver.core.exceptions.InvalidTypeException;
31-import com.datastax.driver.core.utils.Bytes;
32-
33-import static com.datastax.driver.core.Assertions.assertThat;
34-
3533 /**
3634 * DataType simple unit tests.
3735 */
@@ -45,13 +43,21 @@
4543 return t.getName() == DataType.Name.COUNTER;
4644 }
4745
48- /** A test value for a primitive data type */
46+ /**
47+ * A test value for a primitive data type
48+ */
4949 static class TestValue {
50- /** The value as a Java object */
50+ /**
51+ * The value as a Java object
52+ */
5153 final Object javaObject;
52- /** A CQL string that should parse to the value */
54+ /**
55+ * A CQL string that should parse to the value
56+ */
5357 final String cqlInputString;
54- /** How the value should be formatted in CQL */
58+ /**
59+ * How the value should be formatted in CQL
60+ */
5561 final String cqlOutputString;
5662
5763 TestValue(Object javaObject, String cqlInputString, String cqlOutputString) {
@@ -67,98 +73,98 @@
6773 case TEXT:
6874 case VARCHAR:
6975 return new TestValue[]{
70- new TestValue("foo", "'foo'", "'foo'"),
71- new TestValue("fo'o", "'fo''o'", "'fo''o'"),
72- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
76+ new TestValue("foo", "'foo'", "'foo'"),
77+ new TestValue("fo'o", "'fo''o'", "'fo''o'"),
78+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
7379 case BIGINT:
7480 return new TestValue[]{
75- new TestValue(42L, "42", "42"),
76- new TestValue(91294377723L, "91294377723", "91294377723"),
77- new TestValue(-133L, "-133", "-133"),
78- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
81+ new TestValue(42L, "42", "42"),
82+ new TestValue(91294377723L, "91294377723", "91294377723"),
83+ new TestValue(-133L, "-133", "-133"),
84+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
7985 case TIMESTAMP:
8086 // input: single quotes are optional for long literals, mandatory for date patterns
8187 return new TestValue[]{
82- new TestValue(new Date(42L), "42", "42"),
83- new TestValue(new Date(91294377723L), "91294377723", "91294377723"),
84- new TestValue(new Date(-133L), "-133", "-133"),
85- new TestValue(new Date(784041330999L), "'1994-11-05T14:15:30.999+0100'", "784041330999"),
86- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
88+ new TestValue(new Date(42L), "42", "42"),
89+ new TestValue(new Date(91294377723L), "91294377723", "91294377723"),
90+ new TestValue(new Date(-133L), "-133", "-133"),
91+ new TestValue(new Date(784041330999L), "'1994-11-05T14:15:30.999+0100'", "784041330999"),
92+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
8793 case DATE:
8894 // input: single quotes are optional for long literals, mandatory for date patterns
8995 return new TestValue[]{
90- new TestValue(LocalDate.fromDaysSinceEpoch(16071), "'2014-01-01'", "'2014-01-01'"),
91- new TestValue(LocalDate.fromDaysSinceEpoch(0), "'1970-01-01'", "'1970-01-01'"),
92- new TestValue(LocalDate.fromDaysSinceEpoch((int)(2147483648L - (1L << 31))), "'2147483648'", "'1970-01-01'"),
93- new TestValue(LocalDate.fromDaysSinceEpoch((int)(0 - (1L << 31))), "0", "'-5877641-06-23'"),
94- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
96+ new TestValue(LocalDate.fromDaysSinceEpoch(16071), "'2014-01-01'", "'2014-01-01'"),
97+ new TestValue(LocalDate.fromDaysSinceEpoch(0), "'1970-01-01'", "'1970-01-01'"),
98+ new TestValue(LocalDate.fromDaysSinceEpoch((int) (2147483648L - (1L << 31))), "'2147483648'", "'1970-01-01'"),
99+ new TestValue(LocalDate.fromDaysSinceEpoch((int) (0 - (1L << 31))), "0", "'-5877641-06-23'"),
100+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
95101 case TIME:
96102 // input: all literals must by enclosed in single quotes
97103 return new TestValue[]{
98- new TestValue(54012123450000L, "'54012123450000'", "'15:00:12.123450000'"),
99- new TestValue(0L, "'0'", "'00:00:00.000000000'"),
100- new TestValue(54012012345000L, "'15:00:12.012345000'", "'15:00:12.012345000'"),
101- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
104+ new TestValue(54012123450000L, "'54012123450000'", "'15:00:12.123450000'"),
105+ new TestValue(0L, "'0'", "'00:00:00.000000000'"),
106+ new TestValue(54012012345000L, "'15:00:12.012345000'", "'15:00:12.012345000'"),
107+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
102108 case BLOB:
103109 return new TestValue[]{
104- new TestValue(Bytes.fromHexString("0x2450"), "0x2450", "0x2450"),
105- new TestValue(ByteBuffer.allocate(0), "0x", "0x"),
106- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
110+ new TestValue(Bytes.fromHexString("0x2450"), "0x2450", "0x2450"),
111+ new TestValue(ByteBuffer.allocate(0), "0x", "0x"),
112+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
107113 case BOOLEAN:
108114 return new TestValue[]{
109- new TestValue(true, "true", "true"),
110- new TestValue(false, "false", "false"),
111- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
115+ new TestValue(true, "true", "true"),
116+ new TestValue(false, "false", "false"),
117+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
112118 case DECIMAL:
113119 return new TestValue[]{
114- new TestValue(new BigDecimal("1.23E+8"), "1.23E+8", "1.23E+8"),
115- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
120+ new TestValue(new BigDecimal("1.23E+8"), "1.23E+8", "1.23E+8"),
121+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
116122 case DOUBLE:
117123 return new TestValue[]{
118- new TestValue(2.39324324, "2.39324324", "2.39324324"),
119- new TestValue(-12., "-12.0", "-12.0"),
120- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
124+ new TestValue(2.39324324, "2.39324324", "2.39324324"),
125+ new TestValue(-12., "-12.0", "-12.0"),
126+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
121127 case FLOAT:
122128 return new TestValue[]{
123- new TestValue(2.39f, "2.39", "2.39"),
124- new TestValue(-12.f, "-12.0", "-12.0"),
125- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
129+ new TestValue(2.39f, "2.39", "2.39"),
130+ new TestValue(-12.f, "-12.0", "-12.0"),
131+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
126132 case INET:
127133 try {
128134 return new TestValue[]{
129- new TestValue(InetAddress.getByName("128.2.12.3"), "'128.2.12.3'", "'128.2.12.3'"),
130- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
135+ new TestValue(InetAddress.getByName("128.2.12.3"), "'128.2.12.3'", "'128.2.12.3'"),
136+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
131137 } catch (java.net.UnknownHostException e) {
132138 throw new RuntimeException();
133139 }
134140 case TINYINT:
135141 return new TestValue[]{
136- new TestValue((byte)-4, "-4", "-4"),
137- new TestValue((byte)44, "44", "44"),
138- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
142+ new TestValue((byte) -4, "-4", "-4"),
143+ new TestValue((byte) 44, "44", "44"),
144+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
139145 case SMALLINT:
140146 return new TestValue[]{
141- new TestValue((short)-3, "-3", "-3"),
142- new TestValue((short)43, "43", "43"),
143- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
147+ new TestValue((short) -3, "-3", "-3"),
148+ new TestValue((short) 43, "43", "43"),
149+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
144150 case INT:
145151 return new TestValue[]{
146- new TestValue(-2, "-2", "-2"),
147- new TestValue(42, "42", "42"),
148- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
152+ new TestValue(-2, "-2", "-2"),
153+ new TestValue(42, "42", "42"),
154+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
149155 case TIMEUUID:
150156 return new TestValue[]{
151- new TestValue(UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"), "fe2b4360-28c6-11e2-81c1-0800200c9a66", "fe2b4360-28c6-11e2-81c1-0800200c9a66"),
152- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
157+ new TestValue(UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"), "fe2b4360-28c6-11e2-81c1-0800200c9a66", "fe2b4360-28c6-11e2-81c1-0800200c9a66"),
158+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
153159 case UUID:
154160 return new TestValue[]{
155- new TestValue(UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"), "fe2b4360-28c6-11e2-81c1-0800200c9a66", "fe2b4360-28c6-11e2-81c1-0800200c9a66"),
156- new TestValue(UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"), "067e6162-3b6f-4ae2-a171-2470b63dff00", "067e6162-3b6f-4ae2-a171-2470b63dff00"),
157- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
161+ new TestValue(UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"), "fe2b4360-28c6-11e2-81c1-0800200c9a66", "fe2b4360-28c6-11e2-81c1-0800200c9a66"),
162+ new TestValue(UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"), "067e6162-3b6f-4ae2-a171-2470b63dff00", "067e6162-3b6f-4ae2-a171-2470b63dff00"),
163+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
158164 case VARINT:
159165 return new TestValue[]{
160- new TestValue(new BigInteger("12387290982347987032483422342432"), "12387290982347987032483422342432", "12387290982347987032483422342432"),
161- new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL") };
166+ new TestValue(new BigInteger("12387290982347987032483422342432"), "12387290982347987032483422342432", "12387290982347987032483422342432"),
167+ new TestValue(null, null, "NULL"), new TestValue(null, "null", "NULL"), new TestValue(null, "NULL", "NULL")};
162168 default:
163169 throw new RuntimeException("Missing handling of " + dt);
164170 }
@@ -172,8 +178,8 @@
172178
173179 for (TestValue value : primitiveTestValues(dt))
174180 assertThat(codecRegistry.codecFor(dt).parse(value.cqlInputString))
175- .as("Parsing input %s to a %s", value.cqlInputString, dt)
176- .isEqualTo(value.javaObject);
181+ .as("Parsing input %s to a %s", value.cqlInputString, dt)
182+ .isEqualTo(value.javaObject);
177183 }
178184 }
179185
@@ -185,8 +191,8 @@
185191
186192 for (TestValue value : primitiveTestValues(dt))
187193 assertThat(codecRegistry.codecFor(dt).format(value.javaObject))
188- .as("Formatting a %s expecting %s", dt, value.cqlOutputString)
189- .isEqualTo(value.cqlOutputString);
194+ .as("Formatting a %s expecting %s", dt, value.cqlOutputString)
195+ .isEqualTo(value.cqlOutputString);
190196 }
191197 }
192198
@@ -234,17 +240,19 @@
234240
235241 final UserType udt1 = new UserType("ks", "t", Arrays.asList(new UserType.Field("a", DataType.blob())), protocolVersion, codecRegistry);
236242 UserType udt2 = new UserType("ks", "t", Arrays.asList(
237- new UserType.Field("t", DataType.text()),
238- new UserType.Field("i", DataType.cint()),
239- new UserType.Field("L", DataType.list(DataType.text())),
240- new UserType.Field("s", DataType.map(DataType.cint(), udt1))
243+ new UserType.Field("t", DataType.text()),
244+ new UserType.Field("i", DataType.cint()),
245+ new UserType.Field("L", DataType.list(DataType.text())),
246+ new UserType.Field("s", DataType.map(DataType.cint(), udt1))
241247 ), protocolVersion, codecRegistry);
242248
243249 UDTValue toFormat = udt2.newValue();
244250 toFormat.setString("t", "fo'o");
245251 toFormat.setInt("i", 3);
246252 toFormat.setList("\"L\"", Arrays.<String>asList("a", "b"));
247- toFormat.setMap("s", new HashMap<Integer, UDTValue>(){{ put(3, udt1.newValue().setBytes("a", ByteBuffer.wrap(new byte[]{1}))); }});
253+ toFormat.setMap("s", new HashMap<Integer, UDTValue>() {{
254+ put(3, udt1.newValue().setBytes("a", ByteBuffer.wrap(new byte[]{1})));
255+ }});
248256
249257 assertEquals(codecRegistry.codecFor(udt2).parse(toParse), toFormat);
250258 assertEquals(codecRegistry.codecFor(udt2).format(toFormat), toParse);
modified driver-core/src/test/java/com/datastax/driver/core/DirectedGraphTest.java +9 −10
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-
18+import com.datastax.driver.core.exceptions.DriverInternalError;
2019 import org.testng.annotations.Test;
2120
22-import static org.assertj.core.api.Assertions.assertThat;
21+import java.util.List;
2322
24-import com.datastax.driver.core.exceptions.DriverInternalError;
23+import static org.assertj.core.api.Assertions.assertThat;
2524
2625 public class DirectedGraphTest {
2726 @Test(groups = "unit")
@@ -34,7 +33,7 @@
3433 public void should_sort_graph_with_one_node() {
3534 DirectedGraph<String> g = new DirectedGraph<String>("A");
3635 assertThat(g.topologicalSort())
37- .containsExactly("A");
36+ .containsExactly("A");
3837 }
3938
4039 @Test(groups = "unit")
@@ -63,15 +62,15 @@
6362 // There's no guarantee on the order within the same level, so we use sublists:
6463 List<String> sorted = g.topologicalSort();
6564 assertThat(sorted.subList(0, 2))
66- .contains("G", "H");
65+ .contains("G", "H");
6766 assertThat(sorted.subList(2, 4))
68- .contains("F", "E");
67+ .contains("F", "E");
6968 assertThat(sorted.subList(4, 5))
70- .contains("D");
69+ .contains("D");
7170 assertThat(sorted.subList(5, 7))
72- .contains("C", "B" );
71+ .contains("C", "B");
7372 assertThat(sorted.subList(7, 8))
74- .contains("A");
73+ .contains("A");
7574 }
7675
7776 @Test(groups = "unit", expectedExceptions = DriverInternalError.class)
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/FunctionMetadataTest.java +41 −43
@@ -15,17 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.utils.CassandraVersion;
2019 import org.testng.annotations.Test;
2120
22-import static com.google.common.collect.Lists.newArrayList;
23-import static org.assertj.core.api.Assertions.entry;
24-
25-import com.datastax.driver.core.utils.CassandraVersion;
21+import java.util.Collection;
2622
2723 import static com.datastax.driver.core.Assertions.assertThat;
2824 import static com.datastax.driver.core.DataType.cint;
25+import static com.google.common.collect.Lists.newArrayList;
26+import static org.assertj.core.api.Assertions.entry;
2927
3028 @CassandraVersion(major = 2.2)
3129 public class FunctionMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -45,21 +43,21 @@
4543 assertThat(function.getSimpleName()).isEqualTo("plus");
4644 assertThat(function.getReturnType()).isEqualTo(cint());
4745 assertThat(function.getArguments())
48- .containsEntry("s", cint())
49- .containsEntry("v", cint());
46+ .containsEntry("s", cint())
47+ .containsEntry("v", cint());
5048 assertThat(function.getLanguage()).isEqualTo("java");
5149 assertThat(function.getBody()).isEqualTo("return s+v;");
5250 assertThat(function.isCalledOnNullInput()).isFalse();
5351 assertThat(function.toString())
54- .isEqualTo(cql);
52+ .isEqualTo(cql);
5553 assertThat(function.exportAsString())
56- .isEqualTo(String.format("CREATE FUNCTION %s.plus(\n"
57- + " s int,\n"
58- + " v int)\n"
59- + "RETURNS NULL ON NULL INPUT\n"
60- + "RETURNS int\n"
61- + "LANGUAGE java\n"
62- + "AS 'return s+v;';", this.keyspace));
54+ .isEqualTo(String.format("CREATE FUNCTION %s.plus(\n"
55+ + " s int,\n"
56+ + " v int)\n"
57+ + "RETURNS NULL ON NULL INPUT\n"
58+ + "RETURNS int\n"
59+ + "LANGUAGE java\n"
60+ + "AS 'return s+v;';", this.keyspace));
6361 }
6462
6563 @Test(groups = "short")
@@ -81,33 +79,33 @@
8179 assertThat(function.getBody()).isEqualTo("return Math.PI;");
8280 assertThat(function.isCalledOnNullInput()).isTrue();
8381 assertThat(function.toString())
84- .isEqualTo(cql);
82+ .isEqualTo(cql);
8583 assertThat(function.exportAsString())
86- .isEqualTo(String.format("CREATE FUNCTION %s.pi()\n"
87- + "CALLED ON NULL INPUT\n"
88- + "RETURNS double\n"
89- + "LANGUAGE java\n"
90- + "AS 'return Math.PI;';", this.keyspace));
84+ .isEqualTo(String.format("CREATE FUNCTION %s.pi()\n"
85+ + "CALLED ON NULL INPUT\n"
86+ + "RETURNS double\n"
87+ + "LANGUAGE java\n"
88+ + "AS 'return Math.PI;';", this.keyspace));
9189 }
9290
9391 @Test(groups = "short")
9492 public void should_parse_and_format_function_with_udts() {
9593 // given
9694 String body =
97- "//If \"called on null input\", handle nulls\n"
98- + "if(ADDRESS == null) return previous_total + 0;\n"
99- + "//User types are converted to com.datastax.driver.core.UDTValue types\n"
100- + "java.util.Set phones = ADDRESS.getSet(\"phones\", com.datastax.driver.core.UDTValue.class);\n"
101- + "return previous_total + phones.size();\n";
95+ "//If \"called on null input\", handle nulls\n"
96+ + "if(ADDRESS == null) return previous_total + 0;\n"
97+ + "//User types are converted to com.datastax.driver.core.UDTValue types\n"
98+ + "java.util.Set phones = ADDRESS.getSet(\"phones\", com.datastax.driver.core.UDTValue.class);\n"
99+ + "return previous_total + phones.size();\n";
102100 String cqlFunction = String.format(
103- "CREATE FUNCTION %s.\"NUM_PHONES_ACCU\"(previous_total int,\"ADDRESS\" \"Address\") "
104- + "CALLED ON NULL INPUT "
105- + "RETURNS int "
106- + "LANGUAGE java "
107- + "AS "
108- + "'"
109- + body
110- + "';", keyspace);
101+ "CREATE FUNCTION %s.\"NUM_PHONES_ACCU\"(previous_total int,\"ADDRESS\" \"Address\") "
102+ + "CALLED ON NULL INPUT "
103+ + "RETURNS int "
104+ + "LANGUAGE java "
105+ + "AS "
106+ + "'"
107+ + body
108+ + "';", keyspace);
111109 // when
112110 session.execute(cqlFunction);
113111 // then
@@ -130,14 +128,14 @@
130128 @Override
131129 protected Collection<String> getTableDefinitions() {
132130 return newArrayList(
133- String.format("CREATE TYPE IF NOT EXISTS %s.\"Phone\" (number text)", keyspace),
134- String.format("CREATE TYPE IF NOT EXISTS %s.\"Address\" ("
135- + " street text,"
136- + " city text,"
137- + " zip int,"
138- + " phones frozen<set<frozen<\"Phone\">>>,"
139- + " location frozen<tuple<float, float>>"
140- + ")", keyspace)
131+ String.format("CREATE TYPE IF NOT EXISTS %s.\"Phone\" (number text)", keyspace),
132+ String.format("CREATE TYPE IF NOT EXISTS %s.\"Address\" ("
133+ + " street text,"
134+ + " city text,"
135+ + " zip int,"
136+ + " phones frozen<set<frozen<\"Phone\">>>,"
137+ + " location frozen<tuple<float, float>>"
138+ + ")", keyspace)
141139 );
142140 }
143141
modified driver-core/src/test/java/com/datastax/driver/core/GettableDataIntegrationTest.java +63 −68
@@ -15,31 +15,24 @@
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.net.UnknownHostException;
22-import java.nio.ByteBuffer;
23-import java.util.Collection;
24-import java.util.Date;
25-import java.util.List;
26-import java.util.Map;
27-import java.util.Set;
28-import java.util.UUID;
29-import java.util.concurrent.atomic.AtomicInteger;
30-
3118 import com.google.common.collect.ImmutableMap;
3219 import com.google.common.collect.ImmutableSet;
3320 import com.google.common.reflect.TypeToken;
3421 import org.testng.annotations.BeforeClass;
3522 import org.testng.annotations.Test;
3623
37-import static com.google.common.collect.Lists.newArrayList;
38-import static org.assertj.core.api.Assertions.assertThat;
24+import java.math.BigDecimal;
25+import java.math.BigInteger;
26+import java.net.InetAddress;
27+import java.net.UnknownHostException;
28+import java.nio.ByteBuffer;
29+import java.util.*;
30+import java.util.concurrent.atomic.AtomicInteger;
3931
40-import static com.datastax.driver.core.TypeTokens.listOf;
4132 import static com.datastax.driver.core.TestUtils.getValue;
4233 import static com.datastax.driver.core.TestUtils.setValue;
34+import static com.google.common.collect.Lists.newArrayList;
35+import static org.assertj.core.api.Assertions.assertThat;
4336
4437 public class GettableDataIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
4538
@@ -55,8 +48,8 @@
5548 protected Collection<String> getTableDefinitions() {
5649 // only add tuples / nested collections at > 2.1.3.
5750 return newArrayList("CREATE TABLE codec_mapping (k int PRIMARY KEY, "
58- + "v int, l list<int>, m map<int,int>" +
59- (is21 ? ", t tuple<int,int>, s set<frozen<list<int>>>)" : ")"));
51+ + "v int, l list<int>, m map<int,int>" +
52+ (is21 ? ", t tuple<int,int>, s set<frozen<list<int>>>)" : ")"));
6053 }
6154
6255 @Override
@@ -66,58 +59,60 @@
6659
6760 @BeforeClass(groups = "short")
6861 public void setUpRegistry() {
69- for(TypeMapping<?> mapping : mappings) {
62+ for (TypeMapping<?> mapping : mappings) {
7063 registry.register(mapping.codec);
7164 }
7265 }
7366
7467 static final ByteBuffer intBuf = ByteBuffer.allocate(4);
68+
7569 static {
7670 intBuf.putInt(1);
7771 intBuf.flip();
7872 }
7973
8074 static InetAddress localhost;
75+
8176 static {
8277 try {
8378 localhost = InetAddress.getLocalHost();
84- } catch(UnknownHostException e) {
79+ } catch (UnknownHostException e) {
8580 localhost = null;
8681 }
8782 }
8883
8984 // Mappings of Codecs, Data Type to access as (used for determining what get|set method to call), value to set.
9085 private TypeMapping<?>[] mappings = {
91- // set|getString
92- new TypeMapping<String>(new IntToStringCodec(), DataType.varchar(), "1"),
93- // set|getLong
94- new TypeMapping<Long>(new IntToLongCodec(), DataType.bigint(), 1L),
95- // set|getBytes
96- new TypeMapping<ByteBuffer>(new IntToByteBufferCodec(), DataType.blob(), intBuf),
97- // set|getBool
98- new TypeMapping<Boolean>(new IntToBooleanCodec(), DataType.cboolean(), true),
99- // set|getDecimal
100- new TypeMapping<BigDecimal>(new IntToBigDecimalCodec(), DataType.decimal(), new BigDecimal(1)),
101- // set|getDouble
102- new TypeMapping<Double>(new IntToDoubleCodec(), DataType.cdouble(), 1.0d),
103- // set|getFloat
104- new TypeMapping<Float>(new IntToFloatCodec(), DataType.cfloat(), 1.0f),
105- // set|getInet
106- new TypeMapping<InetAddress>(new IntToInetAddressCodec(), DataType.inet(), localhost),
107- // set|getTime
108- new TypeMapping<Long>(new IntToLongCodec(), DataType.time(), 8675309L),
109- // set|getByte
110- new TypeMapping<Byte>(new IntToByteCodec(), DataType.tinyint(), (byte)0xCF),
111- // set|getShort
112- new TypeMapping<Short>(new IntToShortCodec(), DataType.smallint(), (short)1003),
113- // set|getTimestamp
114- new TypeMapping<Date>(new IntToDateCodec(), DataType.timestamp(), new Date(124677)),
115- // set|getDate
116- new TypeMapping<LocalDate>(new IntToLocalDateCodec(), DataType.date(), LocalDate.fromDaysSinceEpoch(1523)),
117- // set|getUUID
118- new TypeMapping<UUID>(new IntToUUIDCodec(), DataType.uuid(), new UUID(244242, 0)),
119- // set|getVarint
120- new TypeMapping<BigInteger>(new IntToBigIntegerCodec(), DataType.varint(), BigInteger.valueOf(4566432L))
86+ // set|getString
87+ new TypeMapping<String>(new IntToStringCodec(), DataType.varchar(), "1"),
88+ // set|getLong
89+ new TypeMapping<Long>(new IntToLongCodec(), DataType.bigint(), 1L),
90+ // set|getBytes
91+ new TypeMapping<ByteBuffer>(new IntToByteBufferCodec(), DataType.blob(), intBuf),
92+ // set|getBool
93+ new TypeMapping<Boolean>(new IntToBooleanCodec(), DataType.cboolean(), true),
94+ // set|getDecimal
95+ new TypeMapping<BigDecimal>(new IntToBigDecimalCodec(), DataType.decimal(), new BigDecimal(1)),
96+ // set|getDouble
97+ new TypeMapping<Double>(new IntToDoubleCodec(), DataType.cdouble(), 1.0d),
98+ // set|getFloat
99+ new TypeMapping<Float>(new IntToFloatCodec(), DataType.cfloat(), 1.0f),
100+ // set|getInet
101+ new TypeMapping<InetAddress>(new IntToInetAddressCodec(), DataType.inet(), localhost),
102+ // set|getTime
103+ new TypeMapping<Long>(new IntToLongCodec(), DataType.time(), 8675309L),
104+ // set|getByte
105+ new TypeMapping<Byte>(new IntToByteCodec(), DataType.tinyint(), (byte) 0xCF),
106+ // set|getShort
107+ new TypeMapping<Short>(new IntToShortCodec(), DataType.smallint(), (short) 1003),
108+ // set|getTimestamp
109+ new TypeMapping<Date>(new IntToDateCodec(), DataType.timestamp(), new Date(124677)),
110+ // set|getDate
111+ new TypeMapping<LocalDate>(new IntToLocalDateCodec(), DataType.date(), LocalDate.fromDaysSinceEpoch(1523)),
112+ // set|getUUID
113+ new TypeMapping<UUID>(new IntToUUIDCodec(), DataType.uuid(), new UUID(244242, 0)),
114+ // set|getVarint
115+ new TypeMapping<BigInteger>(new IntToBigIntegerCodec(), DataType.varint(), BigInteger.valueOf(4566432L))
121116 };
122117
123118 /**
@@ -130,13 +125,13 @@
130125 * type of the column.
131126 * <p/>
132127 * Executes the following for each set|get set:
133- *
128+ * <p/>
134129 * <ol>
135- * <li>Insert row using a prepared statement and binding by name.</li>
136- * <li>Insert row using a prepared statement and binding by index.</li>
137- * <li>Insert row using a prepared statement and binding everything at once.</li>
138- * <li>Retrieve inserted rows and get values by name.</li>
139- * <li>Retrieve inserted rows and get values by index.</li>
130+ * <li>Insert row using a prepared statement and binding by name.</li>
131+ * <li>Insert row using a prepared statement and binding by index.</li>
132+ * <li>Insert row using a prepared statement and binding everything at once.</li>
133+ * <li>Retrieve inserted rows and get values by name.</li>
134+ * <li>Retrieve inserted rows and get values by index.</li>
140135 * </ol>
141136 *
142137 * @jira_ticket JAVA-940
@@ -149,14 +144,14 @@
149144 PreparedStatement select = session.prepare("SELECT v,l,m" + (is21 ? ",t,s" : "") + " from codec_mapping where k=?");
150145
151146 TupleType tupleType = new TupleType(newArrayList(DataType.cint(), DataType.cint()),
152- cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), registry);
147+ cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), registry);
153148
154- for(TypeMapping<?> mapping : mappings) {
149+ for (TypeMapping<?> mapping : mappings) {
155150 // Keys used to insert data in this iteration.
156151 List<Integer> keys = newArrayList();
157152
158153 // Values to store.
159- Map<Object,Object> map = ImmutableMap.of(mapping.value, mapping.value);
154+ Map<Object, Object> map = ImmutableMap.of(mapping.value, mapping.value);
160155 List<Object> list = newArrayList(mapping.value);
161156 Set<List<Object>> set = ImmutableSet.of(list);
162157 TupleValue tupleValue = new TupleValue(tupleType);
@@ -171,7 +166,7 @@
171166 setValue(byName, "v", mapping.outerType, mapping.value);
172167 byName.setList("l", list, mapping.javaType);
173168 byName.setMap("m", map, mapping.javaType, mapping.javaType);
174- if(is21) {
169+ if (is21) {
175170 byName.setTupleValue("t", tupleValue);
176171 byName.setSet("s", set, TypeTokens.listOf(mapping.javaType));
177172 }
@@ -185,7 +180,7 @@
185180 setValue(byIndex, 1, mapping.outerType, mapping.value);
186181 byIndex.setList(2, list, mapping.javaType);
187182 byIndex.setMap(3, map, mapping.javaType, mapping.javaType);
188- if(is21) {
183+ if (is21) {
189184 byIndex.setTupleValue(4, tupleValue);
190185 byIndex.setSet(5, set, TypeTokens.listOf(mapping.javaType));
191186 }
@@ -195,21 +190,21 @@
195190 BoundStatement fullBind;
196191 int fullBindKey = keyCounter.incrementAndGet();
197192 keys.add(fullBindKey);
198- if(is21) {
193+ if (is21) {
199194 fullBind = insert.bind(fullBindKey, mapping.value, list, map, tupleValue, set);
200195 } else {
201196 fullBind = insert.bind(fullBindKey, mapping.value, list, map);
202197 }
203198 session.execute(fullBind);
204199
205- for(int key : keys) {
200+ for (int key : keys) {
206201 // Retrieve by name.
207202 Row row = session.execute(select.bind(key)).one();
208203 assertThat(getValue(row, "v", mapping.outerType, registry)).isEqualTo(mapping.value);
209204 assertThat(row.getList("l", mapping.codec.getJavaType())).isEqualTo(list);
210205 assertThat(row.getMap("m", mapping.codec.getJavaType(), mapping.codec.getJavaType())).isEqualTo(map);
211206
212- if(is21) {
207+ if (is21) {
213208 TupleValue returnedTuple = row.getTupleValue("t");
214209 assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)).isEqualTo(mapping.value);
215210 assertThat(getValue(returnedTuple, 1, mapping.outerType, registry)).isEqualTo(mapping.value);
@@ -222,7 +217,7 @@
222217 assertThat(row.getList(1, mapping.codec.getJavaType())).isEqualTo(list);
223218 assertThat(row.getMap(2, mapping.codec.getJavaType(), mapping.codec.getJavaType())).isEqualTo(map);
224219
225- if(is21) {
220+ if (is21) {
226221 TupleValue returnedTuple = row.getTupleValue(3);
227222 assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)).isEqualTo(mapping.value);
228223 assertThat(getValue(returnedTuple, 1, mapping.outerType, registry)).isEqualTo(mapping.value);
@@ -242,7 +237,7 @@
242237 @SuppressWarnings("unchecked")
243238 TypeMapping(TypeCodec<T> codec, DataType outerType, T value) {
244239 this.codec = codec;
245- this.javaType = (TypeToken<Object>)codec.getJavaType();
240+ this.javaType = (TypeToken<Object>) codec.getJavaType();
246241 this.outerType = outerType;
247242 this.value = value;
248243 }
@@ -382,7 +377,7 @@
382377 byte[] address = ByteBuffer.allocate(4).putInt(value).array();
383378 try {
384379 return InetAddress.getByAddress(address);
385- } catch(UnknownHostException e) {
380+ } catch (UnknownHostException e) {
386381 return null;
387382 }
388383 }
@@ -486,7 +481,7 @@
486481
487482 @Override
488483 protected BigInteger deserialize(Integer value) {
489- return BigInteger.valueOf((long)value);
484+ return BigInteger.valueOf((long) value);
490485 }
491486
492487 @Override
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 +83 −84
@@ -15,6 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.codahale.metrics.Gauge;
19+import com.datastax.driver.core.exceptions.BusyConnectionException;
20+import com.datastax.driver.core.exceptions.ConnectionException;
21+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
22+import com.google.common.util.concurrent.Uninterruptibles;
23+import org.scassandra.cql.PrimitiveType;
24+import org.scassandra.http.client.PrimingRequest;
25+import org.testng.annotations.BeforeClass;
26+import org.testng.annotations.Test;
27+
1828 import java.net.InetSocketAddress;
1929 import java.util.Iterator;
2030 import java.util.List;
@@ -22,32 +32,19 @@
2232 import java.util.concurrent.atomic.AtomicBoolean;
2333 import java.util.concurrent.atomic.AtomicReference;
2434
35+import static com.datastax.driver.core.Assertions.assertThat;
36+import static com.google.common.collect.Lists.newArrayList;
2537 import static java.util.Collections.singletonList;
2638 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;
3639 import static org.mockito.Mockito.*;
3740 import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
3841 import static org.scassandra.http.client.PrimingRequest.then;
3942 import static org.testng.Assert.fail;
4043
41-import com.datastax.driver.core.exceptions.BusyConnectionException;
42-import com.datastax.driver.core.exceptions.ConnectionException;
43-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
44-
45-import static com.datastax.driver.core.Assertions.assertThat;
46-
4744 public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
4845
4946
50- @BeforeClass(groups={"short", "long"})
47+ @BeforeClass(groups = {"short", "long"})
5148 public void reinitializeCluster() {
5249 // Don't use the provided cluster, each test will create its own instead.
5350 cluster.close();
@@ -74,10 +71,10 @@
7471 */
7572 private List<MockRequest> sendRequests(int count, HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
7673 List<MockRequest> requests = newArrayList();
77- for(int i = 0; i < count; i++) {
74+ for (int i = 0; i < count; i++) {
7875 MockRequest request = MockRequest.send(pool);
7976 requests.add(request);
80- if(expectedConnections != null)
77+ if (expectedConnections != null)
8178 assertThat(expectedConnections).contains(request.connection);
8279 }
8380 return requests;
@@ -95,8 +92,8 @@
9592 */
9693 private void completeRequests(int count, List<MockRequest> requests) {
9794 Iterator<MockRequest> requestIt = requests.iterator();
98- for(int i = 0; i < count; i++) {
99- if(requestIt.hasNext()) {
95+ for (int i = 0; i < count; i++) {
96+ if (requestIt.hasNext()) {
10097 MockRequest request = requestIt.next();
10198 request.simulateSuccessResponse();
10299 requestIt.remove();
@@ -110,7 +107,7 @@
110107 * Completes all requests by simulating a successful response.
111108 */
112109 private void completeRequests(List<MockRequest> requests) {
113- for(MockRequest request : requests) {
110+ for (MockRequest request : requests) {
114111 request.simulateSuccessResponse();
115112 }
116113 }
@@ -119,9 +116,9 @@
119116 * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
120117 * of creating a new connection.
121118 *
122- * @since 2.0.10, 2.1.6
123119 * @jira_ticket JAVA-419
124120 * @test_category connection:connection_pool
121+ * @since 2.0.10, 2.1.6
125122 */
126123 @Test(groups = "short")
127124 public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException {
@@ -148,9 +145,9 @@
148145 * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
149146 * timeout instead of creating a new connection.
150147 *
151- * @since 2.0.10, 2.1.6
152148 * @jira_ticket JAVA-419
153149 * @test_category connection:connection_pool
150+ * @since 2.0.10, 2.1.6
154151 */
155152 @Test(groups = "short")
156153 public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
@@ -196,9 +193,9 @@
196193 /**
197194 * Ensures that if the core connection pool is full that borrowConnection will create and use a new connection.
198195 *
199- * @since 2.0.10, 2.1.6
200196 * @jira_ticket JAVA-419
201197 * @test_category connection:connection_pool
198+ * @since 2.0.10, 2.1.6
202199 */
203200 @Test(groups = "short")
204201 public void should_add_extra_connection_when_core_full() throws Exception {
@@ -226,9 +223,9 @@
226223 * Ensures that a trashed connection that has not been timed out should be resurrected into the connection pool if
227224 * borrowConnection is called and a new connection is needed.
228225 *
229- * @since 2.0.10, 2.1.6
230226 * @jira_ticket JAVA-419
231227 * @test_category connection:connection_pool
228+ * @since 2.0.10, 2.1.6
232229 */
233230 @Test(groups = "long")
234231 public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception {
@@ -286,9 +283,9 @@
286283 * Ensures that a trashed connection that has been timed out should not be resurrected into the connection pool if
287284 * borrowConnection is called and a new connection is needed.
288285 *
289- * @since 2.0.10, 2.1.6
290286 * @jira_ticket JAVA-419
291287 * @test_category connection:connection_pool
288+ * @since 2.0.10, 2.1.6
292289 */
293290 @Test(groups = "long")
294291 public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception {
@@ -340,8 +337,8 @@
340337 MockRequest request = MockRequest.send(pool);
341338 requests.add(request);
342339 assertThat(request.connection)
343- .isNotEqualTo(connection2) // should not be the full connection
344- .isNotEqualTo(connection1); // should not be the previously trashed one
340+ .isNotEqualTo(connection2) // should not be the full connection
341+ .isNotEqualTo(connection1); // should not be the previously trashed one
345342 } finally {
346343 completeRequests(requests);
347344 cluster.close();
@@ -351,9 +348,9 @@
351348 /**
352349 * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
353350 *
354- * @since 2.0.10, 2.1.6
355351 * @jira_ticket JAVA-419
356352 * @test_category connection:connection_pool
353+ * @since 2.0.10, 2.1.6
357354 */
358355 @Test(groups = "long")
359356 public void should_not_close_trashed_connection_until_no_in_flight() throws Exception {
@@ -403,9 +400,9 @@
403400 * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
404401 * the connection is put in the trash.
405402 *
406- * @since 2.0.10, 2.1.6
407403 * @jira_ticket JAVA-419
408404 * @test_category connection:connection_pool
405+ * @since 2.0.10, 2.1.6
409406 */
410407 @Test(groups = "short")
411408 public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception {
@@ -453,7 +450,7 @@
453450 * @test_category connection:connection_pool
454451 * @since 2.0.11
455452 */
456- @Test(groups="short")
453+ @Test(groups = "short")
457454 public void should_keep_host_up_when_one_connection_lost() throws Exception {
458455 Cluster cluster = createClusterBuilder().build();
459456 try {
@@ -463,7 +460,7 @@
463460
464461 // Drop a connection and ensure the host stays up.
465462 currentClient.disableListener();
466- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
463+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
467464 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
468465
469466 // connection 0 should be down, while connection 1 and the Host should remain up.
@@ -487,22 +484,22 @@
487484 * @test_category connection:connection_pool
488485 * @since 2.0.11
489486 */
490- @Test(groups="short")
487+ @Test(groups = "short")
491488 public void should_mark_host_down_when_no_connections_remaining() throws Exception {
492489 int readTimeout = 1000;
493490 int reconnectInterval = 1000;
494491 Cluster cluster = this.createClusterBuilder()
495- .withSocketOptions(new SocketOptions()
496- .setConnectTimeoutMillis(readTimeout)
497- .setReadTimeoutMillis(reconnectInterval))
498- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
492+ .withSocketOptions(new SocketOptions()
493+ .setConnectTimeoutMillis(readTimeout)
494+ .setReadTimeoutMillis(reconnectInterval))
495+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
499496 try {
500497 cluster.init();
501498
502499 Connection.Factory factory = spy(cluster.manager.connectionFactory);
503500 cluster.manager.connectionFactory = factory;
504501
505- HostConnectionPool pool = createPool(cluster, 8,8);
502+ HostConnectionPool pool = createPool(cluster, 8, 8);
506503 // copy list to track these connections.
507504 List<Connection> connections = newArrayList(pool.connections);
508505
@@ -517,13 +514,13 @@
517514 assertThat(cluster).hasClosedControlConnection();
518515
519516 // Ensure all connections are closed.
520- for(Connection connection : connections) {
517+ for (Connection connection : connections) {
521518 assertThat(connection.isClosed()).isTrue();
522519 }
523520
524521 // Expect a reconnect attempt on host after reconnect interval
525522 // on behalf of the control connection.
526- verify(factory, timeout(reconnectInterval*2).atLeastOnce()).open(host);
523+ verify(factory, timeout(reconnectInterval * 2).atLeastOnce()).open(host);
527524
528525 // Sleep for a bit to allow reconnect to fail.
529526 Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
@@ -537,9 +534,9 @@
537534 // Reconnect attempt should have been connected for control connection
538535 // and pool.
539536 // 2 attempts for connection.open (reconnect control connection and initial connection for host state).
540- verify(factory, after(reconnectInterval*2).atLeast(2)).open(host);
537+ verify(factory, after(reconnectInterval * 2).atLeast(2)).open(host);
541538 // 7 attempts for core connections after first initial connection.
542- verify(factory, timeout(reconnectInterval*2)).newConnections(any(HostConnectionPool.class), eq(7));
539+ verify(factory, timeout(reconnectInterval * 2)).newConnections(any(HostConnectionPool.class), eq(7));
543540
544541 // Wait some reasonable amount of time for connection to reestablish.
545542 Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
@@ -562,15 +559,15 @@
562559 * @test_category connection:connection_pool
563560 * @since 2.0.11
564561 */
565- @Test(groups="short")
562+ @Test(groups = "short")
566563 public void should_create_new_connections_when_connection_lost_and_under_core_connections() throws Exception {
567564 int readTimeout = 1000;
568565 int reconnectInterval = 1000;
569566 Cluster cluster = this.createClusterBuilder()
570- .withSocketOptions(new SocketOptions()
571- .setConnectTimeoutMillis(readTimeout)
572- .setReadTimeoutMillis(reconnectInterval))
573- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
567+ .withSocketOptions(new SocketOptions()
568+ .setConnectTimeoutMillis(readTimeout)
569+ .setReadTimeoutMillis(reconnectInterval))
570+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
574571 List<MockRequest> requests = newArrayList();
575572 try {
576573 cluster.init();
@@ -586,8 +583,8 @@
586583 // Drop two core connections.
587584 // Disable new connections initially and we'll eventually reenable it.
588585 currentClient.disableListener();
589- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
590- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core2.channel.localAddress()));
586+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
587+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core2.channel.localAddress()));
591588 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
592589
593590 // Since we have a connection left the host should remain up.
@@ -655,10 +652,10 @@
655652 int readTimeout = 1000;
656653 int reconnectInterval = 1000;
657654 Cluster cluster = this.createClusterBuilder()
658- .withSocketOptions(new SocketOptions()
659- .setConnectTimeoutMillis(readTimeout)
660- .setReadTimeoutMillis(reconnectInterval))
661- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
655+ .withSocketOptions(new SocketOptions()
656+ .setConnectTimeoutMillis(readTimeout)
657+ .setReadTimeoutMillis(reconnectInterval))
658+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
662659 List<MockRequest> requests = newArrayList();
663660 try {
664661 cluster.init();
@@ -688,12 +685,12 @@
688685 Connection extra1 = pool.connections.get(1);
689686
690687 // Drop a connection and disable listening.
691- currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
688+ currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
692689 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
693690 currentClient.disableListener();
694691
695692 // Since core0 was closed, all of it's requests should have errored.
696- for(MockRequest request : core0requests) {
693+ for (MockRequest request : core0requests) {
697694 verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt());
698695 }
699696
@@ -753,15 +750,15 @@
753750 * @test_category connection:connection_pool
754751 * @since 2.0.11
755752 */
756- @Test(groups="short")
753+ @Test(groups = "short")
757754 public void should_not_mark_host_down_if_some_connections_fail_on_init() throws Exception {
758755 int readTimeout = 1000;
759756 int reconnectInterval = 1000;
760757 Cluster cluster = this.createClusterBuilder()
761- .withSocketOptions(new SocketOptions()
762- .setConnectTimeoutMillis(readTimeout)
763- .setReadTimeoutMillis(reconnectInterval))
764- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
758+ .withSocketOptions(new SocketOptions()
759+ .setConnectTimeoutMillis(readTimeout)
760+ .setReadTimeoutMillis(reconnectInterval))
761+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
765762 List<MockRequest> requests = newArrayList();
766763 try {
767764 cluster.init();
@@ -819,10 +816,10 @@
819816 int readTimeout = 1000;
820817 int reconnectInterval = 1000;
821818 Cluster cluster = this.createClusterBuilder()
822- .withSocketOptions(new SocketOptions()
823- .setConnectTimeoutMillis(readTimeout)
824- .setReadTimeoutMillis(reconnectInterval))
825- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
819+ .withSocketOptions(new SocketOptions()
820+ .setConnectTimeoutMillis(readTimeout)
821+ .setReadTimeoutMillis(reconnectInterval))
822+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
826823 try {
827824 // Init cluster so control connection is created.
828825 cluster.init();
@@ -860,15 +857,15 @@
860857 * @test_category connection:connection_pool
861858 * @since 2.0.11
862859 */
863- @Test(groups="short")
860+ @Test(groups = "short")
864861 public void should_wait_on_connection_if_not_convicted_and_no_connections_available() throws Exception {
865862 int readTimeout = 1000;
866863 int reconnectInterval = 1000;
867864 Cluster cluster = this.createClusterBuilder()
868- .withSocketOptions(new SocketOptions()
869- .setConnectTimeoutMillis(readTimeout)
870- .setReadTimeoutMillis(reconnectInterval))
871- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
865+ .withSocketOptions(new SocketOptions()
866+ .setConnectTimeoutMillis(readTimeout)
867+ .setReadTimeoutMillis(reconnectInterval))
868+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
872869 try {
873870 // Init cluster so control connection is created.
874871 cluster.init();
@@ -915,15 +912,15 @@
915912 * @test_category connection:connection_pool
916913 * @since 2.0.11
917914 */
918- @Test(groups="short")
915+ @Test(groups = "short")
919916 public void should_wait_on_connection_if_zero_core_connections() throws Exception {
920917 int readTimeout = 1000;
921918 int reconnectInterval = 1000;
922919 Cluster cluster = this.createClusterBuilder()
923- .withSocketOptions(new SocketOptions()
924- .setConnectTimeoutMillis(readTimeout)
925- .setReadTimeoutMillis(reconnectInterval))
926- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
920+ .withSocketOptions(new SocketOptions()
921+ .setConnectTimeoutMillis(readTimeout)
922+ .setReadTimeoutMillis(reconnectInterval))
923+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
927924 try {
928925 // Init cluster so control connection is created.
929926 cluster.init();
@@ -951,26 +948,26 @@
951948
952949 private HostConnectionPool createPool(Cluster cluster, int coreConnections, int maxConnections) {
953950 cluster.getConfiguration().getPoolingOptions()
954- .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
955- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
951+ .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
952+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
956953 Session session = cluster.connect();
957954 Host host = TestUtils.findHost(cluster, 1);
958955
959956 // Replace the existing pool with a spy pool and return it.
960- SessionManager sm = ((SessionManager)session);
957+ SessionManager sm = ((SessionManager) session);
961958 return sm.pools.get(host);
962959 }
963960
964961 /**
965- * <p>
962+ * <p/>
966963 * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
967964 * insertions are being executed, the number of opened connection is monitored.
968965 * <p/>
969966 * If at anytime, the number of opened connections is negative, this test will fail.
970967 *
971- * @since 2.0.6, 2.1.1
972968 * @jira_ticket JAVA-349
973969 * @test_category connection:connection_pool
970+ * @since 2.0.6, 2.1.1
974971 */
975972 @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */)
976973 public void open_connections_metric_should_always_be_positive() throws InterruptedException {
@@ -1030,17 +1027,19 @@
10301027 sb.append(");");
10311028
10321029 PrimingRequest preparedStatementPrime = PrimingRequest.preparedStatementBuilder()
1033- .withQuery(sb.toString())
1034- .withThen(then().withVariableTypes(PrimitiveType.INT))
1035- .build();
1030+ .withQuery(sb.toString())
1031+ .withThen(then().withVariableTypes(PrimitiveType.INT))
1032+ .build();
10361033 primingClient.prime(preparedStatementPrime);
10371034 return sb.toString();
10381035 }
10391036
1040- /** Mock ResponseCallback that simulates the behavior of SpeculativeExecution (in terms of borrowing/releasing connections). */
1037+ /**
1038+ * Mock ResponseCallback that simulates the behavior of SpeculativeExecution (in terms of borrowing/releasing connections).
1039+ */
10411040 static class MockRequest implements Connection.ResponseCallback {
10421041
1043- enum State { START, COMPLETED, FAILED, TIMED_OUT }
1042+ enum State {START, COMPLETED, FAILED, TIMED_OUT}
10441043
10451044 final Connection connection;
10461045 private Connection.ResponseHandler responseHandler;
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataAssert.java +3 −4
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.IndexMetadata.Kind;
1819 import org.assertj.core.api.AbstractAssert;
1920
2021 import static org.assertj.core.api.Assertions.assertThat;
2122
22-import com.datastax.driver.core.IndexMetadata.Kind;
23-
2423 public class IndexMetadataAssert extends AbstractAssert<IndexMetadataAssert, IndexMetadata> {
2524
2625 public IndexMetadataAssert(IndexMetadata actual) {
@@ -41,7 +40,7 @@
4140 assertThat(actual.getOption(name)).isEqualTo(value);
4241 return this;
4342 }
44-
43+
4544 public IndexMetadataAssert asCqlQuery(String cqlQuery) {
4645 assertThat(actual.asCQLQuery()).isEqualTo(cqlQuery);
4746 return this;
@@ -51,7 +50,7 @@
5150 assertThat(actual.isCustomIndex()).isTrue();
5251 return this;
5352 }
54-
53+
5554 public IndexMetadataAssert isNotCustomIndex() {
5655 assertThat(actual.isCustomIndex()).isFalse();
5756 return this;
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +146 −149
@@ -15,26 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Collection;
20-import java.util.List;
21-import java.util.Map;
22-
18+import com.datastax.driver.core.ColumnMetadata.*;
19+import com.datastax.driver.core.Token.M3PToken;
20+import com.datastax.driver.core.utils.CassandraVersion;
2321 import com.google.common.collect.ImmutableList;
2422 import com.google.common.collect.ImmutableMap;
2523 import com.google.common.primitives.Ints;
2624 import org.testng.annotations.BeforeClass;
2725 import org.testng.annotations.Test;
2826
29-import com.datastax.driver.core.ColumnMetadata.*;
30-import com.datastax.driver.core.Token.M3PToken;
31-import com.datastax.driver.core.utils.CassandraVersion;
27+import java.nio.ByteBuffer;
28+import java.util.Collection;
29+import java.util.List;
30+import java.util.Map;
3231
3332 import static com.datastax.driver.core.Assertions.assertThat;
3433 import static com.datastax.driver.core.ColumnMetadata.*;
35-import static com.datastax.driver.core.DataType.cint;
36-import static com.datastax.driver.core.DataType.map;
37-import static com.datastax.driver.core.DataType.text;
34+import static com.datastax.driver.core.DataType.*;
3835 import static com.datastax.driver.core.IndexMetadata.Kind.*;
3936
4037 @CassandraVersion(major = 1.2)
@@ -44,30 +41,30 @@
4441 * Column definitions for schema_columns table (legacy pre-3.0 layout).
4542 */
4643 private static final ColumnDefinitions legacyColumnDefs = new ColumnDefinitions(new ColumnDefinitions.Definition[]{
47- definition(COLUMN_NAME, text()),
48- definition(COMPONENT_INDEX, cint()),
49- definition(KIND_V2, text()),
50- definition(INDEX_NAME, text()),
51- definition(INDEX_TYPE, text()),
52- definition(VALIDATOR, text()),
53- definition(INDEX_OPTIONS, text())
44+ definition(COLUMN_NAME, text()),
45+ definition(COMPONENT_INDEX, cint()),
46+ definition(KIND_V2, text()),
47+ definition(INDEX_NAME, text()),
48+ definition(INDEX_TYPE, text()),
49+ definition(VALIDATOR, text()),
50+ definition(INDEX_OPTIONS, text())
5451 }, CodecRegistry.DEFAULT_INSTANCE);
5552
5653 /**
5754 * Column definitions for indexes table (post-3.0 layout).
5855 */
5956 private static final ColumnDefinitions indexColumnDefs = new ColumnDefinitions(new ColumnDefinitions.Definition[]{
60- definition(IndexMetadata.NAME, text()),
61- definition(IndexMetadata.KIND, text()),
62- definition(IndexMetadata.OPTIONS, map(text(), text()))
57+ definition(IndexMetadata.NAME, text()),
58+ definition(IndexMetadata.KIND, text()),
59+ definition(IndexMetadata.OPTIONS, map(text(), text()))
6360 }, CodecRegistry.DEFAULT_INSTANCE);
64-
61+
6562 private static final TypeCodec<Map<String, String>> MAP_CODEC = TypeCodec.map(TypeCodec.varchar(), TypeCodec.varchar());
66-
63+
6764 private ProtocolVersion protocolVersion;
6865
6966 @Override
70- @BeforeClass(groups = { "short", "long" })
67+ @BeforeClass(groups = {"short", "long"})
7168 public void beforeClass() {
7269 super.beforeClass();
7370 protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
@@ -77,24 +74,24 @@
7774 protected Collection<String> getTableDefinitions() {
7875 ImmutableList.Builder<String> builder = ImmutableList.builder();
7976 builder.add("CREATE TABLE indexing ("
80- + "id int,"
81- + "id2 int,"
82- + "map_values map<text, int>,"
83- + "map_keys map<text, int>,"
84- + "map_entries map<text, int>,"
85- + "map_all map<text, int>,"
86- + "text_column text, "
87- + "\"MixedCaseColumn\" list<text>,"
88- +
89- // Frozen collections was introduced only in C* 2.1.3
90- (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0
91- ?
92- ", map_full frozen<map<text, int>>,"
93- + "set_full frozen<set<text>>,"
94- + "list_full frozen<list<text>>,"
95- :
96- "")
97- + "PRIMARY KEY (id, id2));"
77+ + "id int,"
78+ + "id2 int,"
79+ + "map_values map<text, int>,"
80+ + "map_keys map<text, int>,"
81+ + "map_entries map<text, int>,"
82+ + "map_all map<text, int>,"
83+ + "text_column text, "
84+ + "\"MixedCaseColumn\" list<text>,"
85+ +
86+ // Frozen collections was introduced only in C* 2.1.3
87+ (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0
88+ ?
89+ ", map_full frozen<map<text, int>>,"
90+ + "set_full frozen<set<text>>,"
91+ + "list_full frozen<list<text>>,"
92+ :
93+ "")
94+ + "PRIMARY KEY (id, id2));"
9895 );
9996
10097 return builder.build();
@@ -107,12 +104,12 @@
107104 ColumnMetadata column = getColumn("text_column");
108105 IndexMetadata index = getIndex("text_column_index");
109106 assertThat(index)
110- .hasName("text_column_index")
111- .hasParent((TableMetadata)column.getParent())
112- .isNotCustomIndex()
113- .hasTarget("text_column")
114- .hasKind(COMPOSITES)
115- .asCqlQuery(createValuesIndex);
107+ .hasName("text_column_index")
108+ .hasParent((TableMetadata) column.getParent())
109+ .isNotCustomIndex()
110+ .hasTarget("text_column")
111+ .hasKind(COMPOSITES)
112+ .asCqlQuery(createValuesIndex);
116113 assertThat((TableMetadata) column.getParent()).hasIndex(index);
117114 }
118115
@@ -121,18 +118,18 @@
121118 public void should_create_metadata_for_values_index_on_mixed_case_column() {
122119 // 3.0 assumes the 'values' keyword if index on a collection
123120 String createValuesIndex = cassandraVersion.getMajor() > 2 ?
124- String.format("CREATE INDEX \"MixedCaseIndex\" ON %s.indexing (values(\"MixedCaseColumn\"));", keyspace) :
125- String.format("CREATE INDEX \"MixedCaseIndex\" ON %s.indexing (\"MixedCaseColumn\");", keyspace);
121+ String.format("CREATE INDEX \"MixedCaseIndex\" ON %s.indexing (values(\"MixedCaseColumn\"));", keyspace) :
122+ String.format("CREATE INDEX \"MixedCaseIndex\" ON %s.indexing (\"MixedCaseColumn\");", keyspace);
126123 session.execute(createValuesIndex);
127124 ColumnMetadata column = getColumn("\"MixedCaseColumn\"");
128125 IndexMetadata index = getIndex("\"MixedCaseIndex\"");
129126 assertThat(index)
130- .hasName("MixedCaseIndex")
131- .hasParent((TableMetadata)column.getParent())
132- .isNotCustomIndex()
133- .hasTarget(cassandraVersion.getMajor() > 2 ? "values(\"MixedCaseColumn\")" : "\"MixedCaseColumn\"")
134- .hasKind(COMPOSITES)
135- .asCqlQuery(createValuesIndex);
127+ .hasName("MixedCaseIndex")
128+ .hasParent((TableMetadata) column.getParent())
129+ .isNotCustomIndex()
130+ .hasTarget(cassandraVersion.getMajor() > 2 ? "values(\"MixedCaseColumn\")" : "\"MixedCaseColumn\"")
131+ .hasKind(COMPOSITES)
132+ .asCqlQuery(createValuesIndex);
136133 assertThat((TableMetadata) column.getParent()).hasIndex(index);
137134 }
138135
@@ -141,18 +138,18 @@
141138 public void should_create_metadata_for_index_on_map_values() {
142139 // 3.0 assumes the 'values' keyword if index on a collection
143140 String createValuesIndex = cassandraVersion.getMajor() > 2 ?
144- String.format("CREATE INDEX map_values_index ON %s.indexing (values(map_values));", keyspace) :
145- String.format("CREATE INDEX map_values_index ON %s.indexing (map_values);", keyspace);
141+ String.format("CREATE INDEX map_values_index ON %s.indexing (values(map_values));", keyspace) :
142+ String.format("CREATE INDEX map_values_index ON %s.indexing (map_values);", keyspace);
146143 session.execute(createValuesIndex);
147144 ColumnMetadata column = getColumn("map_values");
148145 IndexMetadata index = getIndex("map_values_index");
149146 assertThat(index)
150- .hasName("map_values_index")
151- .hasParent((TableMetadata)column.getParent())
152- .isNotCustomIndex()
153- .hasTarget(cassandraVersion.getMajor() > 2 ? "values(map_values)" : "map_values")
154- .hasKind(COMPOSITES)
155- .asCqlQuery(createValuesIndex);
147+ .hasName("map_values_index")
148+ .hasParent((TableMetadata) column.getParent())
149+ .isNotCustomIndex()
150+ .hasTarget(cassandraVersion.getMajor() > 2 ? "values(map_values)" : "map_values")
151+ .hasKind(COMPOSITES)
152+ .asCqlQuery(createValuesIndex);
156153 assertThat((TableMetadata) column.getParent()).hasIndex(index);
157154 }
158155
@@ -164,12 +161,12 @@
164161 ColumnMetadata column = getColumn("map_keys");
165162 IndexMetadata index = getIndex("map_keys_index");
166163 assertThat(index)
167- .hasName("map_keys_index")
168- .hasParent((TableMetadata)column.getParent())
169- .isNotCustomIndex()
170- .hasTarget("keys(map_keys)")
171- .hasKind(COMPOSITES)
172- .asCqlQuery(createKeysIndex);
164+ .hasName("map_keys_index")
165+ .hasParent((TableMetadata) column.getParent())
166+ .isNotCustomIndex()
167+ .hasTarget("keys(map_keys)")
168+ .hasKind(COMPOSITES)
169+ .asCqlQuery(createKeysIndex);
173170 assertThat((TableMetadata) column.getParent()).hasIndex(index);
174171 }
175172
@@ -181,12 +178,12 @@
181178 ColumnMetadata column = getColumn("map_full");
182179 IndexMetadata index = getIndex("map_full_index");
183180 assertThat(index)
184- .hasName("map_full_index")
185- .hasParent((TableMetadata)column.getParent())
186- .isNotCustomIndex()
187- .hasTarget("full(map_full)")
188- .hasKind(COMPOSITES)
189- .asCqlQuery(createFullIndex);
181+ .hasName("map_full_index")
182+ .hasParent((TableMetadata) column.getParent())
183+ .isNotCustomIndex()
184+ .hasTarget("full(map_full)")
185+ .hasKind(COMPOSITES)
186+ .asCqlQuery(createFullIndex);
190187 assertThat((TableMetadata) column.getParent()).hasIndex(index);
191188 }
192189
@@ -198,12 +195,12 @@
198195 ColumnMetadata column = getColumn("set_full");
199196 IndexMetadata index = getIndex("set_full_index");
200197 assertThat(index)
201- .hasName("set_full_index")
202- .hasParent((TableMetadata)column.getParent())
203- .isNotCustomIndex()
204- .hasTarget("full(set_full)")
205- .hasKind(COMPOSITES)
206- .asCqlQuery(createFullIndex);
198+ .hasName("set_full_index")
199+ .hasParent((TableMetadata) column.getParent())
200+ .isNotCustomIndex()
201+ .hasTarget("full(set_full)")
202+ .hasKind(COMPOSITES)
203+ .asCqlQuery(createFullIndex);
207204 assertThat((TableMetadata) column.getParent()).hasIndex(index);
208205 }
209206
@@ -215,12 +212,12 @@
215212 ColumnMetadata column = getColumn("list_full");
216213 IndexMetadata index = getIndex("list_full_index");
217214 assertThat(index)
218- .hasName("list_full_index")
219- .hasParent((TableMetadata)column.getParent())
220- .isNotCustomIndex()
221- .hasTarget("full(list_full)")
222- .hasKind(COMPOSITES)
223- .asCqlQuery(createFullIndex);
215+ .hasName("list_full_index")
216+ .hasParent((TableMetadata) column.getParent())
217+ .isNotCustomIndex()
218+ .hasTarget("full(list_full)")
219+ .hasKind(COMPOSITES)
220+ .asCqlQuery(createFullIndex);
224221 assertThat((TableMetadata) column.getParent()).hasIndex(index);
225222 }
226223
@@ -232,12 +229,12 @@
232229 ColumnMetadata column = getColumn("map_entries");
233230 IndexMetadata index = getIndex("map_entries_index");
234231 assertThat(index)
235- .hasName("map_entries_index")
236- .hasParent((TableMetadata)column.getParent())
237- .isNotCustomIndex()
238- .hasTarget("entries(map_entries)")
239- .hasKind(COMPOSITES)
240- .asCqlQuery(createEntriesIndex);
232+ .hasName("map_entries_index")
233+ .hasParent((TableMetadata) column.getParent())
234+ .isNotCustomIndex()
235+ .hasTarget("entries(map_entries)")
236+ .hasKind(COMPOSITES)
237+ .asCqlQuery(createEntriesIndex);
241238 assertThat((TableMetadata) column.getParent()).hasIndex(index);
242239 }
243240
@@ -252,76 +249,76 @@
252249 session.execute(createValuesIndex);
253250
254251 ColumnMetadata column = getColumn("map_all");
255- TableMetadata table = (TableMetadata)column.getParent();
252+ TableMetadata table = (TableMetadata) column.getParent();
256253
257254 assertThat(getIndex("map_all_entries_index"))
258- .hasParent(table)
259- .asCqlQuery(createEntriesIndex);
255+ .hasParent(table)
256+ .asCqlQuery(createEntriesIndex);
260257
261258 assertThat(getIndex("map_all_keys_index"))
262- .hasParent(table)
263- .asCqlQuery(createKeysIndex);
259+ .hasParent(table)
260+ .asCqlQuery(createKeysIndex);
264261
265262 assertThat(getIndex("map_all_values_index"))
266- .hasParent(table)
267- .asCqlQuery(createValuesIndex);
263+ .hasParent(table)
264+ .asCqlQuery(createValuesIndex);
268265 }
269266
270267 @Test(
271- groups = "short",
272- description = "This test case builds a ColumnMetadata object programmatically to test custom indices with pre-3.0 layout,"
273- + "otherwise, it would require deploying an actual custom index class into the C* test cluster")
268+ groups = "short",
269+ description = "This test case builds a ColumnMetadata object programmatically to test custom indices with pre-3.0 layout,"
270+ + "otherwise, it would require deploying an actual custom index class into the C* test cluster")
274271 public void should_parse_legacy_custom_index_options() {
275272 TableMetadata table = getTable("indexing");
276273 List<ByteBuffer> columnData = ImmutableList.of(
277- wrap("text_column"), // column name
278- wrap(0), // component index
279- wrap("regular"), // column kind
280- wrap("custom_index"), // index name
281- wrap("CUSTOM"), // index type
282- wrap("org.apache.cassandra.db.marshal.UTF8Type"), // validator
283- wrap("{\"foo\" : \"bar\", \"class_name\" : \"dummy.DummyIndex\"}") // index options
274+ wrap("text_column"), // column name
275+ wrap(0), // component index
276+ wrap("regular"), // column kind
277+ wrap("custom_index"), // index name
278+ wrap("CUSTOM"), // index type
279+ wrap("org.apache.cassandra.db.marshal.UTF8Type"), // validator
280+ wrap("{\"foo\" : \"bar\", \"class_name\" : \"dummy.DummyIndex\"}") // index options
284281 );
285282 Row columnRow = ArrayBackedRow.fromData(legacyColumnDefs, M3PToken.FACTORY, protocolVersion, columnData);
286283 Raw columnRaw = Raw.fromRow(columnRow, VersionNumber.parse("2.1"));
287284 ColumnMetadata column = ColumnMetadata.fromRaw(table, columnRaw, DataType.varchar());
288285 IndexMetadata index = IndexMetadata.fromLegacy(column, columnRaw);
289286 assertThat(index)
290- .isNotNull()
291- .hasName("custom_index")
292- .isCustomIndex()
293- .hasOption("foo", "bar")
294- .hasKind(CUSTOM)
295- .asCqlQuery(String.format("CREATE CUSTOM INDEX custom_index ON %s.indexing (text_column) "
296- + "USING 'dummy.DummyIndex' WITH OPTIONS = {'foo' : 'bar'};", keyspace));
287+ .isNotNull()
288+ .hasName("custom_index")
289+ .isCustomIndex()
290+ .hasOption("foo", "bar")
291+ .hasKind(CUSTOM)
292+ .asCqlQuery(String.format("CREATE CUSTOM INDEX custom_index ON %s.indexing (text_column) "
293+ + "USING 'dummy.DummyIndex' WITH OPTIONS = {'foo' : 'bar'};", keyspace));
297294 }
298295
299296 @Test(
300- groups = "short",
301- description = "This test case builds a ColumnMetadata object programmatically to test custom indices with post-3.0 layout,"
302- + "otherwise, it would require deploying an actual custom index class into the C* test cluster")
297+ groups = "short",
298+ description = "This test case builds a ColumnMetadata object programmatically to test custom indices with post-3.0 layout,"
299+ + "otherwise, it would require deploying an actual custom index class into the C* test cluster")
303300 public void should_parse_custom_index_options() {
304301 TableMetadata table = getTable("indexing");
305302 List<ByteBuffer> indexData = ImmutableList.of(
306- wrap("custom_index"), // index name
307- wrap("CUSTOM"), // kind
308- MAP_CODEC.serialize(ImmutableMap.of(
309- "foo", "bar",
310- IndexMetadata.CUSTOM_INDEX_OPTION_NAME, "dummy.DummyIndex",
311- IndexMetadata.TARGET_OPTION_NAME, "a, b, keys(c)"
312- ), protocolVersion) // options
303+ wrap("custom_index"), // index name
304+ wrap("CUSTOM"), // kind
305+ MAP_CODEC.serialize(ImmutableMap.of(
306+ "foo", "bar",
307+ IndexMetadata.CUSTOM_INDEX_OPTION_NAME, "dummy.DummyIndex",
308+ IndexMetadata.TARGET_OPTION_NAME, "a, b, keys(c)"
309+ ), protocolVersion) // options
313310 );
314311 Row indexRow = ArrayBackedRow.fromData(indexColumnDefs, M3PToken.FACTORY, protocolVersion, indexData);
315312 IndexMetadata index = IndexMetadata.fromRow(table, indexRow);
316313 assertThat(index)
317- .isNotNull()
318- .hasName("custom_index")
319- .isCustomIndex()
320- .hasOption("foo", "bar")
321- .hasTarget("a, b, keys(c)")
322- .hasKind(CUSTOM)
323- .asCqlQuery(String.format("CREATE CUSTOM INDEX custom_index ON %s.indexing (a, b, keys(c)) "
324- + "USING 'dummy.DummyIndex' WITH OPTIONS = {'foo' : 'bar'};", keyspace));
314+ .isNotNull()
315+ .hasName("custom_index")
316+ .isCustomIndex()
317+ .hasOption("foo", "bar")
318+ .hasTarget("a, b, keys(c)")
319+ .hasKind(CUSTOM)
320+ .asCqlQuery(String.format("CREATE CUSTOM INDEX custom_index ON %s.indexing (a, b, keys(c)) "
321+ + "USING 'dummy.DummyIndex' WITH OPTIONS = {'foo' : 'bar'};", keyspace));
325322 }
326323
327324 /**
@@ -337,25 +334,25 @@
337334 public void should_parse_with_null_string_index_options() {
338335 TableMetadata table = getTable("indexing");
339336 List<ByteBuffer> data = ImmutableList.of(
340- wrap("b@706172656e745f70617468"), // column name 'parent_path'
341- ByteBuffer.allocate(0), // component index (null)
342- wrap("regular"), // kind
343- wrap("cfs_archive_parent_path"), // index name
344- wrap("KEYS"), // index type
345- wrap("org.apache.cassandra.db.marshal.BytesType"), // validator
346- wrap("null") // index options
337+ wrap("b@706172656e745f70617468"), // column name 'parent_path'
338+ ByteBuffer.allocate(0), // component index (null)
339+ wrap("regular"), // kind
340+ wrap("cfs_archive_parent_path"), // index name
341+ wrap("KEYS"), // index type
342+ wrap("org.apache.cassandra.db.marshal.BytesType"), // validator
343+ wrap("null") // index options
347344 );
348345 Row row = ArrayBackedRow.fromData(legacyColumnDefs, M3PToken.FACTORY, cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), data);
349346 Raw raw = Raw.fromRow(row, VersionNumber.parse("2.1"));
350347 ColumnMetadata column = ColumnMetadata.fromRaw(table, raw, DataType.blob());
351348 IndexMetadata index = IndexMetadata.fromLegacy(column, raw);
352349 assertThat(index)
353- .isNotNull()
354- .hasName("cfs_archive_parent_path")
355- .isNotCustomIndex()
356- .hasTarget("\"b@706172656e745f70617468\"")
357- .hasKind(KEYS)
358- .asCqlQuery(String.format("CREATE INDEX cfs_archive_parent_path ON %s.indexing (\"b@706172656e745f70617468\");", keyspace));
350+ .isNotNull()
351+ .hasName("cfs_archive_parent_path")
352+ .isNotCustomIndex()
353+ .hasTarget("\"b@706172656e745f70617468\"")
354+ .hasKind(KEYS)
355+ .asCqlQuery(String.format("CREATE INDEX cfs_archive_parent_path ON %s.indexing (\"b@706172656e745f70617468\");", keyspace));
359356 assertThat(index.getOption(IndexMetadata.INDEX_KEYS_OPTION_NAME)).isNull(); // While the index type is KEYS, since it lacks index_options it does not get considered.
360357 }
361358
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +32 −20
@@ -15,22 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-
20-import org.testng.annotations.Test;
21-
22-import static org.testng.Assert.assertEquals;
23-import static org.testng.Assert.assertTrue;
24-
2518 import com.datastax.driver.core.querybuilder.Batch;
2619 import com.datastax.driver.core.querybuilder.Insert;
2720 import com.datastax.driver.core.utils.CassandraVersion;
21+import org.testng.annotations.Test;
22+
23+import java.nio.ByteBuffer;
2824
2925 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
30-import static com.datastax.driver.core.querybuilder.QueryBuilder.batch;
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
32-import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
33-import static com.datastax.driver.core.querybuilder.QueryBuilder.select;
26+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
27+import static org.testng.Assert.assertEquals;
28+import static org.testng.Assert.assertTrue;
3429
3530 /**
3631 * Test limitations when using large amounts of data with the driver
@@ -183,10 +178,11 @@
183178
184179 /**
185180 * Test a wide row of size 1,000,000
181+ *
186182 * @throws Throwable
187183 */
188184 @Test(groups = "stress")
189- @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.")
190186 public void wideRows() throws Throwable {
191187 Cluster.Builder builder = Cluster.builder();
192188 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -207,10 +203,11 @@
207203
208204 /**
209205 * Test a batch that writes a row of size 4,000 (just below the error threshold for 2.2).
206+ *
210207 * @throws Throwable
211208 */
212209 @Test(groups = "stress")
213- @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.")
214211 public void wideBatchRows() throws Throwable {
215212 Cluster.Builder builder = Cluster.builder();
216213 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -231,6 +228,7 @@
231228
232229 /**
233230 * Test a wide row of size 1,000,000 consisting of a ByteBuffer
231+ *
234232 * @throws Throwable
235233 */
236234 @Test(groups = "stress")
@@ -254,6 +252,7 @@
254252
255253 /**
256254 * Test a row with a single extra large text value
255+ *
257256 * @throws Throwable
258257 */
259258 @Test(groups = "stress")
@@ -277,6 +276,7 @@
277276
278277 /**
279278 * Creates a table with 330 columns
279+ *
280280 * @throws Throwable
281281 */
282282 @Test(groups = "stress")
@@ -309,6 +309,7 @@
309309
310310 /**
311311 * Tests 10 random tests consisting of the other methods in this class
312+ *
312313 * @throws Throwable
313314 */
314315 @Test(groups = "duration")
@@ -335,13 +336,24 @@
335336
336337 try {
337338 for (int i = 0; i < 10; ++i) {
338- switch ((int) (Math.random() * 5)){
339- case 0: testWideRows(c, 0); break;
340- case 1: testWideBatchRows(c, 0); break;
341- case 2: testByteRows(c, 0); break;
342- case 3: testLargeText(c, 0); break;
343- case 4: testWideTable(c, 0); break;
344- 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;
345357 }
346358 }
347359 } 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 close(){}
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 close() {
73+ }
6574 }
6675
6776 @Test(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/LocalDateTest.java +70 −72
@@ -15,78 +15,76 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.Test;
19+
1820 import java.util.Calendar;
1921 import java.util.concurrent.TimeUnit;
2022
21-import org.testng.annotations.Test;
22-
2323 import static com.datastax.driver.core.Assertions.assertThat;
24-import static com.datastax.driver.core.LocalDate.fromDaysSinceEpoch;
25-import static com.datastax.driver.core.LocalDate.fromMillisSinceEpoch;
26-import static com.datastax.driver.core.LocalDate.fromYearMonthDay;
24+import static com.datastax.driver.core.LocalDate.*;
2725
2826 public class LocalDateTest {
2927
3028 @Test(groups = "unit")
3129 public void should_build_from_days_since_epoch() {
3230 assertThat(fromDaysSinceEpoch(0))
33- .hasMillisSinceEpoch(0)
34- .hasDaysSinceEpoch(0)
35- .hasYearMonthDay(1970, 1, 1)
36- .hasToString("1970-01-01");
31+ .hasMillisSinceEpoch(0)
32+ .hasDaysSinceEpoch(0)
33+ .hasYearMonthDay(1970, 1, 1)
34+ .hasToString("1970-01-01");
3735
3836 assertThat(fromDaysSinceEpoch(10))
39- .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(10))
40- .hasDaysSinceEpoch(10)
41- .hasYearMonthDay(1970, 1, 11)
42- .hasToString("1970-01-11");
37+ .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(10))
38+ .hasDaysSinceEpoch(10)
39+ .hasYearMonthDay(1970, 1, 11)
40+ .hasToString("1970-01-11");
4341
4442 assertThat(fromDaysSinceEpoch(-10))
45- .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(-10))
46- .hasDaysSinceEpoch(-10)
47- .hasYearMonthDay(1969, 12, 22)
48- .hasToString("1969-12-22");
43+ .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(-10))
44+ .hasDaysSinceEpoch(-10)
45+ .hasYearMonthDay(1969, 12, 22)
46+ .hasToString("1969-12-22");
4947
5048 assertThat(fromDaysSinceEpoch(Integer.MAX_VALUE))
51- .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(Integer.MAX_VALUE))
52- .hasDaysSinceEpoch(Integer.MAX_VALUE)
53- .hasYearMonthDay(5881580, 7, 11)
54- .hasToString("5881580-07-11");
49+ .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(Integer.MAX_VALUE))
50+ .hasDaysSinceEpoch(Integer.MAX_VALUE)
51+ .hasYearMonthDay(5881580, 7, 11)
52+ .hasToString("5881580-07-11");
5553
5654 assertThat(fromDaysSinceEpoch(Integer.MIN_VALUE))
57- .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(Integer.MIN_VALUE))
58- .hasDaysSinceEpoch(Integer.MIN_VALUE)
59- .hasYearMonthDay(-5877641, 6, 23)
60- .hasToString("-5877641-06-23");
55+ .hasMillisSinceEpoch(TimeUnit.DAYS.toMillis(Integer.MIN_VALUE))
56+ .hasDaysSinceEpoch(Integer.MIN_VALUE)
57+ .hasYearMonthDay(-5877641, 6, 23)
58+ .hasToString("-5877641-06-23");
6159 }
6260
6361 @Test(groups = "unit")
6462 public void should_build_from_millis_since_epoch() {
6563 assertThat(fromMillisSinceEpoch(0))
66- .hasMillisSinceEpoch(0)
67- .hasDaysSinceEpoch(0)
68- .hasYearMonthDay(1970, 1, 1)
69- .hasToString("1970-01-01");
64+ .hasMillisSinceEpoch(0)
65+ .hasDaysSinceEpoch(0)
66+ .hasYearMonthDay(1970, 1, 1)
67+ .hasToString("1970-01-01");
7068
7169 // Rounding
7270 assertThat(fromMillisSinceEpoch(3600))
73- .hasMillisSinceEpoch(0)
74- .hasDaysSinceEpoch(0)
75- .hasYearMonthDay(1970, 1, 1)
76- .hasToString("1970-01-01");
71+ .hasMillisSinceEpoch(0)
72+ .hasDaysSinceEpoch(0)
73+ .hasYearMonthDay(1970, 1, 1)
74+ .hasToString("1970-01-01");
7775 assertThat(fromMillisSinceEpoch(-3600))
78- .hasMillisSinceEpoch(0)
79- .hasDaysSinceEpoch(0)
80- .hasYearMonthDay(1970, 1, 1)
81- .hasToString("1970-01-01");
76+ .hasMillisSinceEpoch(0)
77+ .hasDaysSinceEpoch(0)
78+ .hasYearMonthDay(1970, 1, 1)
79+ .hasToString("1970-01-01");
8280
8381 // Bound checks
8482 try {
85- fromMillisSinceEpoch(TimeUnit.DAYS.toMillis((long)Integer.MIN_VALUE - 1));
83+ fromMillisSinceEpoch(TimeUnit.DAYS.toMillis((long) Integer.MIN_VALUE - 1));
8684 Assertions.fail("Expected an IllegalArgumentException");
8785 } catch (IllegalArgumentException e) { /*expected*/ }
8886 try {
89- fromMillisSinceEpoch(TimeUnit.DAYS.toMillis((long)Integer.MAX_VALUE + 1));
87+ fromMillisSinceEpoch(TimeUnit.DAYS.toMillis((long) Integer.MAX_VALUE + 1));
9088 Assertions.fail("Expected an IllegalArgumentException");
9189 } catch (IllegalArgumentException e) { /*expected*/ }
9290 }
@@ -94,24 +92,24 @@
9492 @Test(groups = "unit")
9593 public void should_build_from_year_month_day() {
9694 assertThat(fromYearMonthDay(1970, 1, 1))
97- .hasMillisSinceEpoch(0)
98- .hasDaysSinceEpoch(0)
99- .hasYearMonthDay(1970, 1, 1)
100- .hasToString("1970-01-01");
95+ .hasMillisSinceEpoch(0)
96+ .hasDaysSinceEpoch(0)
97+ .hasYearMonthDay(1970, 1, 1)
98+ .hasToString("1970-01-01");
10199
102100 // Handling of 0 / negative years
103101 assertThat(fromYearMonthDay(1, 1, 1))
104- .hasDaysSinceEpoch(-719162)
105- .hasYearMonthDay(1, 1, 1)
106- .hasToString("1-01-01");
102+ .hasDaysSinceEpoch(-719162)
103+ .hasYearMonthDay(1, 1, 1)
104+ .hasToString("1-01-01");
107105 assertThat(fromYearMonthDay(0, 1, 1))
108- .hasDaysSinceEpoch(-719162 - 366)
109- .hasYearMonthDay(0, 1, 1)
110- .hasToString("0-01-01");
106+ .hasDaysSinceEpoch(-719162 - 366)
107+ .hasYearMonthDay(0, 1, 1)
108+ .hasToString("0-01-01");
111109 assertThat(fromYearMonthDay(-1, 1, 1))
112- .hasDaysSinceEpoch(-719162 - 366 - 365)
113- .hasYearMonthDay(-1, 1, 1)
114- .hasToString("-1-01-01");
110+ .hasDaysSinceEpoch(-719162 - 366 - 365)
111+ .hasYearMonthDay(-1, 1, 1)
112+ .hasToString("-1-01-01");
115113
116114 // Month/day out of bounds
117115 try {
@@ -145,52 +143,52 @@
145143 @Test(groups = "unit")
146144 public void should_add_and_subtract_years() {
147145 assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.YEAR, 1))
148- .hasYearMonthDay(1971, 1, 1);
146+ .hasYearMonthDay(1971, 1, 1);
149147 assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.YEAR, -1))
150- .hasYearMonthDay(1969, 1, 1);
148+ .hasYearMonthDay(1969, 1, 1);
151149 assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.YEAR, -1970))
152- .hasYearMonthDay(0, 1, 1);
150+ .hasYearMonthDay(0, 1, 1);
153151 assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.YEAR, -1971))
154- .hasYearMonthDay(-1, 1, 1);
152+ .hasYearMonthDay(-1, 1, 1);
155153 assertThat(fromYearMonthDay(0, 5, 12).add(Calendar.YEAR, 1))
156- .hasYearMonthDay(1, 5, 12);
154+ .hasYearMonthDay(1, 5, 12);
157155 assertThat(fromYearMonthDay(-1, 5, 12).add(Calendar.YEAR, 1))
158- .hasYearMonthDay(0, 5, 12);
156+ .hasYearMonthDay(0, 5, 12);
159157 assertThat(fromYearMonthDay(-1, 5, 12).add(Calendar.YEAR, 2))
160- .hasYearMonthDay(1, 5, 12);
158+ .hasYearMonthDay(1, 5, 12);
161159 }
162160
163161 @Test(groups = "unit")
164162 public void should_add_and_subtract_months() {
165163 assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.MONTH, 2))
166- .hasYearMonthDay(1970, 3, 1);
164+ .hasYearMonthDay(1970, 3, 1);
167165 assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.MONTH, 24))
168- .hasYearMonthDay(1972, 1, 1);
166+ .hasYearMonthDay(1972, 1, 1);
169167 assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.MONTH, -5))
170- .hasYearMonthDay(1969, 8, 1);
168+ .hasYearMonthDay(1969, 8, 1);
171169 assertThat(fromYearMonthDay(1, 1, 1).add(Calendar.MONTH, -1))
172- .hasYearMonthDay(0, 12, 1);
170+ .hasYearMonthDay(0, 12, 1);
173171 assertThat(fromYearMonthDay(0, 1, 1).add(Calendar.MONTH, -1))
174- .hasYearMonthDay(-1, 12, 1);
172+ .hasYearMonthDay(-1, 12, 1);
175173 assertThat(fromYearMonthDay(-1, 12, 1).add(Calendar.MONTH, 1))
176- .hasYearMonthDay(0, 1, 1);
174+ .hasYearMonthDay(0, 1, 1);
177175 assertThat(fromYearMonthDay(0, 12, 1).add(Calendar.MONTH, 1))
178- .hasYearMonthDay(1, 1, 1);
176+ .hasYearMonthDay(1, 1, 1);
179177 }
180178
181179 @Test(groups = "unit")
182180 public void should_add_and_subtract_days() {
183181 assertThat(fromYearMonthDay(1970, 1, 1).add(Calendar.DAY_OF_MONTH, 12))
184- .hasYearMonthDay(1970, 1, 13);
182+ .hasYearMonthDay(1970, 1, 13);
185183 assertThat(fromYearMonthDay(1970, 3, 28).add(Calendar.DAY_OF_MONTH, -40))
186- .hasYearMonthDay(1970, 2, 16);
184+ .hasYearMonthDay(1970, 2, 16);
187185 assertThat(fromYearMonthDay(1, 1, 1).add(Calendar.DAY_OF_MONTH, -2))
188- .hasYearMonthDay(0, 12, 30);
186+ .hasYearMonthDay(0, 12, 30);
189187 assertThat(fromYearMonthDay(0, 1, 1).add(Calendar.DAY_OF_MONTH, -2))
190- .hasYearMonthDay(-1, 12, 30);
188+ .hasYearMonthDay(-1, 12, 30);
191189 assertThat(fromYearMonthDay(-1, 12, 31).add(Calendar.DAY_OF_MONTH, 4))
192- .hasYearMonthDay(0, 1, 4);
190+ .hasYearMonthDay(0, 1, 4);
193191 assertThat(fromYearMonthDay(0, 12, 25).add(Calendar.DAY_OF_MONTH, 14))
194- .hasYearMonthDay(1, 1, 8);
192+ .hasYearMonthDay(1, 1, 8);
195193 }
196194 }
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/MappingCodec.java +2 −5
@@ -15,13 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-
18+import com.datastax.driver.core.exceptions.InvalidTypeException;
2019 import com.google.common.reflect.TypeToken;
2120
22-import com.datastax.driver.core.ProtocolVersion;
23-import com.datastax.driver.core.TypeCodec;
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
21+import java.nio.ByteBuffer;
2522
2623 /**
2724 * This class is a copy of MappingCodec declared in the extras module,
modified driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataTest.java +34 −35
@@ -15,16 +15,15 @@
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.utils.CassandraVersion;
2119 import org.testng.annotations.Test;
2220
23-import com.datastax.driver.core.utils.CassandraVersion;
21+import java.util.Collection;
22+import java.util.Collections;
2423
2524 import static com.datastax.driver.core.Assertions.assertThat;
26-import static com.datastax.driver.core.DataType.*;
2725 import static com.datastax.driver.core.ClusteringOrder.DESC;
26+import static com.datastax.driver.core.DataType.cint;
2827
2928 @CassandraVersion(major = 3)
3029 public class MaterializedViewMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -32,7 +31,7 @@
3231 /**
3332 * Validates that a materialized view is properly retrieved and parsed.
3433 *
35- * @test_category metadata,materialized_view
34+ * @test_category metadata, materialized_view
3635 * @jira_ticket JAVA-825
3736 */
3837 @Test(groups = "short")
@@ -40,23 +39,23 @@
4039
4140 // given
4241 String createTable = String.format(
43- "CREATE TABLE %s.scores("
44- + "user TEXT,"
45- + "game TEXT,"
46- + "year INT,"
47- + "month INT,"
48- + "day INT,"
49- + "score INT,"
50- + "PRIMARY KEY (user, game, year, month, day)"
51- + ")",
52- keyspace);
42+ "CREATE TABLE %s.scores("
43+ + "user TEXT,"
44+ + "game TEXT,"
45+ + "year INT,"
46+ + "month INT,"
47+ + "day INT,"
48+ + "score INT,"
49+ + "PRIMARY KEY (user, game, year, month, day)"
50+ + ")",
51+ keyspace);
5352 String createMV = String.format(
54- "CREATE MATERIALIZED VIEW %s.monthlyhigh AS "
55- + "SELECT game, year, month, score, user, day FROM %s.scores "
56- + "WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL "
57- + "PRIMARY KEY ((game, year, month), score, user, day) "
58- + "WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)",
59- keyspace, keyspace);
53+ "CREATE MATERIALIZED VIEW %s.monthlyhigh AS "
54+ + "SELECT game, year, month, score, user, day FROM %s.scores "
55+ + "WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL "
56+ + "PRIMARY KEY ((game, year, month), score, user, day) "
57+ + "WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)",
58+ keyspace, keyspace);
6059
6160 // when
6261 session.execute(createTable);
@@ -87,26 +86,26 @@
8786 /**
8887 * Validates that a materialized view is properly retrieved and parsed when using quoted identifiers.
8988 *
90- * @test_category metadata,materialized_view
89+ * @test_category metadata, materialized_view
9190 * @jira_ticket JAVA-825
9291 */
9392 @Test(groups = "short")
9493 public void should_create_view_metadata_with_quoted_identifiers() {
9594 // given
9695 String createTable = String.format(
97- "CREATE TABLE %s.\"T1\" ("
98- + "\"theKey\" int, "
99- + "\"the;Clustering\" int, "
100- + "\"the Value\" int, "
101- + "PRIMARY KEY (\"theKey\", \"the;Clustering\"))",
102- keyspace);
96+ "CREATE TABLE %s.\"T1\" ("
97+ + "\"theKey\" int, "
98+ + "\"the;Clustering\" int, "
99+ + "\"the Value\" int, "
100+ + "PRIMARY KEY (\"theKey\", \"the;Clustering\"))",
101+ keyspace);
103102 String createMV = String.format(
104- "CREATE MATERIALIZED VIEW %s.\"Mv1\" AS "
105- + "SELECT \"theKey\", \"the;Clustering\", \"the Value\" "
106- + "FROM %s.\"T1\" "
107- + "WHERE \"theKey\" IS NOT NULL AND \"the;Clustering\" IS NOT NULL AND \"the Value\" IS NOT NULL "
108- + "PRIMARY KEY (\"theKey\", \"the;Clustering\")",
109- keyspace, keyspace);
103+ "CREATE MATERIALIZED VIEW %s.\"Mv1\" AS "
104+ + "SELECT \"theKey\", \"the;Clustering\", \"the Value\" "
105+ + "FROM %s.\"T1\" "
106+ + "WHERE \"theKey\" IS NOT NULL AND \"the;Clustering\" IS NOT NULL AND \"the Value\" IS NOT NULL "
107+ + "PRIMARY KEY (\"theKey\", \"the;Clustering\")",
108+ keyspace, keyspace);
110109 // when
111110 session.execute(createTable);
112111 session.execute(createMV);
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 +24 −24
@@ -15,25 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.lang.management.ManagementFactory;
19-import java.util.Collection;
20-import java.util.Collections;
21-
18+import com.datastax.driver.core.Metrics.Errors;
19+import com.datastax.driver.core.exceptions.DriverException;
20+import com.datastax.driver.core.policies.RetryPolicy;
21+import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
2222 import com.google.common.collect.Lists;
23+import org.testng.annotations.Test;
24+
2325 import javax.management.InstanceNotFoundException;
2426 import javax.management.MBeanInfo;
2527 import javax.management.MBeanServer;
2628 import javax.management.ObjectName;
27-import org.testng.annotations.Test;
28-
29-import static org.testng.Assert.assertEquals;
30-
31-import com.datastax.driver.core.Metrics.Errors;
32-import com.datastax.driver.core.exceptions.DriverException;
33-import com.datastax.driver.core.policies.RetryPolicy;
34-import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
29+import java.lang.management.ManagementFactory;
30+import java.util.Collection;
31+import java.util.Collections;
3532
3633 import static com.datastax.driver.core.Assertions.assertThat;
34+import static org.testng.Assert.assertEquals;
3735
3836 public class MetricsTest extends CCMBridge.PerClassSingleNodeCluster {
3937 private volatile RetryDecision retryDecision;
@@ -64,17 +62,19 @@
6462 }
6563
6664 @Override
67- public void init(Cluster cluster) {}
65+ public void init(Cluster cluster) {
66+ }
6867
6968 @Override
70- public void close() {}
69+ public void close() {
70+ }
7171 });
7272 }
7373
7474 @Override
7575 protected Collection<String> getTableDefinitions() {
7676 return Lists.newArrayList("CREATE TABLE test (k int primary key, v int)",
77- "INSERT INTO test (k, v) VALUES (1, 1)");
77+ "INSERT INTO test (k, v) VALUES (1, 1)");
7878 }
7979
8080 @Test(groups = "short")
@@ -105,7 +105,7 @@
105105 *
106106 * @test_category metrics
107107 */
108- @Test(groups="short")
108+ @Test(groups = "short")
109109 public void should_enable_metrics_and_jmx_by_default() throws Exception {
110110 assertThat(cluster.getMetrics()).isNotNull();
111111 ObjectName clusterMetricsON = ObjectName.getInstance(cluster.getClusterName() + "-metrics:name=connected-to");
@@ -123,12 +123,12 @@
123123 *
124124 * @test_category metrics
125125 */
126- @Test(groups="short", expectedExceptions=InstanceNotFoundException.class)
126+ @Test(groups = "short", expectedExceptions = InstanceNotFoundException.class)
127127 public void metrics_should_be_null_when_metrics_disabled() throws Exception {
128128 Cluster cluster = super.configure(Cluster.builder())
129- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
130- .withoutMetrics()
131- .build();
129+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
130+ .withoutMetrics()
131+ .build();
132132 try {
133133 cluster.init();
134134 assertThat(cluster.getMetrics()).isNull();
@@ -147,12 +147,12 @@
147147 *
148148 * @test_category metrics
149149 */
150- @Test(groups="short", expectedExceptions=InstanceNotFoundException.class)
150+ @Test(groups = "short", expectedExceptions = InstanceNotFoundException.class)
151151 public void should_be_no_jmx_mbean_when_jmx_is_disabled() throws Exception {
152152 Cluster cluster = super.configure(Cluster.builder())
153- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
154- .withoutJMXReporting()
155- .build();
153+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
154+ .withoutJMXReporting()
155+ .build();
156156 try {
157157 cluster.init();
158158 assertThat(cluster.getMetrics()).isNotNull();
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
@@ -67,12 +64,12 @@
6764 }
6865 }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
6966 cluster = Cluster.builder()
70- .addContactPoint(ipOfNode(1))
71- .withPoolingOptions(new PoolingOptions()
72- .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
73- )
74- .withNettyOptions(nettyOptions)
75- .build();
67+ .addContactPoint(ipOfNode(1))
68+ .withPoolingOptions(new PoolingOptions()
69+ .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
70+ )
71+ .withNettyOptions(nettyOptions)
72+ .build();
7673 // when
7774 cluster.connect();// force session creation to populate pools
7875
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +262 −262
@@ -15,11 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
19-import java.util.List;
20-import java.util.Map;
21-import java.util.Set;
22-
2318 import com.google.common.collect.ImmutableList;
2419 import com.google.common.collect.ImmutableMap;
2520 import com.google.common.collect.ImmutableMap.Builder;
@@ -29,6 +24,11 @@
2924 import org.apache.log4j.Logger;
3025 import org.testng.annotations.Test;
3126
27+import java.net.InetSocketAddress;
28+import java.util.List;
29+import java.util.Map;
30+import java.util.Set;
31+
3232 import static org.assertj.core.api.Assertions.assertThat;
3333
3434 public class NetworkTopologyStrategyTest extends AbstractReplicationStrategyTest {
@@ -49,7 +49,7 @@
4949
5050 private static ReplicationStrategy networkTopologyStrategy(ReplicationFactorDefinition... rfs) {
5151 Builder<String, String> builder = ImmutableMap.<String, String>builder()
52- .put("class", "NetworkTopologyStrategy");
52+ .put("class", "NetworkTopologyStrategy");
5353
5454 for (ReplicationFactorDefinition rf : rfs)
5555 builder.put(rf.dc, String.valueOf(rf.replicationFactor));
@@ -124,46 +124,46 @@
124124 }
125125
126126 private static final List<Token> exampleRing = ImmutableList.<Token>builder()
127- .add(TOKEN01)
128- .add(TOKEN02)
129- .add(TOKEN03)
130- .add(TOKEN04)
131- .add(TOKEN05)
132- .add(TOKEN06)
133- .add(TOKEN07)
134- .add(TOKEN08)
135- .add(TOKEN09)
136- .add(TOKEN10)
137- .add(TOKEN11)
138- .add(TOKEN12)
139- .add(TOKEN13)
140- .add(TOKEN14)
141- .add(TOKEN15)
142- .add(TOKEN16)
143- .add(TOKEN17)
144- .add(TOKEN18)
145- .build();
127+ .add(TOKEN01)
128+ .add(TOKEN02)
129+ .add(TOKEN03)
130+ .add(TOKEN04)
131+ .add(TOKEN05)
132+ .add(TOKEN06)
133+ .add(TOKEN07)
134+ .add(TOKEN08)
135+ .add(TOKEN09)
136+ .add(TOKEN10)
137+ .add(TOKEN11)
138+ .add(TOKEN12)
139+ .add(TOKEN13)
140+ .add(TOKEN14)
141+ .add(TOKEN15)
142+ .add(TOKEN16)
143+ .add(TOKEN17)
144+ .add(TOKEN18)
145+ .build();
146146
147147 private static final Map<Token, Host> exampleTokenToPrimary = ImmutableMap.<Token, Host>builder()
148- .put(TOKEN01, host(IP1, DC1, RACK11))
149- .put(TOKEN02, host(IP1, DC1, RACK11))
150- .put(TOKEN03, host(IP5, DC1, RACK12))
151- .put(TOKEN04, host(IP3, DC1, RACK11))
152- .put(TOKEN05, host(IP1, DC1, RACK11))
153- .put(TOKEN06, host(IP5, DC1, RACK12))
154- .put(TOKEN07, host(IP2, DC2, RACK21))
155- .put(TOKEN08, host(IP6, DC2, RACK22))
156- .put(TOKEN09, host(IP3, DC1, RACK11))
157- .put(TOKEN10, host(IP4, DC2, RACK21))
158- .put(TOKEN11, host(IP5, DC1, RACK12))
159- .put(TOKEN12, host(IP4, DC2, RACK21))
160- .put(TOKEN13, host(IP4, DC2, RACK21))
161- .put(TOKEN14, host(IP2, DC2, RACK21))
162- .put(TOKEN15, host(IP6, DC2, RACK22))
163- .put(TOKEN16, host(IP3, DC1, RACK11))
164- .put(TOKEN17, host(IP2, DC2, RACK21))
165- .put(TOKEN18, host(IP6, DC2, RACK22))
166- .build();
148+ .put(TOKEN01, host(IP1, DC1, RACK11))
149+ .put(TOKEN02, host(IP1, DC1, RACK11))
150+ .put(TOKEN03, host(IP5, DC1, RACK12))
151+ .put(TOKEN04, host(IP3, DC1, RACK11))
152+ .put(TOKEN05, host(IP1, DC1, RACK11))
153+ .put(TOKEN06, host(IP5, DC1, RACK12))
154+ .put(TOKEN07, host(IP2, DC2, RACK21))
155+ .put(TOKEN08, host(IP6, DC2, RACK22))
156+ .put(TOKEN09, host(IP3, DC1, RACK11))
157+ .put(TOKEN10, host(IP4, DC2, RACK21))
158+ .put(TOKEN11, host(IP5, DC1, RACK12))
159+ .put(TOKEN12, host(IP4, DC2, RACK21))
160+ .put(TOKEN13, host(IP4, DC2, RACK21))
161+ .put(TOKEN14, host(IP2, DC2, RACK21))
162+ .put(TOKEN15, host(IP6, DC2, RACK22))
163+ .put(TOKEN16, host(IP3, DC1, RACK11))
164+ .put(TOKEN17, host(IP2, DC2, RACK21))
165+ .put(TOKEN18, host(IP6, DC2, RACK22))
166+ .build();
167167
168168 /*
169169 * --------------
@@ -174,18 +174,18 @@
174174 @Test(groups = "unit")
175175 public void networkTopologyWithSimpleDCLayoutTest1() {
176176 List<Token> ring = ImmutableList.<Token>builder()
177- .add(TOKEN01)
178- .add(TOKEN04)
179- .add(TOKEN14)
180- .add(TOKEN19)
181- .build();
177+ .add(TOKEN01)
178+ .add(TOKEN04)
179+ .add(TOKEN14)
180+ .add(TOKEN19)
181+ .build();
182182
183183 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
184- .put(TOKEN01, host(IP1, DC1, RACK11))
185- .put(TOKEN04, host(IP2, DC2, RACK21))
186- .put(TOKEN14, host(IP1, DC1, RACK11))
187- .put(TOKEN19, host(IP2, DC2, RACK21))
188- .build();
184+ .put(TOKEN01, host(IP1, DC1, RACK11))
185+ .put(TOKEN04, host(IP2, DC2, RACK21))
186+ .put(TOKEN14, host(IP1, DC1, RACK11))
187+ .put(TOKEN19, host(IP2, DC2, RACK21))
188+ .build();
189189
190190 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 1), rf(DC2, 1));
191191
@@ -200,26 +200,26 @@
200200 @Test(groups = "unit")
201201 public void networkTopologyWithSimpleDCLayoutTest2() {
202202 List<Token> ring = ImmutableList.<Token>builder()
203- .add(TOKEN01)
204- .add(TOKEN03)
205- .add(TOKEN05)
206- .add(TOKEN07)
207- .add(TOKEN13)
208- .add(TOKEN15)
209- .add(TOKEN17)
210- .add(TOKEN19)
211- .build();
203+ .add(TOKEN01)
204+ .add(TOKEN03)
205+ .add(TOKEN05)
206+ .add(TOKEN07)
207+ .add(TOKEN13)
208+ .add(TOKEN15)
209+ .add(TOKEN17)
210+ .add(TOKEN19)
211+ .build();
212212
213213 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
214- .put(TOKEN01, host(IP1, DC1, RACK11))
215- .put(TOKEN03, host(IP2, DC2, RACK21))
216- .put(TOKEN05, host(IP3, DC1, RACK11))
217- .put(TOKEN07, host(IP4, DC2, RACK21))
218- .put(TOKEN13, host(IP1, DC1, RACK11))
219- .put(TOKEN15, host(IP2, DC2, RACK21))
220- .put(TOKEN17, host(IP3, DC1, RACK11))
221- .put(TOKEN19, host(IP4, DC2, RACK21))
222- .build();
214+ .put(TOKEN01, host(IP1, DC1, RACK11))
215+ .put(TOKEN03, host(IP2, DC2, RACK21))
216+ .put(TOKEN05, host(IP3, DC1, RACK11))
217+ .put(TOKEN07, host(IP4, DC2, RACK21))
218+ .put(TOKEN13, host(IP1, DC1, RACK11))
219+ .put(TOKEN15, host(IP2, DC2, RACK21))
220+ .put(TOKEN17, host(IP3, DC1, RACK11))
221+ .put(TOKEN19, host(IP4, DC2, RACK21))
222+ .build();
223223
224224 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 1), rf(DC2, 1));
225225
@@ -238,22 +238,22 @@
238238 @Test(groups = "unit")
239239 public void networkTopologyWithSimple3DCLayoutTest() {
240240 List<Token> ring = ImmutableList.<Token>builder()
241- .add(TOKEN01)
242- .add(TOKEN05)
243- .add(TOKEN09)
244- .add(TOKEN11)
245- .add(TOKEN15)
246- .add(TOKEN19)
247- .build();
241+ .add(TOKEN01)
242+ .add(TOKEN05)
243+ .add(TOKEN09)
244+ .add(TOKEN11)
245+ .add(TOKEN15)
246+ .add(TOKEN19)
247+ .build();
248248
249249 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
250- .put(TOKEN01, host(IP1, DC1, RACK11))
251- .put(TOKEN05, host(IP2, DC2, RACK21))
252- .put(TOKEN09, host(IP3, DC3, RACK31))
253- .put(TOKEN11, host(IP1, DC1, RACK11))
254- .put(TOKEN15, host(IP2, DC2, RACK21))
255- .put(TOKEN19, host(IP3, DC3, RACK31))
256- .build();
250+ .put(TOKEN01, host(IP1, DC1, RACK11))
251+ .put(TOKEN05, host(IP2, DC2, RACK21))
252+ .put(TOKEN09, host(IP3, DC3, RACK31))
253+ .put(TOKEN11, host(IP1, DC1, RACK11))
254+ .put(TOKEN15, host(IP2, DC2, RACK21))
255+ .put(TOKEN19, host(IP3, DC3, RACK31))
256+ .build();
257257
258258 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 1), rf(DC2, 1), rf(DC3, 1));
259259
@@ -270,30 +270,30 @@
270270 @Test(groups = "unit")
271271 public void networkTopologyWithUnbalancedRingTest() {
272272 List<Token> ring = ImmutableList.<Token>builder()
273- .add(TOKEN01)
274- .add(TOKEN03)
275- .add(TOKEN05)
276- .add(TOKEN07)
277- .add(TOKEN09)
278- .add(TOKEN11)
279- .add(TOKEN13)
280- .add(TOKEN15)
281- .add(TOKEN17)
282- .add(TOKEN19)
283- .build();
273+ .add(TOKEN01)
274+ .add(TOKEN03)
275+ .add(TOKEN05)
276+ .add(TOKEN07)
277+ .add(TOKEN09)
278+ .add(TOKEN11)
279+ .add(TOKEN13)
280+ .add(TOKEN15)
281+ .add(TOKEN17)
282+ .add(TOKEN19)
283+ .build();
284284
285285 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
286- .put(TOKEN01, host(IP1, DC1, RACK11))
287- .put(TOKEN03, host(IP1, DC1, RACK11))
288- .put(TOKEN05, host(IP2, DC2, RACK21))
289- .put(TOKEN07, host(IP3, DC1, RACK11))
290- .put(TOKEN09, host(IP4, DC2, RACK21))
291- .put(TOKEN11, host(IP1, DC1, RACK11))
292- .put(TOKEN13, host(IP1, DC1, RACK11))
293- .put(TOKEN15, host(IP2, DC2, RACK21))
294- .put(TOKEN17, host(IP3, DC1, RACK11))
295- .put(TOKEN19, host(IP4, DC2, RACK21))
296- .build();
286+ .put(TOKEN01, host(IP1, DC1, RACK11))
287+ .put(TOKEN03, host(IP1, DC1, RACK11))
288+ .put(TOKEN05, host(IP2, DC2, RACK21))
289+ .put(TOKEN07, host(IP3, DC1, RACK11))
290+ .put(TOKEN09, host(IP4, DC2, RACK21))
291+ .put(TOKEN11, host(IP1, DC1, RACK11))
292+ .put(TOKEN13, host(IP1, DC1, RACK11))
293+ .put(TOKEN15, host(IP2, DC2, RACK21))
294+ .put(TOKEN17, host(IP3, DC1, RACK11))
295+ .put(TOKEN19, host(IP4, DC2, RACK21))
296+ .build();
297297
298298 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2));
299299
@@ -314,42 +314,42 @@
314314 @Test(groups = "unit")
315315 public void networkTopologyWithDCMultirackLayoutTest() {
316316 List<Token> ring = ImmutableList.<Token>builder()
317- .add(TOKEN01)
318- .add(TOKEN02)
319- .add(TOKEN03)
320- .add(TOKEN04)
321- .add(TOKEN05)
322- .add(TOKEN06)
323- .add(TOKEN07)
324- .add(TOKEN08)
325- .add(TOKEN12)
326- .add(TOKEN13)
327- .add(TOKEN14)
328- .add(TOKEN15)
329- .add(TOKEN16)
330- .add(TOKEN17)
331- .add(TOKEN18)
332- .add(TOKEN19)
333- .build();
317+ .add(TOKEN01)
318+ .add(TOKEN02)
319+ .add(TOKEN03)
320+ .add(TOKEN04)
321+ .add(TOKEN05)
322+ .add(TOKEN06)
323+ .add(TOKEN07)
324+ .add(TOKEN08)
325+ .add(TOKEN12)
326+ .add(TOKEN13)
327+ .add(TOKEN14)
328+ .add(TOKEN15)
329+ .add(TOKEN16)
330+ .add(TOKEN17)
331+ .add(TOKEN18)
332+ .add(TOKEN19)
333+ .build();
334334
335335 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
336- .put(TOKEN01, host(IP1, DC1, RACK11))
337- .put(TOKEN02, host(IP2, DC2, RACK21))
338- .put(TOKEN03, host(IP3, DC1, RACK12))
339- .put(TOKEN04, host(IP4, DC2, RACK22))
340- .put(TOKEN05, host(IP5, DC1, RACK11))
341- .put(TOKEN06, host(IP6, DC2, RACK21))
342- .put(TOKEN07, host(IP7, DC1, RACK12))
343- .put(TOKEN08, host(IP8, DC2, RACK22))
344- .put(TOKEN12, host(IP1, DC1, RACK11))
345- .put(TOKEN13, host(IP2, DC2, RACK21))
346- .put(TOKEN14, host(IP3, DC1, RACK12))
347- .put(TOKEN15, host(IP4, DC2, RACK22))
348- .put(TOKEN16, host(IP5, DC1, RACK11))
349- .put(TOKEN17, host(IP6, DC2, RACK21))
350- .put(TOKEN18, host(IP7, DC1, RACK12))
351- .put(TOKEN19, host(IP8, DC2, RACK22))
352- .build();
336+ .put(TOKEN01, host(IP1, DC1, RACK11))
337+ .put(TOKEN02, host(IP2, DC2, RACK21))
338+ .put(TOKEN03, host(IP3, DC1, RACK12))
339+ .put(TOKEN04, host(IP4, DC2, RACK22))
340+ .put(TOKEN05, host(IP5, DC1, RACK11))
341+ .put(TOKEN06, host(IP6, DC2, RACK21))
342+ .put(TOKEN07, host(IP7, DC1, RACK12))
343+ .put(TOKEN08, host(IP8, DC2, RACK22))
344+ .put(TOKEN12, host(IP1, DC1, RACK11))
345+ .put(TOKEN13, host(IP2, DC2, RACK21))
346+ .put(TOKEN14, host(IP3, DC1, RACK12))
347+ .put(TOKEN15, host(IP4, DC2, RACK22))
348+ .put(TOKEN16, host(IP5, DC1, RACK11))
349+ .put(TOKEN17, host(IP6, DC2, RACK21))
350+ .put(TOKEN18, host(IP7, DC1, RACK12))
351+ .put(TOKEN19, host(IP8, DC2, RACK22))
352+ .build();
353353
354354 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2));
355355
@@ -376,44 +376,44 @@
376376 @Test(groups = "unit")
377377 public void networkTopologyWithMultirackHostSkippingTest1() {
378378 List<Token> ring = ImmutableList.<Token>builder()
379- .add(TOKEN01)
380- .add(TOKEN02)
381- .add(TOKEN03)
382- .add(TOKEN04)
383- .add(TOKEN05)
384- .add(TOKEN06)
385- .add(TOKEN07)
386- .add(TOKEN08)
387- .add(TOKEN12)
388- .add(TOKEN13)
389- .add(TOKEN14)
390- .add(TOKEN15)
391- .add(TOKEN16)
392- .add(TOKEN17)
393- .add(TOKEN18)
394- .add(TOKEN19)
395- .build();
379+ .add(TOKEN01)
380+ .add(TOKEN02)
381+ .add(TOKEN03)
382+ .add(TOKEN04)
383+ .add(TOKEN05)
384+ .add(TOKEN06)
385+ .add(TOKEN07)
386+ .add(TOKEN08)
387+ .add(TOKEN12)
388+ .add(TOKEN13)
389+ .add(TOKEN14)
390+ .add(TOKEN15)
391+ .add(TOKEN16)
392+ .add(TOKEN17)
393+ .add(TOKEN18)
394+ .add(TOKEN19)
395+ .build();
396396
397397 //this is to simulate when we hit the same rack in a DC first as a second replica
398398 //so that'll get skipped and re-added later as a third
399399 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
400- .put(TOKEN01, host(IP1, DC1, RACK11))
401- .put(TOKEN02, host(IP2, DC2, RACK21))
402- .put(TOKEN03, host(IP3, DC1, RACK11))
403- .put(TOKEN04, host(IP4, DC2, RACK21))
404- .put(TOKEN05, host(IP5, DC1, RACK12))
405- .put(TOKEN06, host(IP6, DC2, RACK22))
406- .put(TOKEN07, host(IP7, DC1, RACK12))
407- .put(TOKEN08, host(IP8, DC2, RACK22))
408- .put(TOKEN12, host(IP1, DC1, RACK11))
409- .put(TOKEN13, host(IP2, DC2, RACK21))
410- .put(TOKEN14, host(IP3, DC1, RACK11))
411- .put(TOKEN15, host(IP4, DC2, RACK21))
412- .put(TOKEN16, host(IP5, DC1, RACK12))
413- .put(TOKEN17, host(IP6, DC2, RACK22))
414- .put(TOKEN18, host(IP7, DC1, RACK12))
415- .put(TOKEN19, host(IP8, DC2, RACK22))
416- .build();
400+ .put(TOKEN01, host(IP1, DC1, RACK11))
401+ .put(TOKEN02, host(IP2, DC2, RACK21))
402+ .put(TOKEN03, host(IP3, DC1, RACK11))
403+ .put(TOKEN04, host(IP4, DC2, RACK21))
404+ .put(TOKEN05, host(IP5, DC1, RACK12))
405+ .put(TOKEN06, host(IP6, DC2, RACK22))
406+ .put(TOKEN07, host(IP7, DC1, RACK12))
407+ .put(TOKEN08, host(IP8, DC2, RACK22))
408+ .put(TOKEN12, host(IP1, DC1, RACK11))
409+ .put(TOKEN13, host(IP2, DC2, RACK21))
410+ .put(TOKEN14, host(IP3, DC1, RACK11))
411+ .put(TOKEN15, host(IP4, DC2, RACK21))
412+ .put(TOKEN16, host(IP5, DC1, RACK12))
413+ .put(TOKEN17, host(IP6, DC2, RACK22))
414+ .put(TOKEN18, host(IP7, DC1, RACK12))
415+ .put(TOKEN19, host(IP8, DC2, RACK22))
416+ .build();
417417
418418 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 3), rf(DC2, 3));
419419
@@ -441,42 +441,42 @@
441441 @Test(groups = "unit")
442442 public void networkTopologyWithMultirackHostSkippingTest2() {
443443 List<Token> ring = ImmutableList.<Token>builder()
444- .add(TOKEN01)
445- .add(TOKEN02)
446- .add(TOKEN03)
447- .add(TOKEN04)
448- .add(TOKEN05)
449- .add(TOKEN06)
450- .add(TOKEN07)
451- .add(TOKEN08)
452- .add(TOKEN12)
453- .add(TOKEN13)
454- .add(TOKEN14)
455- .add(TOKEN15)
456- .add(TOKEN16)
457- .add(TOKEN17)
458- .add(TOKEN18)
459- .add(TOKEN19)
460- .build();
444+ .add(TOKEN01)
445+ .add(TOKEN02)
446+ .add(TOKEN03)
447+ .add(TOKEN04)
448+ .add(TOKEN05)
449+ .add(TOKEN06)
450+ .add(TOKEN07)
451+ .add(TOKEN08)
452+ .add(TOKEN12)
453+ .add(TOKEN13)
454+ .add(TOKEN14)
455+ .add(TOKEN15)
456+ .add(TOKEN16)
457+ .add(TOKEN17)
458+ .add(TOKEN18)
459+ .add(TOKEN19)
460+ .build();
461461
462462 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
463- .put(TOKEN01, host(IP1, DC1, RACK11))
464- .put(TOKEN02, host(IP1, DC1, RACK11))
465- .put(TOKEN03, host(IP3, DC1, RACK11))
466- .put(TOKEN04, host(IP3, DC1, RACK11))
467- .put(TOKEN05, host(IP5, DC1, RACK12))
468- .put(TOKEN06, host(IP5, DC1, RACK12))
469- .put(TOKEN07, host(IP7, DC1, RACK12))
470- .put(TOKEN08, host(IP7, DC1, RACK12))
471- .put(TOKEN12, host(IP2, DC2, RACK21))
472- .put(TOKEN13, host(IP2, DC2, RACK21))
473- .put(TOKEN14, host(IP4, DC2, RACK21))
474- .put(TOKEN15, host(IP4, DC2, RACK21))
475- .put(TOKEN16, host(IP6, DC2, RACK22))
476- .put(TOKEN17, host(IP6, DC2, RACK22))
477- .put(TOKEN18, host(IP8, DC2, RACK22))
478- .put(TOKEN19, host(IP8, DC2, RACK22))
479- .build();
463+ .put(TOKEN01, host(IP1, DC1, RACK11))
464+ .put(TOKEN02, host(IP1, DC1, RACK11))
465+ .put(TOKEN03, host(IP3, DC1, RACK11))
466+ .put(TOKEN04, host(IP3, DC1, RACK11))
467+ .put(TOKEN05, host(IP5, DC1, RACK12))
468+ .put(TOKEN06, host(IP5, DC1, RACK12))
469+ .put(TOKEN07, host(IP7, DC1, RACK12))
470+ .put(TOKEN08, host(IP7, DC1, RACK12))
471+ .put(TOKEN12, host(IP2, DC2, RACK21))
472+ .put(TOKEN13, host(IP2, DC2, RACK21))
473+ .put(TOKEN14, host(IP4, DC2, RACK21))
474+ .put(TOKEN15, host(IP4, DC2, RACK21))
475+ .put(TOKEN16, host(IP6, DC2, RACK22))
476+ .put(TOKEN17, host(IP6, DC2, RACK22))
477+ .put(TOKEN18, host(IP8, DC2, RACK22))
478+ .put(TOKEN19, host(IP8, DC2, RACK22))
479+ .build();
480480
481481 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 3), rf(DC2, 3));
482482
@@ -504,42 +504,42 @@
504504 public void networkTopologyWithMultirackHostSkippingTest3() {
505505 //this is the same topology as in the previous test, but with different rfs
506506 List<Token> ring = ImmutableList.<Token>builder()
507- .add(TOKEN01)
508- .add(TOKEN02)
509- .add(TOKEN03)
510- .add(TOKEN04)
511- .add(TOKEN05)
512- .add(TOKEN06)
513- .add(TOKEN07)
514- .add(TOKEN08)
515- .add(TOKEN12)
516- .add(TOKEN13)
517- .add(TOKEN14)
518- .add(TOKEN15)
519- .add(TOKEN16)
520- .add(TOKEN17)
521- .add(TOKEN18)
522- .add(TOKEN19)
523- .build();
507+ .add(TOKEN01)
508+ .add(TOKEN02)
509+ .add(TOKEN03)
510+ .add(TOKEN04)
511+ .add(TOKEN05)
512+ .add(TOKEN06)
513+ .add(TOKEN07)
514+ .add(TOKEN08)
515+ .add(TOKEN12)
516+ .add(TOKEN13)
517+ .add(TOKEN14)
518+ .add(TOKEN15)
519+ .add(TOKEN16)
520+ .add(TOKEN17)
521+ .add(TOKEN18)
522+ .add(TOKEN19)
523+ .build();
524524
525525 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
526- .put(TOKEN01, host(IP1, DC1, RACK11))
527- .put(TOKEN02, host(IP1, DC1, RACK11))
528- .put(TOKEN03, host(IP3, DC1, RACK11))
529- .put(TOKEN04, host(IP3, DC1, RACK11))
530- .put(TOKEN05, host(IP5, DC1, RACK12))
531- .put(TOKEN06, host(IP5, DC1, RACK12))
532- .put(TOKEN07, host(IP7, DC1, RACK12))
533- .put(TOKEN08, host(IP7, DC1, RACK12))
534- .put(TOKEN12, host(IP2, DC2, RACK21))
535- .put(TOKEN13, host(IP2, DC2, RACK21))
536- .put(TOKEN14, host(IP4, DC2, RACK21))
537- .put(TOKEN15, host(IP4, DC2, RACK21))
538- .put(TOKEN16, host(IP6, DC2, RACK22))
539- .put(TOKEN17, host(IP6, DC2, RACK22))
540- .put(TOKEN18, host(IP8, DC2, RACK22))
541- .put(TOKEN19, host(IP8, DC2, RACK22))
542- .build();
526+ .put(TOKEN01, host(IP1, DC1, RACK11))
527+ .put(TOKEN02, host(IP1, DC1, RACK11))
528+ .put(TOKEN03, host(IP3, DC1, RACK11))
529+ .put(TOKEN04, host(IP3, DC1, RACK11))
530+ .put(TOKEN05, host(IP5, DC1, RACK12))
531+ .put(TOKEN06, host(IP5, DC1, RACK12))
532+ .put(TOKEN07, host(IP7, DC1, RACK12))
533+ .put(TOKEN08, host(IP7, DC1, RACK12))
534+ .put(TOKEN12, host(IP2, DC2, RACK21))
535+ .put(TOKEN13, host(IP2, DC2, RACK21))
536+ .put(TOKEN14, host(IP4, DC2, RACK21))
537+ .put(TOKEN15, host(IP4, DC2, RACK21))
538+ .put(TOKEN16, host(IP6, DC2, RACK22))
539+ .put(TOKEN17, host(IP6, DC2, RACK22))
540+ .put(TOKEN18, host(IP8, DC2, RACK22))
541+ .put(TOKEN19, host(IP8, DC2, RACK22))
542+ .build();
543543
544544 //all nodes will contain all data, question is the replica order
545545 ReplicationStrategy strategy = networkTopologyStrategy(rf(DC1, 4), rf(DC2, 4));
@@ -592,24 +592,24 @@
592592 @Test(groups = "unit")
593593 public void networkTopologyStrategyNoNodesInDCTest() {
594594 long t1 = System.currentTimeMillis();
595- Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2))
595+ Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2))
596596 .computeTokenToReplicaMap(keyspace, largeRingTokenToPrimary, largeRing);
597597 assertThat(System.currentTimeMillis() - t1).isLessThan(10000);
598598
599599 InetSocketAddress currNode = null;
600600 InetSocketAddress nextNode;
601601 for (int node = 0; node < 99; node++) { // 100th wraps so doesn't match this, check after
602- if(currNode == null) {
602+ if (currNode == null) {
603603 currNode = socketAddress("127.0.0." + node);
604604 }
605- nextNode = socketAddress("127.0.0." + (node+1));
605+ nextNode = socketAddress("127.0.0." + (node + 1));
606606 for (int vnodes = 0; vnodes < 256; vnodes++) {
607607 Token token = token("" + ((node * 256) + vnodes));
608608 assertReplicaPlacement(replicaMap, token, currNode, nextNode);
609609 }
610610 currNode = nextNode;
611611 }
612- assertReplicaPlacement(replicaMap, token(""+ 99 * 256), currNode, socketAddress("127.0.0.0"));
612+ assertReplicaPlacement(replicaMap, token("" + 99 * 256), currNode, socketAddress("127.0.0.0"));
613613 }
614614
615615
@@ -645,30 +645,30 @@
645645 logger.addAppender(logs);
646646
647647 List<Token> ring = ImmutableList.<Token>builder()
648- .add(TOKEN01)
649- .add(TOKEN02)
650- .add(TOKEN03)
651- .add(TOKEN04)
652- .build();
648+ .add(TOKEN01)
649+ .add(TOKEN02)
650+ .add(TOKEN03)
651+ .add(TOKEN04)
652+ .build();
653653
654654 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
655- .put(TOKEN01, host(IP1, DC1, RACK11))
656- .put(TOKEN02, host(IP2, DC1, RACK12))
657- .put(TOKEN03, host(IP3, DC2, RACK21))
658- .put(TOKEN04, host(IP4, DC2, RACK22))
659- .build();
655+ .put(TOKEN01, host(IP1, DC1, RACK11))
656+ .put(TOKEN02, host(IP2, DC1, RACK12))
657+ .put(TOKEN03, host(IP3, DC2, RACK21))
658+ .put(TOKEN04, host(IP4, DC2, RACK22))
659+ .build();
660660
661661 // Wrong configuration: impossible replication factor for DC2
662662 networkTopologyStrategy(rf(DC1, 2), rf(DC2, 3))
663- .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
663+ .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
664664 assertThat(logs.getNext())
665- .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, DC2));
665+ .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, DC2));
666666
667667 // Wrong configuration: non-existing datacenter
668668 networkTopologyStrategy(rf(DC1, 2), rf("does_not_exist", 2))
669- .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
669+ .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring);
670670 assertThat(logs.getNext())
671- .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, "does_not_exist"));
671+ .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, "does_not_exist"));
672672
673673 logger.setLevel(null);
674674 logger.removeAppender(logs);
modified driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +12 −14
@@ -15,18 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
20-import org.testng.annotations.*;
18+import org.testng.annotations.AfterClass;
19+import org.testng.annotations.AfterMethod;
20+import org.testng.annotations.BeforeClass;
21+import org.testng.annotations.Test;
2122
22-import static com.google.common.collect.Lists.newArrayList;
23-import static org.mockito.Mockito.reset;
24-import static org.mockito.Mockito.spy;
25-import static org.mockito.Mockito.timeout;
26-import static org.mockito.Mockito.times;
27-import static org.mockito.Mockito.verify;
23+import java.util.Collection;
2824
2925 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
26+import static com.google.common.collect.Lists.newArrayList;
27+import static org.mockito.Mockito.*;
3028
3129 public class NodeListRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
3230
@@ -57,9 +55,9 @@
5755 queryOptions.setRefreshSchemaIntervalMillis(0);
5856 // Create a separate cluster that will receive the schema events on its control connection.
5957 cluster2 = this.configure(Cluster.builder())
60- .addContactPointsWithPorts(newArrayList(hostAddress))
61- .withQueryOptions(queryOptions)
62- .build();
58+ .addContactPointsWithPorts(newArrayList(hostAddress))
59+ .withQueryOptions(queryOptions)
60+ .build();
6361 session2 = cluster2.connect();
6462
6563 // Create a spy of the Cluster's control connection and replace it with the spy.
@@ -77,7 +75,7 @@
7775 public void teardown() {
7876 cluster2.close();
7977 // drop all keyspaces
80- for(String keyspace : keyspaces) {
78+ for (String keyspace : keyspaces) {
8179 session.execute("DROP KEYSPACE " + keyspace);
8280 }
8381 }
@@ -112,7 +110,7 @@
112110 // Create keyspaces 5 times to cause
113111 // refreshNodeListAndTokenMap to be called.
114112 String prefix = "srwmprr";
115- for(int i = 0; i < 5; i++) {
113+ for (int i = 0; i < 5; i++) {
116114 String keyspace = prefix + i;
117115 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
118116 keyspaces.add(keyspace);
modified driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +10 −14
@@ -15,20 +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;
29-import static org.mockito.Mockito.verifyNoMoreInteractions;
21+import java.util.Collection;
22+import java.util.concurrent.TimeUnit;
3023
3124 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.*;
3228
3329 public class NodeRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
3430
@@ -41,22 +37,22 @@
4137 * Ensures that when a new node is bootstrapped into the cluster, stopped, and then subsequently
4238 * started within {@link QueryOptions#setRefreshNodeIntervalMillis(int)} that an 'onAdd' event
4339 * event is the only one processed and that the {@link Host} is marked up.
44- * <p>
40+ * <p/>
4541 * Since NEW_NODE_DELAY_SECONDS is typically configured with a high value (60 seconds default
4642 * in the maven profile) this test can take a very long time.
4743 *
4844 * @jira_ticket JAVA-657
4945 * @since 2.0.11
5046 */
51- @Test(groups="long")
47+ @Test(groups = "long")
5248 public void should_call_onAdd_with_bootstrap_stop_start() {
5349 int refreshNodeInterval = 10000;
5450 QueryOptions queryOptions = new QueryOptions().setRefreshNodeIntervalMillis(refreshNodeInterval);
5551 CCMBridge ccm = CCMBridge.builder("test").withNodes(1).build();
5652 Cluster cluster = Cluster.builder()
57- .addContactPoint(CCMBridge.ipOfNode(1))
58- .withQueryOptions(queryOptions)
59- .build();
53+ .addContactPoint(CCMBridge.ipOfNode(1))
54+ .withQueryOptions(queryOptions)
55+ .build();
6056
6157 try {
6258 cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java +17 −18
@@ -15,14 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.Test;
19+
1820 import java.math.BigInteger;
1921 import java.nio.ByteBuffer;
2022 import java.util.List;
2123
22-import org.testng.annotations.Test;
23-
2424 import static org.assertj.core.api.Assertions.assertThat;
25-import static org.testng.Assert.fail;
2625
2726 public class OPPTokenFactoryTest {
2827 private static final Token.Factory factory = Token.OPPToken.FACTORY;
@@ -33,52 +32,52 @@
3332 public void should_split_range() {
3433 List<Token> splits = factory.split(token('a'), token('d'), 3);
3534 assertThat(splits).containsExactly(
36- token('b'),
37- token('c')
35+ token('b'),
36+ token('c')
3837 );
3938 }
4039
4140 @Test(groups = "unit")
4241 public void should_split_range_producing_empty_splits_near_ring_end() {
4342 // the first token following min
44- ByteBuffer buffer = ByteBuffer.wrap(new byte[]{ 0 });
43+ ByteBuffer buffer = ByteBuffer.wrap(new byte[]{0});
4544 Token zero = token(buffer);
4645
4746 // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring)
4847 List<Token> splits = factory.split(minToken, zero, 3);
4948 assertThat(splits).containsExactly(
50- zero,
51- zero
49+ zero,
50+ zero
5251 );
5352 }
5453
5554 @Test(groups = "unit")
5655 public void should_strip_trailing_0_bytes() {
57- Token with0Bytes = token(ByteBuffer.wrap(new byte[]{ 4, 0, 0, 0 }));
58- Token without0Bytes = token(ByteBuffer.wrap(new byte[]{ 4 }));
56+ Token with0Bytes = token(ByteBuffer.wrap(new byte[]{4, 0, 0, 0}));
57+ Token without0Bytes = token(ByteBuffer.wrap(new byte[]{4}));
5958 Token fromStringWith0Bytes = factory.fromString("040000");
6059
6160 assertThat(with0Bytes)
62- .isEqualTo(without0Bytes)
63- .isEqualTo(fromStringWith0Bytes);
61+ .isEqualTo(without0Bytes)
62+ .isEqualTo(fromStringWith0Bytes);
6463
6564 Token withMixed0Bytes = factory.fromString("0004000400");
6665 Token withoutMixed0Bytes = factory.fromString("00040004");
6766
6867 assertThat(withMixed0Bytes)
69- .isEqualTo(withoutMixed0Bytes);
68+ .isEqualTo(withoutMixed0Bytes);
7069 }
7170
7271 @Test(groups = "unit")
7372 public void should_split_range_that_wraps_around_the_ring() {
74- for(int start = 1; start < 128; start++) {
75- for(int end = start; end < start; end++) {
73+ for (int start = 1; start < 128; start++) {
74+ for (int end = start; end < start; end++) {
7675 // Take the midpoint of the ring and offset by the midpoint of start+end.
7776 long expected = 0x81 + ((start + end) / 2);
7877 TokenRange tr = new TokenRange(token(start), token(end), factory);
7978 assertThat(factory.split(tr.getStart(), tr.getEnd(), 2))
80- .as("Expected 0x%X for start: %d, end: %d", expected, start, end)
81- .containsExactly(token(expected));
79+ .as("Expected 0x%X for start: %d, end: %d", expected, start, end)
80+ .containsExactly(token(expected));
8281 }
8382 }
8483 }
@@ -89,7 +88,7 @@
8988 }
9089
9190 private static Token token(char c) {
92- return new Token.OPPToken(ByteBuffer.wrap(new byte[]{ (byte)c }));
91+ return new Token.OPPToken(ByteBuffer.wrap(new byte[]{(byte) c}));
9392 }
9493
9594 private static Token token(long i) {
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java +2 −1
@@ -22,7 +22,8 @@
2222 super("-p ByteOrderedPartitioner", DataType.blob());
2323 }
2424
25- @Override protected Token.Factory tokenFactory() {
25+ @Override
26+ protected Token.Factory tokenFactory() {
2627 return OPPToken.FACTORY;
2728 }
2829 }
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java +2 −1
@@ -20,7 +20,8 @@
2020 super("-p ByteOrderedPartitioner", DataType.blob(), true);
2121 }
2222
23- @Override protected Token.Factory tokenFactory() {
23+ @Override
24+ protected Token.Factory tokenFactory() {
2425 return Token.OPPToken.FACTORY;
2526 }
2627 }
modified driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +18 −19
@@ -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;
19+import com.datastax.driver.core.utils.CassandraVersion;
2220 import org.slf4j.Logger;
2321 import org.slf4j.LoggerFactory;
2422 import org.testng.annotations.BeforeClass;
2523 import org.testng.annotations.Test;
2624
27-import static org.assertj.core.api.Assertions.assertThat;
25+import java.util.Collection;
26+import java.util.Collections;
27+import java.util.Iterator;
2828
29-import com.datastax.driver.core.exceptions.PagingStateException;
30-import com.datastax.driver.core.utils.CassandraVersion;
29+import static org.assertj.core.api.Assertions.assertThat;
3130
32-@CassandraVersion(major=2.0)
31+@CassandraVersion(major = 2.0)
3332 public class PagingStateTest extends CCMBridge.PerClassSingleNodeCluster {
3433 private static final Logger logger = LoggerFactory.getLogger(PagingStateTest.class);
3534 public static final String KEY = "paging_test";
@@ -51,7 +50,7 @@
5150 *
5251 * @test_category paging
5352 * @expected_result {@link ResultSet} from the query with the provided {@link PagingState} starts from the
54- * subsequent row from the first query.
53+ * subsequent row from the first query.
5554 */
5655 @Test(groups = "short")
5756 public void should_complete_when_using_paging_state() {
@@ -68,13 +67,13 @@
6867 }
6968
7069 /**
71- * <p>
70+ * <p/>
7271 * Validates that if the {@link PagingState} is altered in any way that it may not be reused.
7372 * The paging state is altered in the following ways:
74- *
73+ * <p/>
7574 * <ol>
76- * <li>Altering a byte in the paging state raw bytes.</li>
77- * <li>Setting the {@link PagingState} on a different Statement. (should fail hash validation)</li>
75+ * <li>Altering a byte in the paging state raw bytes.</li>
76+ * <li>Setting the {@link PagingState} on a different Statement. (should fail hash validation)</li>
7877 * </ol>
7978 *
8079 * @test_category paging
@@ -93,7 +92,7 @@
9392 String savedPagingStateString = savedPagingState.toString();
9493
9594 // corrupting the paging state
96- savedPagingStateBuffer[6] = (byte)42;
95+ savedPagingStateBuffer[6] = (byte) 42;
9796
9897 try {
9998 st.setFetchSize(20).setPagingState(PagingState.fromBytes(savedPagingStateBuffer));
@@ -123,10 +122,10 @@
123122 *
124123 * @test_category paging
125124 * @expected_result {@link ResultSet} from the query with the provided paging state starts from the subsequent row
126- * from the first query.
125+ * from the first query.
127126 */
128127 @Test(groups = "short")
129- @CassandraVersion(major=2.0)
128+ @CassandraVersion(major = 2.0)
130129 public void should_be_able_to_use_state_with_bound_statement() {
131130 PreparedStatement prepared = session.prepare("SELECT v from test where k=?");
132131 BoundStatement bs = prepared.bind(KEY);
@@ -149,7 +148,7 @@
149148 * @expected_result A failure is thrown when setting paging state on a different {@link BoundStatement}.
150149 */
151150 @Test(groups = "short", expectedExceptions = {PagingStateException.class})
152- @CassandraVersion(major=2.0)
151+ @CassandraVersion(major = 2.0)
153152 public void should_not_be_able_to_use_state_with_different_bound_statement() {
154153 PreparedStatement prepared = session.prepare("SELECT v from test where k=?");
155154 BoundStatement bs0 = prepared.bind(KEY);
@@ -196,7 +195,7 @@
196195 @Test(groups = "unit", expectedExceptions = {PagingStateException.class})
197196 public void should_fail_when_given_invalid_byte_array() {
198197 // Given an expected page state of size 1 and hash of size 1, we should expect 6 bytes, but only receive 5.
199- byte[] complete = { 0x00, 0x01, 0x00, 0x01, 0x00 };
198+ byte[] complete = {0x00, 0x01, 0x00, 0x01, 0x00};
200199 PagingState.fromBytes(complete);
201200 }
202201
@@ -214,7 +213,7 @@
214213 *
215214 * @test_category paging
216215 * @expected_result {@link ResultSet} from the query with the provided raw paging state starts from the
217- * subsequent row from the first query.
216+ * subsequent row from the first query.
218217 */
219218 @Test(groups = "short")
220219 public void should_complete_when_using_unsafe_paging_state() {
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java +7 −10
@@ -15,20 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import org.testng.annotations.Test;
19+
1820 import java.util.Collection;
1921 import java.util.Collections;
2022 import java.util.concurrent.LinkedBlockingQueue;
2123 import java.util.concurrent.ThreadPoolExecutor;
2224 import java.util.concurrent.TimeUnit;
2325
24-import org.testng.annotations.Test;
25-
2626 import static org.assertj.core.api.Assertions.assertThat;
2727 import static org.mockito.Matchers.any;
28-import static org.mockito.Mockito.atLeastOnce;
29-import static org.mockito.Mockito.reset;
30-import static org.mockito.Mockito.spy;
31-import static org.mockito.Mockito.verify;
28+import static org.mockito.Mockito.*;
3229
3330 public class PoolingOptionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
3431 @Override
@@ -50,14 +47,14 @@
5047 @Test(groups = "short")
5148 public void should_be_able_to_use_custom_initialization_executor() {
5249 ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
53- new LinkedBlockingQueue<Runnable>()));
50+ new LinkedBlockingQueue<Runnable>()));
5451
5552 PoolingOptions poolingOptions = new PoolingOptions();
5653 poolingOptions.setInitializationExecutor(executor);
5754
5855 Cluster cluster = Cluster.builder()
59- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
60- .withPoolingOptions(poolingOptions).build();
56+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
57+ .withPoolingOptions(poolingOptions).build();
6158 try {
6259 cluster.init();
6360 // Ensure executor used.
@@ -73,7 +70,7 @@
7370
7471 // Expect core connections + control connection.
7572 assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
76- TestUtils.numberOfLocalCoreConnections(cluster) + 1);
73+ TestUtils.numberOfLocalCoreConnections(cluster) + 1);
7774
7875 reset();
7976
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +2 −3
@@ -17,11 +17,10 @@
1717
1818 import org.testng.annotations.Test;
1919
20-import static org.assertj.core.api.Assertions.assertThat;
21-import static org.assertj.core.api.Assertions.fail;
22-
2320 import static com.datastax.driver.core.HostDistance.LOCAL;
2421 import static com.datastax.driver.core.HostDistance.REMOTE;
22+import static org.assertj.core.api.Assertions.assertThat;
23+import static org.assertj.core.api.Assertions.fail;
2524
2625 public class PoolingOptionsTest {
2726
modified driver-core/src/test/java/com/datastax/driver/core/PreparedIdTest.java +4 −4
@@ -15,19 +15,19 @@
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
23-import static com.datastax.driver.core.Assertions.*;
21+import java.util.Collection;
22+
23+import static com.datastax.driver.core.Assertions.assertThat;
2424
2525 public class PreparedIdTest extends CCMBridge.PerClassSingleNodeCluster {
2626
2727 @Override
2828 protected Collection<String> getTableDefinitions() {
2929 return Lists.newArrayList(
30- "CREATE TABLE foo(k1 int, k2 int, k3 int, v int, PRIMARY KEY ((k1, k2, k3)))"
30+ "CREATE TABLE foo(k1 int, k2 int, k3 int, v int, PRIMARY KEY ((k1, k2, k3)))"
3131 );
3232 }
3333
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +39 −47
@@ -15,30 +15,22 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.util.*;
20-
21-import com.google.common.collect.ImmutableList;
22-import org.testng.annotations.Test;
23-
24-import static org.assertj.core.api.Assertions.assertThat;
25-import static org.testng.Assert.assertEquals;
26-import static org.testng.Assert.assertFalse;
27-import static org.testng.Assert.assertTrue;
28-import static org.testng.Assert.fail;
29-
3018 import com.datastax.driver.core.exceptions.InvalidQueryException;
3119 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
3220 import com.datastax.driver.core.utils.CassandraVersion;
21+import com.google.common.collect.ImmutableList;
22+import org.testng.annotations.Test;
23+
24+import java.net.InetAddress;
25+import java.util.*;
3326
34-import static com.datastax.driver.core.TestUtils.getFixedValue;
35-import static com.datastax.driver.core.TestUtils.getFixedValue2;
36-import static com.datastax.driver.core.TestUtils.getValue;
37-import static com.datastax.driver.core.TestUtils.setValue;
27+import static com.datastax.driver.core.TestUtils.*;
28+import static org.assertj.core.api.Assertions.assertThat;
29+import static org.testng.Assert.*;
3830
3931 /**
4032 * Prepared statement tests.
41- *
33+ * <p/>
4234 * Note: this class also happens to test all the get methods from Row.
4335 */
4436 public class PreparedStatementTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -172,7 +164,7 @@
172164
173165 String name = "c_list_" + rawType;
174166 DataType type = DataType.list(rawType);
175- List<Object> value = (List<Object>)getFixedValue(type);
167+ List<Object> value = (List<Object>) getFixedValue(type);
176168 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
177169 BoundStatement bs = ps.bind();
178170 setValue(bs, name, type, value);
@@ -197,7 +189,7 @@
197189
198190 String name = "c_list_" + rawType;
199191 DataType type = DataType.list(rawType);
200- List<Object> value = (List<Object>)getFixedValue2(type);
192+ List<Object> value = (List<Object>) getFixedValue2(type);
201193 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_list', ?)", ALL_LIST_TABLE, name));
202194 BoundStatement bs = ps.bind();
203195 setValue(bs, name, type, value);
@@ -219,7 +211,7 @@
219211
220212 String name = "c_set_" + rawType;
221213 DataType type = DataType.set(rawType);
222- Set<Object> value = (Set<Object>)getFixedValue(type);
214+ Set<Object> value = (Set<Object>) getFixedValue(type);
223215 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
224216 BoundStatement bs = ps.bind();
225217 setValue(bs, name, type, value);
@@ -244,7 +236,7 @@
244236
245237 String name = "c_set_" + rawType;
246238 DataType type = DataType.set(rawType);
247- Set<Object> value = (Set<Object>)getFixedValue2(type);
239+ Set<Object> value = (Set<Object>) getFixedValue2(type);
248240 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_set', ?)", ALL_SET_TABLE, name));
249241 BoundStatement bs = ps.bind();
250242 setValue(bs, name, type, value);
@@ -271,7 +263,7 @@
271263
272264 String name = "c_map_" + rawKeyType + '_' + rawValueType;
273265 DataType type = DataType.map(rawKeyType, rawValueType);
274- Map<Object, Object> value = (Map<Object, Object>)getFixedValue(type);
266+ Map<Object, Object> value = (Map<Object, Object>) getFixedValue(type);
275267 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
276268 BoundStatement bs = ps.bind();
277269 setValue(bs, name, type, value);
@@ -302,7 +294,7 @@
302294
303295 String name = "c_map_" + rawKeyType + '_' + rawValueType;
304296 DataType type = DataType.map(rawKeyType, rawValueType);
305- Map<Object, Object> value = (Map<Object, Object>)getFixedValue2(type);
297+ Map<Object, Object> value = (Map<Object, Object>) getFixedValue2(type);
306298 PreparedStatement ps = session.prepare(String.format("INSERT INTO %s(k, %s) VALUES ('prepared_map', ?)", ALL_MAP_TABLE, name));
307299 BoundStatement bs = ps.bind();
308300 setValue(bs, name, type, value);
@@ -356,7 +348,7 @@
356348 * Prints the table definitions that will be used in testing
357349 * (for exporting purposes)
358350 */
359- @Test(groups = { "docs" })
351+ @Test(groups = {"docs"})
360352 public void printTableDefinitions() {
361353 for (String definition : getTableDefinitions()) {
362354 System.out.println(definition);
@@ -406,9 +398,9 @@
406398 @Test(groups = "short")
407399 public void should_set_routing_key_on_case_sensitive_keyspace_and_table() {
408400 session.execute("CREATE KEYSPACE \"Test\" WITH replication = { "
409- + " 'class': 'SimpleStrategy',"
410- + " 'replication_factor': '1'"
411- + "}");
401+ + " 'class': 'SimpleStrategy',"
402+ + " 'replication_factor': '1'"
403+ + "}");
412404 session.execute("CREATE TABLE \"Test\".\"Foo\" (i int PRIMARY KEY)");
413405
414406 PreparedStatement ps = session.prepare("INSERT INTO \"Test\".\"Foo\" (i) VALUES (?)");
@@ -419,8 +411,8 @@
419411 @Test(groups = "short", expectedExceptions = InvalidQueryException.class)
420412 public void should_fail_when_prepared_on_another_cluster() throws Exception {
421413 Cluster otherCluster = Cluster.builder()
422- .addContactPointsWithPorts(ImmutableList.of(hostAddress))
423- .build();
414+ .addContactPointsWithPorts(ImmutableList.of(hostAddress))
415+ .build();
424416 try {
425417 PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
426418 BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
@@ -438,16 +430,16 @@
438430 * Note that we have to force protocol version to less than V4 because
439431 * higher protocol versions would allow such unbound values to be sent.
440432 *
441- * @since 2.2.0
442433 * @test_category prepared_statements:binding
443434 * @jira_ticket JAVA-777
435+ * @since 2.2.0
444436 */
445437 @Test(groups = "short")
446438 public void should_not_allow_unbound_value_on_bound_statement_when_protocol_lesser_than_v4() {
447439 Cluster cluster = Cluster.builder()
448- .addContactPointsWithPorts(Collections.singleton(hostAddress))
449- .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V3))
450- .build();
440+ .addContactPointsWithPorts(Collections.singleton(hostAddress))
441+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V3))
442+ .build();
451443 Session session = cluster.connect();
452444 try {
453445 PreparedStatement ps = session.prepare("INSERT INTO " + keyspace + "." + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
@@ -469,17 +461,17 @@
469461 * Note that we have to force protocol version to less than V4 because
470462 * higher protocol versions would allow such unbound values to be sent.
471463 *
472- * @since 2.2.0
473464 * @test_category prepared_statements:binding
474465 * @jira_ticket JAVA-777
466+ * @since 2.2.0
475467 */
476468 @Test(groups = "short")
477469 @CassandraVersion(major = 2.0)
478470 public void should_not_allow_unbound_value_on_batch_statement_when_protocol_lesser_than_v4() {
479471 Cluster cluster = Cluster.builder()
480- .addContactPointsWithPorts(Collections.singleton(hostAddress))
481- .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V3))
482- .build();
472+ .addContactPointsWithPorts(Collections.singleton(hostAddress))
473+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion(ProtocolVersion.V3))
474+ .build();
483475 Session session = cluster.connect();
484476 try {
485477 PreparedStatement ps = session.prepare("INSERT INTO " + keyspace + "." + SIMPLE_TABLE + " (k, i) VALUES (?, ?)");
@@ -501,9 +493,9 @@
501493 * is not bound (UNSET flag).
502494 * This only works from protocol V4 onwards.
503495 *
504- * @since 2.2.0
505496 * @test_category prepared_statements:binding
506497 * @jira_ticket JAVA-777
498+ * @since 2.2.0
507499 */
508500 @Test(groups = "short")
509501 @CassandraVersion(major = 2.2)
@@ -529,9 +521,9 @@
529521 * Tests that a value that was previously set on a bound statement can be unset by index.
530522 * This only works from protocol V4 onwards.
531523 *
532- * @since 2.2.0
533524 * @test_category prepared_statements:binding
534525 * @jira_ticket JAVA-930
526+ * @since 2.2.0
535527 */
536528 @Test(groups = "short")
537529 @CassandraVersion(major = 2.2)
@@ -546,8 +538,8 @@
546538 session.execute(bound);
547539
548540 ResultSet rows = session.execute(
549- new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
550- .enableTracing());
541+ new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
542+ .enableTracing());
551543
552544 assertThat(rows.one().isNull("i"));
553545 QueryTrace queryTrace = rows.getExecutionInfo().getQueryTrace();
@@ -558,9 +550,9 @@
558550 * Tests that a value that was previously set on a bound statement can be unset by name.
559551 * This only works from protocol V4 onwards.
560552 *
561- * @since 2.2.0
562553 * @test_category prepared_statements:binding
563554 * @jira_ticket JAVA-930
555+ * @since 2.2.0
564556 */
565557 @Test(groups = "short")
566558 @CassandraVersion(major = 2.2)
@@ -575,8 +567,8 @@
575567 session.execute(bound);
576568
577569 ResultSet rows = session.execute(
578- new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
579- .enableTracing());
570+ new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'")
571+ .enableTracing());
580572
581573 assertThat(rows.one().isNull("i"));
582574 QueryTrace queryTrace = rows.getExecutionInfo().getQueryTrace();
@@ -588,9 +580,9 @@
588580 * is not bound (UNSET flag).
589581 * This only works from protocol V4 onwards.
590582 *
591- * @since 2.2.0
592583 * @test_category prepared_statements:binding
593584 * @jira_ticket JAVA-777
585+ * @since 2.2.0
594586 */
595587 @Test(groups = "short")
596588 @CassandraVersion(major = 2.2)
@@ -615,9 +607,9 @@
615607 /**
616608 * Tests that a tombstone is created when binding a null value to a column in a prepared statement.
617609 *
618- * @since 2.2.0
619610 * @test_category prepared_statements:binding
620611 * @jira_ticket JAVA-777
612+ * @since 2.2.0
621613 */
622614 @Test(groups = "short")
623615 public void should_create_tombstone_when_null_value_on_bound_statement() {
@@ -637,9 +629,9 @@
637629 /**
638630 * Tests that a tombstone is created when binding a null value to a column in a batch statement.
639631 *
640- * @since 2.2.0
641632 * @test_category prepared_statements:binding
642633 * @jira_ticket JAVA-777
634+ * @since 2.2.0
643635 */
644636 @Test(groups = "short")
645637 @CassandraVersion(major = 2.0)
modified driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java +28 −30
@@ -15,25 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.Bytes;
19+import com.google.common.base.Predicate;
20+import com.google.common.collect.ImmutableMap;
21+import com.google.common.collect.Lists;
22+import com.google.common.collect.Maps;
23+
1824 import java.math.BigDecimal;
1925 import java.math.BigInteger;
2026 import java.net.InetAddress;
2127 import java.net.UnknownHostException;
2228 import java.util.*;
2329
24-import com.google.common.base.Predicate;
25-import com.google.common.collect.ImmutableMap;
26-import com.google.common.collect.Lists;
27-
2830 import static org.assertj.core.api.Assertions.assertThat;
2931
30-import com.datastax.driver.core.utils.Bytes;
31-
32-import com.google.common.collect.Maps;
33-
3432 /**
3533 * This class provides sample values for each primitive data type.
36- *
34+ * <p/>
3735 * These values have no particular meaning, the goal is just to have an instance that can be used in automated tests.
3836 */
3937 public class PrimitiveTypeSamples {
@@ -44,25 +42,25 @@
4442 try {
4543 final Collection<DataType> primitiveTypes = DataType.allPrimitiveTypes(TestUtils.getDesiredProtocolVersion());
4644 ImmutableMap<DataType, Object> data = ImmutableMap.<DataType, Object>builder()
47- .put(DataType.ascii(), "ascii")
48- .put(DataType.bigint(), Long.MAX_VALUE)
49- .put(DataType.blob(), Bytes.fromHexString("0xCAFE"))
50- .put(DataType.cboolean(), Boolean.TRUE)
51- .put(DataType.decimal(), new BigDecimal("12.3E+7"))
52- .put(DataType.cdouble(), Double.MAX_VALUE)
53- .put(DataType.cfloat(), Float.MAX_VALUE)
54- .put(DataType.inet(), InetAddress.getByName("123.123.123.123"))
55- .put(DataType.tinyint(), Byte.MAX_VALUE)
56- .put(DataType.smallint(), Short.MAX_VALUE)
57- .put(DataType.cint(), Integer.MAX_VALUE)
58- .put(DataType.text(), "text")
59- .put(DataType.timestamp(), new Date(872835240000L))
60- .put(DataType.date(), LocalDate.fromDaysSinceEpoch(16071))
61- .put(DataType.time(), 54012123450000L)
62- .put(DataType.timeuuid(), UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"))
63- .put(DataType.uuid(), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"))
64- .put(DataType.varint(), new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"))
65- .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.tinyint(), Byte.MAX_VALUE)
54+ .put(DataType.smallint(), Short.MAX_VALUE)
55+ .put(DataType.cint(), Integer.MAX_VALUE)
56+ .put(DataType.text(), "text")
57+ .put(DataType.timestamp(), new Date(872835240000L))
58+ .put(DataType.date(), LocalDate.fromDaysSinceEpoch(16071))
59+ .put(DataType.time(), 54012123450000L)
60+ .put(DataType.timeuuid(), UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"))
61+ .put(DataType.uuid(), UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"))
62+ .put(DataType.varint(), new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"))
63+ .build();
6664
6765 // Only include data types that support the desired protocol version.
6866 Map<DataType, Object> result = Maps.filterKeys(data, new Predicate<DataType>() {
@@ -76,8 +74,8 @@
7674 List<DataType> tmp = Lists.newArrayList(primitiveTypes);
7775 tmp.removeAll(result.keySet());
7876 assertThat(tmp)
79- .as("new datatype not covered in test")
80- .containsOnly(DataType.counter());
77+ .as("new datatype not covered in test")
78+ .containsOnly(DataType.counter());
8179
8280 return result;
8381 } catch (UnknownHostException e) {
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +52 −54
@@ -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()
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("Timed out waiting for server response");
128+ .contains("Query error")
129+ .contains(ip)
130+ .contains(Integer.toString(scassandra.getBinaryPort()))
131+ .contains(query)
132+ .contains("Timed out waiting for server response");
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,19 +160,19 @@
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);
177- Throwable error = ((NoHostAvailableException)e).getErrors().get(hostAddress);
175+ Throwable error = ((NoHostAvailableException) e).getErrors().get(hostAddress);
178176 assertThat(error).isNotNull().isOfAnyClassIn(loggedException);
179177 } else {
180178 assertThat(e).isInstanceOf(expectedException);
@@ -183,11 +181,11 @@
183181 // then
184182 String line = errorAppender.waitAndGet(5000);
185183 assertThat(line)
186- .contains("Query error")
187- .contains(ip)
188- .contains(Integer.toString(scassandra.getBinaryPort()))
189- .contains(query)
190- .contains(loggedException.getName());
184+ .contains("Query error")
185+ .contains(ip)
186+ .contains(Integer.toString(scassandra.getBinaryPort()))
187+ .contains(query)
188+ .contains(loggedException.getName());
191189 }
192190
193191 }
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +183 −187
@@ -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}.
@@ -54,38 +50,38 @@
5450
5551 private static final List<DataType> dataTypes = new ArrayList<DataType>(
5652 Sets.filter(DataType.allPrimitiveTypes(TestUtils.getDesiredProtocolVersion()), new Predicate<DataType>() {
57- @Override
58- public boolean apply(DataType type) {
59- return type != DataType.counter();
60- }
61- }));
53+ @Override
54+ public boolean apply(DataType type) {
55+ return type != DataType.counter();
56+ }
57+ }));
6258
6359 private static final List<Object> values = Lists.transform(dataTypes, new Function<DataType, Object>() {
64- @Override
65- public Object apply(DataType type) {
66- return getFixedValue(type);
60+ @Override
61+ public Object apply(DataType type) {
62+ return getFixedValue(type);
63+ }
6764 }
68- }
6965 );
7066
7167 private static final String definitions = Joiner.on(", ").join(
72- Lists.transform(dataTypes, new Function<DataType, String>() {
73- @Override
74- public String apply(DataType type) {
75- return "c_" + type + " " + type;
76- }
77- }
78- )
68+ Lists.transform(dataTypes, new Function<DataType, String>() {
69+ @Override
70+ public String apply(DataType type) {
71+ return "c_" + type + " " + type;
72+ }
73+ }
74+ )
7975 );
8076
8177 private static final String assignments = Joiner.on(", ").join(
82- Lists.transform(dataTypes, new Function<DataType, String>() {
83- @Override
84- public String apply(DataType type) {
85- return "c_" + type + " = ?";
86- }
87- }
88- )
78+ Lists.transform(dataTypes, new Function<DataType, String>() {
79+ @Override
80+ public String apply(DataType type) {
81+ return "c_" + type + " = ?";
82+ }
83+ }
84+ )
8985 );
9086
9187 private Logger normal = Logger.getLogger(NORMAL_LOGGER.getName());
@@ -98,14 +94,14 @@
9894
9995 private QueryLogger queryLogger;
10096
101- @BeforeMethod(groups = { "short", "unit" })
97+ @BeforeMethod(groups = {"short", "unit"})
10298 public void startCapturingLogs() {
10399 normal.addAppender(normalAppender = new MemoryAppender());
104100 slow.addAppender(slowAppender = new MemoryAppender());
105101 error.addAppender(errorAppender = new MemoryAppender());
106102 }
107103
108- @AfterMethod(groups = { "short", "unit" })
104+ @AfterMethod(groups = {"short", "unit"})
109105 public void stopCapturingLogs() {
110106 normal.setLevel(null);
111107 slow.setLevel(null);
@@ -115,16 +111,16 @@
115111 error.removeAppender(errorAppender);
116112 }
117113
118- @BeforeMethod(groups = { "short", "unit" })
114+ @BeforeMethod(groups = {"short", "unit"})
119115 public void resetLogLevels() {
120116 normal.setLevel(INFO);
121117 slow.setLevel(INFO);
122118 error.setLevel(INFO);
123119 }
124120
125- @AfterMethod(groups = { "short", "unit" })
121+ @AfterMethod(groups = {"short", "unit"})
126122 public void unregisterQueryLogger() {
127- if(cluster != null && queryLogger != null) {
123+ if (cluster != null && queryLogger != null) {
128124 cluster.unregister(queryLogger);
129125 }
130126 }
@@ -136,18 +132,18 @@
136132 // given
137133 normal.setLevel(DEBUG);
138134 queryLogger = QueryLogger.builder()
139- .withConstantThreshold(Long.MAX_VALUE)
140- .build();
135+ .withConstantThreshold(Long.MAX_VALUE)
136+ .build();
141137 cluster.register(queryLogger);
142138 String query = "SELECT c_text FROM test WHERE pk = 42";
143139 session.execute(query);
144140 // then
145141 String line = normalAppender.waitAndGet(10000);
146142 assertThat(line)
147- .contains("Query completed normally")
148- .contains(ipOfNode(1))
149- .contains(query)
150- .doesNotContain("parameters");
143+ .contains("Query completed normally")
144+ .contains(ipOfNode(1))
145+ .contains(query)
146+ .doesNotContain("parameters");
151147 }
152148
153149 @Test(groups = "short")
@@ -155,8 +151,8 @@
155151 // given
156152 normal.setLevel(DEBUG);
157153 queryLogger = QueryLogger.builder()
158- .withConstantThreshold(Long.MAX_VALUE)
159- .build();
154+ .withConstantThreshold(Long.MAX_VALUE)
155+ .build();
160156 cluster.register(queryLogger);
161157 String query = "SELECT * FROM test where pk = ?";
162158 PreparedStatement ps = session.prepare(query);
@@ -165,21 +161,21 @@
165161 // then
166162 String line = normalAppender.waitAndGet(10000);
167163 assertThat(line)
168- .contains("Query completed normally")
169- .contains(ipOfNode(1))
170- .contains(query)
171- .doesNotContain("actual parameters");
164+ .contains("Query completed normally")
165+ .contains(ipOfNode(1))
166+ .contains(query)
167+ .doesNotContain("actual parameters");
172168 }
173169
174170 @Test(groups = "short")
175- @CassandraVersion(major=2.0)
171+ @CassandraVersion(major = 2.0)
176172 public void should_log_batch_statements() throws Exception {
177173 // given
178174 normal.setLevel(DEBUG);
179175 queryLogger = QueryLogger.builder()
180- .withConstantThreshold(Long.MAX_VALUE)
181- .withMaxQueryStringLength(Integer.MAX_VALUE)
182- .build();
176+ .withConstantThreshold(Long.MAX_VALUE)
177+ .withMaxQueryStringLength(Integer.MAX_VALUE)
178+ .build();
183179 cluster.register(queryLogger);
184180 // when
185181 String query1 = "INSERT INTO test (pk) VALUES (?)";
@@ -193,24 +189,24 @@
193189 // then
194190 String line = normalAppender.waitAndGet(10000);
195191 assertThat(line)
196- .contains("Query completed normally")
197- .contains(ipOfNode(1))
198- .contains("BEGIN BATCH")
199- .contains("APPLY BATCH")
200- .contains(query1)
201- .contains(query2)
202- .doesNotContain("c_int:");
192+ .contains("Query completed normally")
193+ .contains(ipOfNode(1))
194+ .contains("BEGIN BATCH")
195+ .contains("APPLY BATCH")
196+ .contains(query1)
197+ .contains(query2)
198+ .doesNotContain("c_int:");
203199 }
204200
205201 @Test(groups = "short")
206- @CassandraVersion(major=2.0)
202+ @CassandraVersion(major = 2.0)
207203 public void should_log_unlogged_batch_statements() throws Exception {
208204 // given
209205 normal.setLevel(DEBUG);
210206 queryLogger = QueryLogger.builder()
211- .withConstantThreshold(Long.MAX_VALUE)
212- .withMaxQueryStringLength(Integer.MAX_VALUE)
213- .build();
207+ .withConstantThreshold(Long.MAX_VALUE)
208+ .withMaxQueryStringLength(Integer.MAX_VALUE)
209+ .build();
214210 cluster.register(queryLogger);
215211 // when
216212 String query1 = "INSERT INTO test (pk) VALUES (?)";
@@ -224,17 +220,17 @@
224220 // then
225221 String line = normalAppender.waitAndGet(10000);
226222 assertThat(line)
227- .contains("Query completed normally")
228- .contains(ipOfNode(1))
229- .contains("BEGIN UNLOGGED BATCH")
230- .contains("APPLY BATCH")
231- .contains(query1)
232- .contains(query2)
233- .doesNotContain("c_int:");
223+ .contains("Query completed normally")
224+ .contains(ipOfNode(1))
225+ .contains("BEGIN UNLOGGED BATCH")
226+ .contains("APPLY BATCH")
227+ .contains(query1)
228+ .contains(query2)
229+ .doesNotContain("c_int:");
234230 }
235231
236232 @Test(groups = "short")
237- @CassandraVersion(major=2.0)
233+ @CassandraVersion(major = 2.0)
238234 public void should_log_counter_batch_statements() throws Exception {
239235 // Create a special table for testing with counters.
240236 session.execute(
@@ -354,9 +350,9 @@
354350 // given
355351 normal.setLevel(DEBUG);
356352 queryLogger = QueryLogger.builder()
357- .withConstantThreshold(Long.MAX_VALUE)
358- .withMaxQueryStringLength(Integer.MAX_VALUE)
359- .build();
353+ .withConstantThreshold(Long.MAX_VALUE)
354+ .withMaxQueryStringLength(Integer.MAX_VALUE)
355+ .build();
360356 cluster.register(queryLogger);
361357 // when
362358 String query = "SELECT * FROM test where pk = ?";
@@ -366,10 +362,10 @@
366362 // then
367363 String line = normalAppender.waitAndGet(10000);
368364 assertThat(line)
369- .contains("Query completed normally")
370- .contains(ipOfNode(1))
371- .contains(query)
372- .doesNotContain("pk:42");
365+ .contains("Query completed normally")
366+ .contains(ipOfNode(1))
367+ .contains(query)
368+ .doesNotContain("pk:42");
373369 }
374370
375371 // Tests for slow and error queries are in QueryLoggerErrorsTest
@@ -377,14 +373,14 @@
377373 // Tests with query parameters (log level TRACE)
378374
379375 @Test(groups = "short")
380- @CassandraVersion(major=2.0)
376+ @CassandraVersion(major = 2.0)
381377 public void should_log_non_null_named_parameter() throws Exception {
382378 // given
383379 normal.setLevel(TRACE);
384380 queryLogger = QueryLogger.builder()
385- .withConstantThreshold(Long.MAX_VALUE)
386- .withMaxQueryStringLength(Integer.MAX_VALUE)
387- .build();
381+ .withConstantThreshold(Long.MAX_VALUE)
382+ .withMaxQueryStringLength(Integer.MAX_VALUE)
383+ .build();
388384 cluster.register(queryLogger);
389385 // when
390386 String query = "UPDATE test SET c_text = :param1 WHERE pk = :param2";
@@ -396,11 +392,11 @@
396392 // then
397393 String line = normalAppender.waitAndGet(10000);
398394 assertThat(line)
399- .contains("Query completed normally")
400- .contains(ipOfNode(1))
401- .contains(query)
402- .contains("param2:42")
403- .contains("param1:'foo'");
395+ .contains("Query completed normally")
396+ .contains(ipOfNode(1))
397+ .contains(query)
398+ .contains("param2:42")
399+ .contains("param1:'foo'");
404400 }
405401
406402 @Test(groups = "short")
@@ -419,11 +415,11 @@
419415 // then
420416 String line = normalAppender.waitAndGet(10000);
421417 assertThat(line)
422- .contains("Query completed normally")
423- .contains(ipOfNode(1))
424- .contains(query)
425- .contains("pk:42")
426- .contains("c_text:'foo'");
418+ .contains("Query completed normally")
419+ .contains(ipOfNode(1))
420+ .contains(query)
421+ .contains("pk:42")
422+ .contains("c_text:'foo'");
427423 }
428424
429425 @Test(groups = "short")
@@ -442,15 +438,15 @@
442438 // then
443439 String line = normalAppender.waitAndGet(10000);
444440 assertThat(line)
445- .contains("Query completed normally")
446- .contains(ipOfNode(1))
447- .contains(query)
448- .contains("pk:42")
449- .contains("c_text:NULL");
441+ .contains("Query completed normally")
442+ .contains(ipOfNode(1))
443+ .contains(query)
444+ .contains("pk:42")
445+ .contains("c_text:NULL");
450446 }
451447
452448 @Test(groups = "short")
453- @CassandraVersion(major=3.0)
449+ @CassandraVersion(major = 3.0)
454450 public void should_log_unset_parameter() throws Exception {
455451 // given
456452 normal.setLevel(TRACE);
@@ -465,15 +461,15 @@
465461 // then
466462 String line = normalAppender.waitAndGet(10000);
467463 assertThat(line)
468- .contains("Query completed normally")
469- .contains(ipOfNode(1))
470- .contains(query)
471- .contains("pk:42")
472- .contains("c_text:<UNSET>");
464+ .contains("Query completed normally")
465+ .contains(ipOfNode(1))
466+ .contains(query)
467+ .contains("pk:42")
468+ .contains("c_text:<UNSET>");
473469 }
474470
475471 @Test(groups = "short")
476- @CassandraVersion(major=2.0)
472+ @CassandraVersion(major = 2.0)
477473 public void should_log_bound_statement_parameters_inside_batch_statement() throws Exception {
478474 // given
479475 normal.setLevel(TRACE);
@@ -489,14 +485,14 @@
489485 // then
490486 String line = normalAppender.waitAndGet(10000);
491487 assertThat(line)
492- .contains("Query completed normally")
493- .contains(ipOfNode(1))
494- .contains(query1)
495- .contains(query2)
496- .contains("pk:42")
497- .contains("pk:43")
498- .contains("c_text:'foo'")
499- .contains("c_int:12345");
488+ .contains("Query completed normally")
489+ .contains(ipOfNode(1))
490+ .contains(query1)
491+ .contains(query2)
492+ .contains("pk:42")
493+ .contains("pk:43")
494+ .contains("c_text:'foo'")
495+ .contains("c_int:12345");
500496 }
501497 // Test different CQL types
502498
@@ -505,8 +501,8 @@
505501 // given
506502 normal.setLevel(TRACE);
507503 queryLogger = QueryLogger.builder()
508- .withMaxParameterValueLength(Integer.MAX_VALUE)
509- .build();
504+ .withMaxParameterValueLength(Integer.MAX_VALUE)
505+ .build();
510506 cluster.register(queryLogger);
511507 // when
512508 String query = "UPDATE test SET " + assignments + " WHERE pk = 42";
@@ -516,9 +512,9 @@
516512 // then
517513 String line = normalAppender.waitAndGet(10000);
518514 assertThat(line)
519- .contains("Query completed normally")
520- .contains(ipOfNode(1))
521- .contains(query);
515+ .contains("Query completed normally")
516+ .contains(ipOfNode(1))
517+ .contains(query);
522518 CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
523519 for (DataType type : dataTypes) {
524520 TypeCodec<Object> codec = codecRegistry.codecFor(type);
@@ -533,8 +529,8 @@
533529 // given
534530 normal.setLevel(DEBUG);
535531 queryLogger = QueryLogger.builder()
536- .withMaxQueryStringLength(5)
537- .build();
532+ .withMaxQueryStringLength(5)
533+ .build();
538534 cluster.register(queryLogger);
539535 // when
540536 String query = "SELECT * FROM test WHERE pk = 42";
@@ -542,20 +538,20 @@
542538 // then
543539 String line = normalAppender.waitAndGet(10000);
544540 assertThat(line)
545- .contains("Query completed normally")
546- .contains(ipOfNode(1))
547- .contains("SELEC" + TRUNCATED_OUTPUT)
548- .doesNotContain(query);
541+ .contains("Query completed normally")
542+ .contains(ipOfNode(1))
543+ .contains("SELEC" + TRUNCATED_OUTPUT)
544+ .doesNotContain(query);
549545 }
550546
551- @CassandraVersion(major=2.0)
547+ @CassandraVersion(major = 2.0)
552548 @Test(groups = "short")
553549 public void should_show_total_statements_for_batches_even_if_query_truncated() throws Exception {
554550 // given
555551 normal.setLevel(DEBUG);
556552 queryLogger = QueryLogger.builder()
557- .withMaxQueryStringLength(5)
558- .build();
553+ .withMaxQueryStringLength(5)
554+ .build();
559555 cluster.register(queryLogger);
560556 // when
561557 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
@@ -567,12 +563,12 @@
567563 // then
568564 String line = normalAppender.waitAndGet(10000);
569565 assertThat(line)
570- .contains("Query completed normally")
571- .contains(ipOfNode(1))
572- .contains("BEGIN" + TRUNCATED_OUTPUT)
573- .doesNotContain(query1)
574- .doesNotContain(query2)
575- .contains(" [2 statements");
566+ .contains("Query completed normally")
567+ .contains(ipOfNode(1))
568+ .contains("BEGIN" + TRUNCATED_OUTPUT)
569+ .doesNotContain(query1)
570+ .doesNotContain(query2)
571+ .contains(" [2 statements");
576572 }
577573
578574 @Test(groups = "short")
@@ -580,8 +576,8 @@
580576 // given
581577 normal.setLevel(DEBUG);
582578 queryLogger = QueryLogger.builder()
583- .withMaxQueryStringLength(-1)
584- .build();
579+ .withMaxQueryStringLength(-1)
580+ .build();
585581 cluster.register(queryLogger);
586582 // when
587583 String query = "SELECT * FROM test WHERE pk = 42";
@@ -589,20 +585,20 @@
589585 // then
590586 String line = normalAppender.waitAndGet(10000);
591587 assertThat(line)
592- .contains("Query completed normally")
593- .contains(ipOfNode(1))
594- .contains(query)
595- .doesNotContain(TRUNCATED_OUTPUT);
588+ .contains("Query completed normally")
589+ .contains(ipOfNode(1))
590+ .contains(query)
591+ .doesNotContain(TRUNCATED_OUTPUT);
596592 }
597593
598- @CassandraVersion(major=2.0)
594+ @CassandraVersion(major = 2.0)
599595 @Test(groups = "short")
600596 public void should_truncate_parameter_when_max_length_exceeded() throws Exception {
601597 // given
602598 normal.setLevel(TRACE);
603599 queryLogger = QueryLogger.builder()
604- .withMaxParameterValueLength(5)
605- .build();
600+ .withMaxParameterValueLength(5)
601+ .build();
606602 cluster.register(queryLogger);
607603 // when
608604 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
@@ -614,10 +610,10 @@
614610 // then
615611 String line = normalAppender.waitAndGet(10000);
616612 assertThat(line)
617- .contains("Query completed normally")
618- .contains(ipOfNode(1))
619- .contains("c_int:12345" + TRUNCATED_OUTPUT)
620- .doesNotContain("123456");
613+ .contains("Query completed normally")
614+ .contains(ipOfNode(1))
615+ .contains("c_int:12345" + TRUNCATED_OUTPUT)
616+ .doesNotContain("123456");
621617 }
622618
623619 @Test(groups = "short")
@@ -625,23 +621,23 @@
625621 // given
626622 normal.setLevel(TRACE);
627623 queryLogger = QueryLogger.builder()
628- .withMaxParameterValueLength(6)
629- .build();
624+ .withMaxParameterValueLength(6)
625+ .build();
630626 cluster.register(queryLogger);
631627 // when
632628 String query = "UPDATE test SET c_blob = ? WHERE pk = ?";
633629 PreparedStatement ps = session.prepare(query);
634630 BoundStatement bs = ps.bind();
635- bs.setBytes("c_blob", ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1,2,3))));
631+ bs.setBytes("c_blob", ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1, 2, 3))));
636632 bs.setInt("pk", 42);
637633 session.execute(bs);
638634 // then
639635 String line = normalAppender.waitAndGet(10000);
640636 assertThat(line)
641- .contains("Query completed normally")
642- .contains(ipOfNode(1))
643- .contains("c_blob:0x0102" + TRUNCATED_OUTPUT)
644- .doesNotContain("123456");
637+ .contains("Query completed normally")
638+ .contains(ipOfNode(1))
639+ .contains("c_blob:0x0102" + TRUNCATED_OUTPUT)
640+ .doesNotContain("123456");
645641 }
646642
647643 @Test(groups = "short")
@@ -649,8 +645,8 @@
649645 // given
650646 normal.setLevel(TRACE);
651647 queryLogger = QueryLogger.builder()
652- .withMaxParameterValueLength(-1)
653- .build();
648+ .withMaxParameterValueLength(-1)
649+ .build();
654650 cluster.register(queryLogger);
655651 // when
656652 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
@@ -662,10 +658,10 @@
662658 // then
663659 String line = normalAppender.waitAndGet(10000);
664660 assertThat(line)
665- .contains("Query completed normally")
666- .contains(ipOfNode(1))
667- .contains("c_int:123456")
668- .doesNotContain(TRUNCATED_OUTPUT);
661+ .contains("Query completed normally")
662+ .contains(ipOfNode(1))
663+ .contains("c_int:123456")
664+ .doesNotContain(TRUNCATED_OUTPUT);
669665 }
670666
671667 @Test(groups = "short")
@@ -673,8 +669,8 @@
673669 // given
674670 normal.setLevel(TRACE);
675671 queryLogger = QueryLogger.builder()
676- .withMaxLoggedParameters(1)
677- .build();
672+ .withMaxLoggedParameters(1)
673+ .build();
678674 cluster.register(queryLogger);
679675 // when
680676 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
@@ -686,21 +682,21 @@
686682 // then
687683 String line = normalAppender.waitAndGet(10000);
688684 assertThat(line)
689- .contains("Query completed normally")
690- .contains(ipOfNode(1))
691- .contains("c_int:123456")
692- .doesNotContain("pk:42")
693- .contains(FURTHER_PARAMS_OMITTED);
685+ .contains("Query completed normally")
686+ .contains(ipOfNode(1))
687+ .contains("c_int:123456")
688+ .doesNotContain("pk:42")
689+ .contains(FURTHER_PARAMS_OMITTED);
694690 }
695691
696692 @Test(groups = "short")
697- @CassandraVersion(major=2.0)
693+ @CassandraVersion(major = 2.0)
698694 public void should_not_log_exceeding_number_of_parameters_in_batch_statement() throws Exception {
699695 // given
700696 normal.setLevel(TRACE);
701697 queryLogger = QueryLogger.builder()
702- .withMaxLoggedParameters(1)
703- .build();
698+ .withMaxLoggedParameters(1)
699+ .build();
704700 cluster.register(queryLogger);
705701 // when
706702 String query1 = "UPDATE test SET c_text = ? WHERE pk = ?";
@@ -712,15 +708,15 @@
712708 // then
713709 String line = normalAppender.waitAndGet(10000);
714710 assertThat(line)
715- .contains("Query completed normally")
716- .contains(ipOfNode(1))
717- .contains(query1)
718- .contains(query2)
719- .contains("c_text:'foo'")
720- .doesNotContain("pk:42")
721- .doesNotContain("c_int:12345")
722- .doesNotContain("pk:43")
723- .contains(FURTHER_PARAMS_OMITTED);
711+ .contains("Query completed normally")
712+ .contains(ipOfNode(1))
713+ .contains(query1)
714+ .contains(query2)
715+ .contains("c_text:'foo'")
716+ .doesNotContain("pk:42")
717+ .doesNotContain("c_int:12345")
718+ .doesNotContain("pk:43")
719+ .contains(FURTHER_PARAMS_OMITTED);
724720 }
725721
726722 @Test(groups = "short")
@@ -728,8 +724,8 @@
728724 // given
729725 normal.setLevel(TRACE);
730726 queryLogger = QueryLogger.builder()
731- .withMaxLoggedParameters(-1)
732- .build();
727+ .withMaxLoggedParameters(-1)
728+ .build();
733729 cluster.register(queryLogger);
734730 // when
735731 String query = "UPDATE test SET c_int = ? WHERE pk = ?";
@@ -741,10 +737,10 @@
741737 // then
742738 String line = normalAppender.waitAndGet(10000);
743739 assertThat(line)
744- .contains("Query completed normally")
745- .contains(ipOfNode(1))
746- .contains("c_int:123456")
747- .contains("pk:42");
740+ .contains("Query completed normally")
741+ .contains(ipOfNode(1))
742+ .contains("c_int:123456")
743+ .contains("pk:42");
748744 }
749745
750746 @Override
modified driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java +11 −10
@@ -15,13 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.concurrent.TimeUnit;
20-
2118 import com.google.common.collect.Lists;
22-import org.scassandra.Scassandra;
2319 import org.scassandra.http.client.PreparedStatementPreparation;
24-import org.testng.annotations.*;
20+import org.testng.annotations.AfterMethod;
21+import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.Test;
23+
24+import java.util.List;
25+import java.util.concurrent.TimeUnit;
2526
2627 import static com.datastax.driver.core.Assertions.assertThat;
2728 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
@@ -46,11 +47,11 @@
4647 queryOptions = new QueryOptions();
4748 loadBalancingPolicy = new SortingLoadBalancingPolicy();
4849 cluster = Cluster.builder()
49- .addContactPoint(CCMBridge.ipOfNode(2))
50- .withLoadBalancingPolicy(loadBalancingPolicy)
51- .withQueryOptions(queryOptions)
52- .withNettyOptions(nonQuietClusterCloseOptions)
53- .build();
50+ .addContactPoint(CCMBridge.ipOfNode(2))
51+ .withLoadBalancingPolicy(loadBalancingPolicy)
52+ .withQueryOptions(queryOptions)
53+ .withNettyOptions(nonQuietClusterCloseOptions)
54+ .build();
5455
5556 session = cluster.connect();
5657
modified driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java +15 −15
@@ -15,23 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.Cluster.Builder;
19+import com.datastax.driver.core.Metrics.Errors;
20+import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
21+import com.datastax.driver.core.utils.CassandraVersion;
2022 import com.google.common.collect.Lists;
2123 import org.testng.annotations.BeforeMethod;
2224 import org.testng.annotations.Test;
25+
26+import java.util.Collection;
27+
2328 import static org.testng.Assert.assertEquals;
2429 import static org.testng.Assert.assertTrue;
2530
26-import com.datastax.driver.core.Cluster.Builder;
27-import com.datastax.driver.core.Metrics.Errors;
28-import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
29-import com.datastax.driver.core.utils.CassandraVersion;
30-
3131 /**
3232 * Tests the behavior of client-provided timestamps with protocol v3.
3333 */
34-@CassandraVersion(major=2.1)
34+@CassandraVersion(major = 2.1)
3535 public class QueryTimestampTest extends CCMBridge.PerClassSingleNodeCluster {
3636
3737 @Override
@@ -44,13 +44,13 @@
4444 @Override
4545 protected Builder configure(Builder builder) {
4646 return builder
47- .withTimestampGenerator(new TimestampGenerator() {
48- @Override
49- public long next() {
50- return timestampFromGenerator;
51- }
52- })
53- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
47+ .withTimestampGenerator(new TimestampGenerator() {
48+ @Override
49+ public long next() {
50+ return timestampFromGenerator;
51+ }
52+ })
53+ .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
5454 }
5555
5656 @BeforeMethod(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java +11 −11
@@ -15,17 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.util.concurrent.Futures;
19+import com.google.common.util.concurrent.ListenableFuture;
20+import com.google.common.util.concurrent.Uninterruptibles;
21+import org.assertj.core.util.Maps;
22+
1823 import java.net.InetAddress;
1924 import java.util.List;
2025 import java.util.Map;
2126 import java.util.concurrent.ExecutionException;
2227 import java.util.concurrent.TimeUnit;
2328
24-import com.google.common.util.concurrent.Futures;
25-import com.google.common.util.concurrent.ListenableFuture;
26-import com.google.common.util.concurrent.Uninterruptibles;
27-import org.assertj.core.util.Maps;
28-
2929 import static com.google.common.collect.Lists.newArrayList;
3030 import static org.assertj.core.api.Assertions.assertThat;
3131 import static org.testng.Assert.fail;
@@ -49,7 +49,7 @@
4949
5050 public void query(Session session, int times, ConsistencyLevel cl, Class<? extends Exception> expectedException) {
5151 Statement statement = new SimpleStatement(QUERY);
52- if(cl != null) {
52+ if (cl != null) {
5353 statement.setConsistencyLevel(cl);
5454 }
5555
@@ -63,20 +63,20 @@
6363 public void query(Session session, int times, Statement statement, Class<? extends Exception> expectedException) {
6464 List<ListenableFuture<ResultSet>> futures = newArrayList();
6565
66- for(int i = 0; i < times; i++) {
66+ for (int i = 0; i < times; i++) {
6767 futures.add(session.executeAsync(statement));
6868 }
6969
7070 try {
7171 List<ResultSet> results = Uninterruptibles.getUninterruptibly(Futures.allAsList(futures), 1, TimeUnit.MINUTES);
72- for(ResultSet result : results) {
72+ for (ResultSet result : results) {
7373 InetAddress coordinator = result.getExecutionInfo().getQueriedHost().getAddress();
7474 Integer n = coordinators.get(coordinator);
7575 coordinators.put(coordinator, n == null ? 1 : n + 1);
7676 }
7777 } catch (ExecutionException ex) {
7878 Throwable cause = ex.getCause();
79- if(expectedException == null) {
79+ if (expectedException == null) {
8080 fail("Queries failed", ex);
8181 } else {
8282 assertThat(cause).isInstanceOf(expectedException);
@@ -99,8 +99,8 @@
9999 public void assertQueried(ScassandraCluster sCluster, int dc, int node, int n) {
100100 int queryCount = queryCount(sCluster, dc, node);
101101 assertThat(queryCount)
102- .as("Expected node %d:%d to be queried %d times but was %d", dc, node, n, queryCount)
103- .isEqualTo(n);
102+ .as("Expected node %d:%d to be queried %d times but was %d", dc, node, n, queryCount)
103+ .isEqualTo(n);
104104 }
105105
106106 public void reset() {
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java +15 −16
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-
2018 import org.testng.annotations.Test;
2119
20+import java.util.List;
21+
2222 import static org.assertj.core.api.Assertions.assertThat;
23-import static org.testng.Assert.fail;
2423
2524 public class RPTokenFactoryTest {
2625 Token.Factory factory = Token.RPToken.FACTORY;
@@ -29,21 +28,21 @@
2928 public void should_split_range() {
3029 List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("127605887595351923798765477786913079296"), 3);
3130 assertThat(splits).containsExactly(
32- factory.fromString("42535295865117307932921825928971026432"),
33- factory.fromString("85070591730234615865843651857942052864")
31+ factory.fromString("42535295865117307932921825928971026432"),
32+ factory.fromString("85070591730234615865843651857942052864")
3433 );
3534 }
3635
3736 @Test(groups = "unit")
3837 public void should_split_range_that_wraps_around_the_ring() {
3938 List<Token> splits = factory.split(
40- factory.fromString("127605887595351923798765477786913079296"),
41- factory.fromString("85070591730234615865843651857942052864"),
42- 3);
39+ factory.fromString("127605887595351923798765477786913079296"),
40+ factory.fromString("85070591730234615865843651857942052864"),
41+ 3);
4342
4443 assertThat(splits).containsExactly(
45- factory.fromString("0"),
46- factory.fromString("42535295865117307932921825928971026432")
44+ factory.fromString("0"),
45+ factory.fromString("42535295865117307932921825928971026432")
4746 );
4847 }
4948
@@ -55,14 +54,14 @@
5554 // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring)
5655 List<Token> splits = factory.split(maxToken, minToken, 3);
5756 assertThat(splits).containsExactly(
58- maxToken,
59- maxToken
57+ maxToken,
58+ maxToken
6059 );
6160
6261 splits = factory.split(minToken, factory.fromString("0"), 3);
6362 assertThat(splits).containsExactly(
64- factory.fromString("0"),
65- factory.fromString("0")
63+ factory.fromString("0"),
64+ factory.fromString("0")
6665 );
6766 }
6867
@@ -70,8 +69,8 @@
7069 public void should_split_whole_ring() {
7170 List<Token> splits = factory.split(factory.fromString("-1"), factory.fromString("-1"), 3);
7271 assertThat(splits).containsExactly(
73- factory.fromString("56713727820156410577229101238628035242"),
74- factory.fromString("113427455640312821154458202477256070485")
72+ factory.fromString("56713727820156410577229101238628035242"),
73+ factory.fromString("113427455640312821154458202477256070485")
7574 );
7675 }
7776 }
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java +2 −1
@@ -22,7 +22,8 @@
2222 super("-p RandomPartitioner", DataType.varint());
2323 }
2424
25- @Override protected Token.Factory tokenFactory() {
25+ @Override
26+ protected Token.Factory tokenFactory() {
2627 return RPToken.FACTORY;
2728 }
2829 }
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java +2 −1
@@ -20,7 +20,8 @@
2020 super("-p RandomPartitioner", DataType.varint(), true);
2121 }
2222
23- @Override protected Token.Factory tokenFactory() {
23+ @Override
24+ protected Token.Factory tokenFactory() {
2425 return Token.RPToken.FACTORY;
2526 }
2627 }
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +17 −18
@@ -15,25 +15,24 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.TimeUnit;
19-
18+import com.datastax.driver.core.utils.CassandraVersion;
2019 import org.slf4j.Logger;
2120 import org.slf4j.LoggerFactory;
2221 import org.testng.annotations.AfterMethod;
2322 import org.testng.annotations.BeforeMethod;
2423 import org.testng.annotations.Test;
2524
25+import java.util.concurrent.TimeUnit;
2626
27-import com.datastax.driver.core.utils.CassandraVersion;
28-
29-import static com.datastax.driver.core.Assertions.*;
27+import static com.datastax.driver.core.Assertions.assertThat;
28+import static com.datastax.driver.core.Assertions.fail;
3029 import static com.datastax.driver.core.Host.State.DOWN;
3130 import static com.datastax.driver.core.Host.State.UP;
3231 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3332
3433 /**
3534 * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
36- *
35+ * <p/>
3736 * This class tests scenarios where these nodes have been recommissioned to another cluster and
3837 * come back up. The driver must detect that they are not part of the cluster anymore, and ignore them.
3938 */
@@ -52,7 +51,7 @@
5251
5352 // Now start the driver that will connect to node2 and node3, and consider node1 down
5453 mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
55- .withQueryOptions(nonDebouncingQueryOptions()).build();
54+ .withQueryOptions(nonDebouncingQueryOptions()).build();
5655 mainCluster.connect();
5756 waitForCountUpHosts(mainCluster, 2);
5857 // From that point, reconnections to node1 have been scheduled.
@@ -75,7 +74,7 @@
7574
7675 // Start the driver, the control connection will be on node2
7776 mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
78- .withQueryOptions(nonDebouncingQueryOptions()).build();
77+ .withQueryOptions(nonDebouncingQueryOptions()).build();
7978 mainCluster.connect();
8079 waitForCountUpHosts(mainCluster, 1);
8180
@@ -103,7 +102,7 @@
103102
104103 // Start the driver, it should only connect to node 2
105104 mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
106- .withQueryOptions(nonDebouncingQueryOptions()).build();
105+ .withQueryOptions(nonDebouncingQueryOptions()).build();
107106
108107 // When we first initialize the Cluster, all hosts are marked UP
109108 assertThat(mainCluster).host(2).hasState(UP);
@@ -114,13 +113,13 @@
114113
115114 // Node 1 should now be DOWN with no reconnection attempt
116115 assertThat(mainCluster).host(1)
117- .goesDownWithin(10, TimeUnit.SECONDS)
118- .hasState(DOWN)
119- .isNotReconnectingFromDown();
116+ .goesDownWithin(10, TimeUnit.SECONDS)
117+ .hasState(DOWN)
118+ .isNotReconnectingFromDown();
120119 }
121120
122121 @Test(groups = "long")
123- @CassandraVersion(major=2.0)
122+ @CassandraVersion(major = 2.0)
124123 public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception {
125124 // Simulate the bug before starting the cluster
126125 mainCcm = CCMBridge.builder("main").withNodes(2).build();
@@ -132,16 +131,16 @@
132131
133132 // Start the driver, it should only connect to node 2
134133 mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
135- .withQueryOptions(nonDebouncingQueryOptions()).build();
134+ .withQueryOptions(nonDebouncingQueryOptions()).build();
136135
137136 // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version.
138137 mainCluster.connect();
139138
140139 // Node 1 should now be DOWN with no reconnection attempt
141140 assertThat(mainCluster).host(1)
142- .goesDownWithin(10, TimeUnit.SECONDS)
143- .hasState(DOWN)
144- .isNotReconnectingFromDown();
141+ .goesDownWithin(10, TimeUnit.SECONDS)
142+ .hasState(DOWN)
143+ .isNotReconnectingFromDown();
145144 }
146145
147146 @BeforeMethod(groups = "long")
@@ -183,7 +182,7 @@
183182
184183 if (i == maxRetries)
185184 fail(String.format("Up host count didn't reach %d after %d seconds",
186- expectedCount, i * interval));
185+ expectedCount, i * interval));
187186 else
188187 logger.debug("Counted {} up hosts after {} seconds", actualCount, i * interval);
189188
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java +18 −11
@@ -15,14 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import org.testng.annotations.Test;
19-import static org.testng.Assert.assertTrue;
20-import static org.testng.Assert.fail;
21-
2218 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2319 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
2420 import com.datastax.driver.core.policies.ExponentialReconnectionPolicy;
2521 import com.datastax.driver.core.policies.ReconnectionPolicy;
22+import org.testng.annotations.Test;
23+
24+import static org.testng.Assert.assertTrue;
25+import static org.testng.Assert.fail;
2626
2727 public class ReconnectionPolicyTest extends AbstractPoliciesTest {
2828
@@ -47,22 +47,26 @@
4747 try {
4848 new ExponentialReconnectionPolicy(-1, 1);
4949 fail();
50- } catch (IllegalArgumentException e) {}
50+ } catch (IllegalArgumentException e) {
51+ }
5152
5253 try {
5354 new ExponentialReconnectionPolicy(1, -1);
5455 fail();
55- } catch (IllegalArgumentException e) {}
56+ } catch (IllegalArgumentException e) {
57+ }
5658
5759 try {
5860 new ExponentialReconnectionPolicy(-1, -1);
5961 fail();
60- } catch (IllegalArgumentException e) {}
62+ } catch (IllegalArgumentException e) {
63+ }
6164
6265 try {
6366 new ExponentialReconnectionPolicy(2, 1);
6467 fail();
65- } catch (IllegalArgumentException e) {}
68+ } catch (IllegalArgumentException e) {
69+ }
6670
6771 // Test nextDelays()
6872 ReconnectionPolicy.ReconnectionSchedule schedule = new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000).newSchedule();
@@ -104,7 +108,8 @@
104108 try {
105109 new ConstantReconnectionPolicy(-1);
106110 fail();
107- } catch (IllegalArgumentException e) {}
111+ } catch (IllegalArgumentException e) {
112+ }
108113
109114 // Test nextDelays()
110115 ReconnectionPolicy.ReconnectionSchedule schedule = new ConstantReconnectionPolicy(10 * 1000).newSchedule();
@@ -142,7 +147,8 @@
142147 startTime = System.nanoTime() / 1000000000;
143148 query(c, 12);
144149 fail("Test race condition where node has not shut off quickly enough.");
145- } catch (NoHostAvailableException e) {}
150+ } catch (NoHostAvailableException e) {
151+ }
146152
147153 long thisTime;
148154 boolean restarted = false;
@@ -184,7 +190,8 @@
184190 startTime = System.nanoTime() / 1000000000;
185191 query(c, 12);
186192 fail("Test race condition where node has not shut off quickly enough.");
187- } catch (NoHostAvailableException e) {}
193+ } catch (NoHostAvailableException e) {
194+ }
188195
189196 restarted = false;
190197 while (true) {
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +44 −45
@@ -15,6 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.Host.State;
19+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
20+import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
21+import com.datastax.driver.core.policies.LoadBalancingPolicy;
22+import com.datastax.driver.core.policies.RoundRobinPolicy;
23+import com.google.common.util.concurrent.ListenableFuture;
24+import org.testng.annotations.Test;
25+
1826 import java.io.IOException;
1927 import java.net.InetSocketAddress;
2028 import java.util.Collections;
@@ -24,21 +32,10 @@
2432 import java.util.concurrent.TimeUnit;
2533 import java.util.concurrent.atomic.AtomicInteger;
2634
35+import static com.datastax.driver.core.Assertions.assertThat;
2736 import static java.util.concurrent.TimeUnit.SECONDS;
28-
29-import com.google.common.util.concurrent.ListenableFuture;
30-import org.testng.annotations.Test;
31-
3237 import static org.assertj.core.api.Assertions.assertThat;
33-import static org.mockito.Mockito.reset;
34-import static org.mockito.Mockito.spy;
35-import static org.mockito.Mockito.times;
36-import static org.mockito.Mockito.verify;
37-
38-import com.datastax.driver.core.Host.State;
39-import com.datastax.driver.core.policies.*;
40-
41-import static com.datastax.driver.core.Assertions.assertThat;
38+import static org.mockito.Mockito.*;
4239
4340 /**
4441 * Scenarios where a Cluster loses connection to a host and reconnects.
@@ -53,9 +50,9 @@
5350 ccm = CCMBridge.builder("test").withNodes(2).build();
5451 int reconnectionDelay = 1000;
5552 cluster = Cluster.builder()
56- .addContactPoint(CCMBridge.ipOfNode(1))
57- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
58- .build();
53+ .addContactPoint(CCMBridge.ipOfNode(1))
54+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay))
55+ .build();
5956 cluster.connect();
6057
6158 assertThat(cluster).usesControlHost(1);
@@ -69,7 +66,7 @@
6966 ccm.start(2);
7067 ccm.waitForUp(2);
7168
72- assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
69+ assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
7370
7471 // Give the control connection a few moments to reconnect
7572 TimeUnit.MILLISECONDS.sleep(reconnectionDelay * 2);
@@ -88,9 +85,9 @@
8885 Cluster cluster = null;
8986 try {
9087 ccm = CCMBridge.builder("test")
91- .withCassandraConfiguration("authenticator", "PasswordAuthenticator") // default credentials: cassandra / cassandra
92- .notStarted()
93- .build();
88+ .withCassandraConfiguration("authenticator", "PasswordAuthenticator") // default credentials: cassandra / cassandra
89+ .notStarted()
90+ .build();
9491 ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
9592
9693 CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra");
@@ -98,11 +95,11 @@
9895 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
9996
10097 cluster = Cluster.builder()
101- .addContactPoint(CCMBridge.ipOfNode(1))
102- // Start with the correct auth so that we can initialize the server
103- .withAuthProvider(authProvider)
104- .withReconnectionPolicy(reconnectionPolicy)
105- .build();
98+ .addContactPoint(CCMBridge.ipOfNode(1))
99+ // Start with the correct auth so that we can initialize the server
100+ .withAuthProvider(authProvider)
101+ .withReconnectionPolicy(reconnectionPolicy)
102+ .build();
106103
107104 cluster.init();
108105 assertThat(cluster).usesControlHost(1);
@@ -128,7 +125,7 @@
128125 authProvider.setPassword("cassandra");
129126
130127 // The driver should eventually reconnect to the node
131- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
128+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
132129 } finally {
133130 if (cluster != null)
134131 cluster.close();
@@ -148,9 +145,9 @@
148145 try {
149146 ccm = CCMBridge.builder("test").withNodes(2).build();
150147 cluster = Cluster.builder()
151- .addContactPoint(CCMBridge.ipOfNode(1))
152- .withReconnectionPolicy(reconnectionPolicy)
153- .build();
148+ .addContactPoint(CCMBridge.ipOfNode(1))
149+ .withReconnectionPolicy(reconnectionPolicy)
150+ .build();
154151 cluster.connect();
155152
156153 // Stop a node and cancel the reconnection attempts to it
@@ -168,7 +165,7 @@
168165 ccm.waitForUp(2);
169166
170167 // The driver should now see the node as UP again
171- assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
168+ assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
172169
173170 } finally {
174171 if (cluster != null)
@@ -189,10 +186,10 @@
189186 try {
190187 ccm = CCMBridge.builder("test").withNodes(1).build();
191188 cluster = Cluster.builder()
192- .addContactPoint(CCMBridge.ipOfNode(1))
193- .withLoadBalancingPolicy(loadBalancingPolicy)
194- .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
195- .build();
189+ .addContactPoint(CCMBridge.ipOfNode(1))
190+ .withLoadBalancingPolicy(loadBalancingPolicy)
191+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis))
192+ .build();
196193 cluster.connect();
197194
198195 // Tweak the LBP so that the control connection never reconnects, otherwise
@@ -229,7 +226,7 @@
229226 // Trigger another one-time reconnection attempt (this will succeed). The
230227 // host should be back up.
231228 host1.tryReconnectOnce();
232- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
229+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
233230 } finally {
234231 if (cluster != null)
235232 cluster.close();
@@ -255,12 +252,12 @@
255252 try {
256253 ccm = CCMBridge.builder("test").withNodes(1).build();
257254 cluster = Cluster.builder()
258- .addContactPoint(CCMBridge.ipOfNode(1))
259- .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
260- .withLoadBalancingPolicy(loadBalancingPolicy)
261- .withSocketOptions(socketOptions)
262- .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
263- .build();
255+ .addContactPoint(CCMBridge.ipOfNode(1))
256+ .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
257+ .withLoadBalancingPolicy(loadBalancingPolicy)
258+ .withSocketOptions(socketOptions)
259+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
260+ .build();
264261 // Create two sessions to have multiple pools
265262 cluster.connect();
266263 cluster.connect();
@@ -287,7 +284,7 @@
287284 // Reset the spy and count the number of connections attempts for 1 reconnect
288285 reset(socketOptions);
289286 host1.tryReconnectOnce();
290- assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
287+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS);
291288 // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
292289 // but the one from the reconnection attempt gets reused).
293290 verify(socketOptions, times(corePoolSize * 2)).getKeepAlive();
@@ -299,7 +296,9 @@
299296 }
300297 }
301298
302- /** Extends the plain text auth provider to track how many times the credentials have been requested */
299+ /**
300+ * Extends the plain text auth provider to track how many times the credentials have been requested
301+ */
303302 static class CountingAuthProvider extends PlainTextAuthProvider {
304303 final AtomicInteger count = new AtomicInteger();
305304
@@ -332,8 +331,8 @@
332331 public HostDistance distance(Host host) {
333332 HostDistance distance = distances.get(host);
334333 return (distance != null)
335- ? distance
336- : super.distance(host);
334+ ? distance
335+ : super.distance(host);
337336 }
338337
339338 public void setDistance(Host host, HostDistance distance) {
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +25 −27
@@ -15,17 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import static java.util.concurrent.TimeUnit.SECONDS;
19-
20-import org.mockito.Mockito;
21-import org.testng.annotations.Test;
22-
2318 import com.datastax.driver.core.Host.State;
2419 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
2520 import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy;
2621 import com.datastax.driver.core.policies.RoundRobinPolicy;
22+import org.mockito.Mockito;
23+import org.testng.annotations.Test;
2724
2825 import static com.datastax.driver.core.Assertions.assertThat;
26+import static java.util.concurrent.TimeUnit.SECONDS;
2927
3028 public class RefreshConnectedHostTest {
3129
@@ -49,40 +47,40 @@
4947
5048 PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
5149 cluster = Cluster.builder()
52- .addContactPoint(CCMBridge.ipOfNode(1))
53- .withPoolingOptions(poolingOptions)
54- .withLoadBalancingPolicy(loadBalancingPolicy)
55- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
56- .withQueryOptions(TestUtils.nonDebouncingQueryOptions())
57- .build();
50+ .addContactPoint(CCMBridge.ipOfNode(1))
51+ .withPoolingOptions(poolingOptions)
52+ .withLoadBalancingPolicy(loadBalancingPolicy)
53+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
54+ .withQueryOptions(TestUtils.nonDebouncingQueryOptions())
55+ .build();
5856
5957 Session session = cluster.connect();
6058
6159 assertThat(cluster).usesControlHost(1);
6260 assertThat(cluster).host(1)
63- .hasState(State.UP)
64- .isAtDistance(HostDistance.LOCAL);
61+ .hasState(State.UP)
62+ .isAtDistance(HostDistance.LOCAL);
6563 // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
6664 // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
6765 assertThat(cluster).host(2)
68- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
69- .isAtDistance(HostDistance.LOCAL);
66+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS)
67+ .isAtDistance(HostDistance.LOCAL);
7068
7169 // Bring host 3 up, its presence should be acknowledged but it should be ignored
7270 ccm.start(3);
7371 ccm.waitForUp(3);
7472
7573 assertThat(cluster).host(1)
76- .hasState(State.UP)
77- .isAtDistance(HostDistance.LOCAL);
74+ .hasState(State.UP)
75+ .isAtDistance(HostDistance.LOCAL);
7876 assertThat(cluster).host(2)
79- .hasState(State.UP)
80- .isAtDistance(HostDistance.LOCAL);
77+ .hasState(State.UP)
78+ .isAtDistance(HostDistance.LOCAL);
8179
8280 // Ensure that the host is added to the Cluster.
8381 assertThat(cluster).host(3)
84- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
85- .isAtDistance(HostDistance.IGNORED);
82+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS)
83+ .isAtDistance(HostDistance.IGNORED);
8684 assertThat(session).hasNoPoolFor(3);
8785
8886 // Kill host 2, host 3 should take its place
@@ -90,19 +88,19 @@
9088 TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
9189
9290 assertThat(cluster).host(1)
93- .hasState(State.UP)
94- .isAtDistance(HostDistance.LOCAL);
91+ .hasState(State.UP)
92+ .isAtDistance(HostDistance.LOCAL);
9593 assertThat(cluster).host(2)
96- .hasState(State.DOWN);
94+ .hasState(State.DOWN);
9795 assertThat(cluster).host(3)
98- .hasState(State.UP)
99- .isAtDistance(HostDistance.LOCAL);
96+ .hasState(State.UP)
97+ .isAtDistance(HostDistance.LOCAL);
10098 assertThat(session).hasPoolFor(3);
10199
102100 // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
103101 // we switch the node from IGNORED to UP:
104102 Mockito.verify(poolingOptions)
105- .refreshConnectedHost(TestUtils.findHost(cluster, 3));
103+ .refreshConnectedHost(TestUtils.findHost(cluster, 3));
106104
107105 } finally {
108106 if (cluster != null)
modified driver-core/src/test/java/com/datastax/driver/core/ReplicationStrategyTest.java +18 −17
@@ -17,6 +17,7 @@
1717
1818 import com.google.common.collect.ImmutableMap;
1919 import org.testng.annotations.Test;
20+
2021 import static org.testng.Assert.*;
2122
2223 public class ReplicationStrategyTest {
@@ -25,9 +26,9 @@
2526 public void createSimpleReplicationStrategyTest() throws Exception {
2627 ReplicationStrategy strategy = ReplicationStrategy.create(
2728 ImmutableMap.<String, String>builder()
28- .put("class", "SimpleStrategy")
29- .put("replication_factor", "3")
30- .build());
29+ .put("class", "SimpleStrategy")
30+ .put("replication_factor", "3")
31+ .build());
3132
3233 assertNotNull(strategy);
3334 assertTrue(strategy instanceof ReplicationStrategy.SimpleStrategy);
@@ -37,10 +38,10 @@
3738 public void createNetworkTopologyStrategyTest() throws Exception {
3839 ReplicationStrategy strategy = ReplicationStrategy.create(
3940 ImmutableMap.<String, String>builder()
40- .put("class", "NetworkTopologyStrategy")
41- .put("dc1", "2")
42- .put("dc2", "2")
43- .build());
41+ .put("class", "NetworkTopologyStrategy")
42+ .put("dc1", "2")
43+ .put("dc2", "2")
44+ .build());
4445
4546 assertNotNull(strategy);
4647 assertTrue(strategy instanceof ReplicationStrategy.NetworkTopologyStrategy);
@@ -50,9 +51,9 @@
5051 public void createSimpleReplicationStrategyWithoutFactorTest() throws Exception {
5152 ReplicationStrategy strategy = ReplicationStrategy.create(
5253 ImmutableMap.<String, String>builder()
53- .put("class", "SimpleStrategy")
54- //no replication_factor
55- .build());
54+ .put("class", "SimpleStrategy")
55+ //no replication_factor
56+ .build());
5657
5758 assertNull(strategy);
5859 }
@@ -61,10 +62,10 @@
6162 public void createUnknownStrategyTest() throws Exception {
6263 ReplicationStrategy strategy = ReplicationStrategy.create(
6364 ImmutableMap.<String, String>builder()
64- //no such strategy
65- .put("class", "FooStrategy")
66- .put("foo_factor", "3")
67- .build());
65+ //no such strategy
66+ .put("class", "FooStrategy")
67+ .put("foo_factor", "3")
68+ .build());
6869
6970 assertNull(strategy);
7071 }
@@ -73,9 +74,9 @@
7374 public void createUnspecifiedStrategyTest() throws Exception {
7475 ReplicationStrategy strategy = ReplicationStrategy.create(
7576 ImmutableMap.<String, String>builder()
76- //nothing useful is set
77- .put("foo", "bar")
78- .build());
77+ //nothing useful is set
78+ .put("foo", "bar")
79+ .build());
7980
8081 assertNull(strategy);
8182 }
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +18 −18
@@ -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,23 +36,23 @@
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()
47- .addContactPoint("127.0.0.1")
48- .withPort(scassandra.getBinaryPort())
49- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
50- .withProtocolVersion(ProtocolVersion.V2)
51- .withPoolingOptions(new PoolingOptions()
52- .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
53- .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
54- .setHeartbeatIntervalSeconds(0))
55- .build();
47+ .addContactPoint("127.0.0.1")
48+ .withPort(scassandra.getBinaryPort())
49+ // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
50+ .withProtocolVersion(ProtocolVersion.V2)
51+ .withPoolingOptions(new PoolingOptions()
52+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
53+ .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
54+ .setHeartbeatIntervalSeconds(0))
55+ .build();
5656
5757 Session session = cluster.connect();
5858
@@ -86,7 +86,7 @@
8686 }
8787
8888 private Connection getSingleConnection(Session session) {
89- HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next();
89+ HostConnectionPool pool = ((SessionManager) session).pools.values().iterator().next();
9090 return pool.connections.get(0);
9191 }
9292 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +5 −6
@@ -15,9 +15,8 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import org.testng.annotations.Test;
19-
2018 import com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import org.testng.annotations.Test;
2120
2221 public class SSLAuthenticatedEncryptionTest extends SSLTestBase {
2322
@@ -35,11 +34,11 @@
3534 * @test_category connection:ssl, authentication
3635 * @expected_result Connection can be established to a cassandra node using SSL that requires client auth.
3736 */
38- @Test(groups="short", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class)
37+ @Test(groups = "short", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class)
3938 public void should_connect_with_ssl_with_client_auth_and_node_requires_auth(SslImplementation sslImplementation) throws Exception {
4039 connectWithSSLOptions(getSSLOptions(sslImplementation, true, true));
4140 }
42-
41+
4342 /**
4443 * <p>
4544 * Validates that an SSL connection can not be established with if the target
@@ -50,7 +49,7 @@
5049 * @test_category connection:ssl, authentication
5150 * @expected_result Connection is not established.
5251 */
53- @Test(groups="short", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class, expectedExceptions={NoHostAvailableException.class})
52+ @Test(groups = "short", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class, expectedExceptions = {NoHostAvailableException.class})
5453 public void should_not_connect_without_client_auth_but_node_requires_auth(SslImplementation sslImplementation) throws Exception {
5554 connectWithSSLOptions(getSSLOptions(sslImplementation, false, true));
5655 }
@@ -63,7 +62,7 @@
6362 * @test_category connection:ssl, authentication
6463 * @expected_result Connection can be established.
6564 */
66- @Test(groups="isolated")
65+ @Test(groups = "isolated")
6766 public void should_use_system_properties_with_default_ssl_options() throws Exception {
6867 System.setProperty("javax.net.ssl.keyStore", CCMBridge.DEFAULT_CLIENT_KEYSTORE_FILE.getAbsolutePath());
6968 System.setProperty("javax.net.ssl.keyStorePassword", CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD);
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +13 −14
@@ -15,11 +15,10 @@
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 org.testng.annotations.Test;
2120
22-import com.datastax.driver.core.exceptions.NoHostAvailableException;
21+import java.util.concurrent.TimeUnit;
2322
2423 import static com.datastax.driver.core.Assertions.assertThat;
2524
@@ -38,7 +37,7 @@
3837 * @test_category connection:ssl
3938 * @expected_result Connection can be established to a cassandra node using SSL.
4039 */
41- @Test(groups="short", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class)
40+ @Test(groups = "short", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class)
4241 public void should_connect_with_ssl_without_client_auth_and_node_doesnt_require_auth(SslImplementation sslImplementation) throws Exception {
4342 connectWithSSLOptions(getSSLOptions(sslImplementation, false, true));
4443 }
@@ -52,7 +51,7 @@
5251 * @test_category connection:ssl
5352 * @expected_result Connection can not be established to a cassandra node using SSL with an untrusted cert.
5453 */
55- @Test(groups="short", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class, expectedExceptions={NoHostAvailableException.class})
54+ @Test(groups = "short", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class, expectedExceptions = {NoHostAvailableException.class})
5655 public void should_not_connect_with_ssl_without_trusting_server_cert(SslImplementation sslImplementation) throws Exception {
5756 connectWithSSLOptions(getSSLOptions(sslImplementation, false, false));
5857 }
@@ -62,7 +61,7 @@
6261 * Validates that an SSL connection can not be established if the client is not specifying SSL, but
6362 * the cassandra node is using SSL.
6463 * </p>
65- *
64+ * <p/>
6665 * <p>
6766 * Note that future versions of cassandra may support both SSL-encrypted and non-SSL connections
6867 * simultaneously (CASSANDRA-8803)
@@ -71,13 +70,13 @@
7170 * @test_category connection:ssl
7271 * @expected_result Connection can not be established to a cassandra node using SSL and the client not using SSL.
7372 */
74- @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
73+ @Test(groups = "short", expectedExceptions = {NoHostAvailableException.class})
7574 public void should_not_connect_without_ssl_but_node_uses_ssl() throws Exception {
7675 Cluster cluster = null;
7776 try {
7877 cluster = Cluster.builder()
79- .addContactPoint(CCMBridge.IP_PREFIX + '1')
80- .build();
78+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
79+ .build();
8180
8281 cluster.connect();
8382 } finally {
@@ -95,14 +94,14 @@
9594 * @test_category connection:ssl
9695 * @expected_result Connection is re-established within a sufficient amount of time after a node comes back online.
9796 */
98- @Test(groups="long", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class)
97+ @Test(groups = "long", dataProvider = "sslImplementation", dataProviderClass = SSLTestBase.class)
9998 public void should_reconnect_with_ssl_on_node_up(SslImplementation sslImplementation) throws Exception {
10099 Cluster cluster = null;
101100 try {
102101 cluster = Cluster.builder()
103- .addContactPoint(CCMBridge.IP_PREFIX + '1')
104- .withSSL(getSSLOptions(sslImplementation, true, true))
105- .build();
102+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
103+ .withSSL(getSSLOptions(sslImplementation, true, true))
104+ .build();
106105
107106 cluster.connect();
108107
@@ -124,7 +123,7 @@
124123 * @test_category connection:ssl
125124 * @expected_result Connection can be established.
126125 */
127- @Test(groups="isolated")
126+ @Test(groups = "isolated")
128127 public void should_use_system_properties_with_default_ssl_options() throws Exception {
129128 System.setProperty("javax.net.ssl.trustStore", CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
130129 System.setProperty("javax.net.ssl.trustStorePassword", CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +33 −34
@@ -15,22 +15,21 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.security.KeyStore;
19-import java.security.SecureRandom;
20-
2118 import io.netty.handler.ssl.SslContextBuilder;
22-import javax.net.ssl.KeyManagerFactory;
23-import javax.net.ssl.SSLContext;
24-import javax.net.ssl.TrustManagerFactory;
2519 import org.testng.annotations.AfterClass;
2620 import org.testng.annotations.BeforeClass;
2721 import org.testng.annotations.DataProvider;
2822
29-import static io.netty.handler.ssl.SslProvider.OPENSSL;
30-import static org.assertj.core.api.Assertions.fail;
23+import javax.net.ssl.KeyManagerFactory;
24+import javax.net.ssl.SSLContext;
25+import javax.net.ssl.TrustManagerFactory;
26+import java.security.KeyStore;
27+import java.security.SecureRandom;
3128
3229 import static com.datastax.driver.core.SSLTestBase.SslImplementation.JDK;
3330 import static com.datastax.driver.core.SSLTestBase.SslImplementation.NETTY_OPENSSL;
31+import static io.netty.handler.ssl.SslProvider.OPENSSL;
32+import static org.assertj.core.api.Assertions.fail;
3433
3534 public abstract class SSLTestBase {
3635
@@ -42,25 +41,25 @@
4241 this.requireClientAuth = requireClientAuth;
4342 }
4443
45- @DataProvider(name="sslImplementation")
44+ @DataProvider(name = "sslImplementation")
4645 public static Object[][] sslImplementation() {
4746 // Bypass Netty SSL if on JDK 1.6 since it only works on 1.7+.
4847 String javaVersion = System.getProperty("java.version");
49- if(javaVersion.startsWith("1.6")) {
50- return new Object[][]{ { JDK } };
48+ if (javaVersion.startsWith("1.6")) {
49+ return new Object[][]{{JDK}};
5150 } else {
52- return new Object[][]{ { JDK }, { NETTY_OPENSSL } };
51+ return new Object[][]{{JDK}, {NETTY_OPENSSL}};
5352 }
5453 }
5554
56- @BeforeClass(groups={"isolated", "short", "long"})
55+ @BeforeClass(groups = {"isolated", "short", "long"})
5756 public void beforeClass() {
5857 ccm = CCMBridge.builder("test")
59- .withSSL(requireClientAuth)
60- .build();
58+ .withSSL(requireClientAuth)
59+ .build();
6160 }
6261
63- @AfterClass(groups={"isolated", "short", "long"})
62+ @AfterClass(groups = {"isolated", "short", "long"})
6463 public void afterClass() {
6564 ccm.remove();
6665 }
@@ -73,15 +72,15 @@
7372 *
7473 * @param sslOptions SSLOptions to use.
7574 * @throws Exception A {@link com.datastax.driver.core.exceptions.NoHostAvailableException} will be
76- * raised here if connection cannot be established.
75+ * raised here if connection cannot be established.
7776 */
7877 protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception {
7978 Cluster cluster = null;
8079 try {
8180 cluster = Cluster.builder()
82- .addContactPoint(CCMBridge.IP_PREFIX + '1')
83- .withSSL(sslOptions)
84- .build();
81+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
82+ .withSSL(sslOptions)
83+ .build();
8584
8685 cluster.connect();
8786 } finally {
@@ -97,15 +96,15 @@
9796 * </p>
9897 *
9998 * @throws Exception A {@link com.datastax.driver.core.exceptions.NoHostAvailableException} will be
100- * raised here if connection cannot be established.
99+ * raised here if connection cannot be established.
101100 */
102101 protected void connectWithSSL() throws Exception {
103102 Cluster cluster = null;
104103 try {
105104 cluster = Cluster.builder()
106- .addContactPoint(CCMBridge.IP_PREFIX + '1')
107- .withSSL()
108- .build();
105+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
106+ .withSSL()
107+ .build();
109108
110109 cluster.connect();
111110 } finally {
@@ -114,12 +113,12 @@
114113 }
115114 }
116115
117- enum SslImplementation { JDK, NETTY_OPENSSL}
116+ enum SslImplementation {JDK, NETTY_OPENSSL}
118117
119118 /**
120119 * @param sslImplementation the SSL implementation to use
121- * @param clientAuth whether the client should authenticate
122- * @param trustingServer whether the client should trust the server's certificate
120+ * @param clientAuth whether the client should authenticate
121+ * @param trustingServer whether the client should trust the server's certificate
123122 * @return {@link com.datastax.driver.core.SSLOptions} with the given configuration for
124123 * server certificate validation and client certificate authentication.
125124 */
@@ -129,8 +128,8 @@
129128 if (trustingServer) {
130129 KeyStore ks = KeyStore.getInstance("JKS");
131130 ks.load(
132- this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH),
133- CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD.toCharArray());
131+ this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH),
132+ CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD.toCharArray());
134133
135134 tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
136135 tmf.init(ks);
@@ -143,8 +142,8 @@
143142 if (clientAuth) {
144143 KeyStore ks = KeyStore.getInstance("JKS");
145144 ks.load(
146- this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH),
147- CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
145+ this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH),
146+ CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
148147
149148 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
150149 kmf.init(ks, CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
@@ -157,9 +156,9 @@
157156
158157 case NETTY_OPENSSL:
159158 SslContextBuilder builder = SslContextBuilder
160- .forClient()
161- .sslProvider(OPENSSL)
162- .trustManager(tmf);
159+ .forClient()
160+ .sslProvider(OPENSSL)
161+ .trustManager(tmf);
163162
164163 if (clientAuth) {
165164 builder.keyManager(CCMBridge.DEFAULT_CLIENT_CERT_CHAIN_FILE, CCMBridge.DEFAULT_CLIENT_PRIVATE_KEY_FILE);
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +135 −136
@@ -15,11 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.Map;
20-import java.util.TreeSet;
21-import java.util.concurrent.TimeUnit;
22-
2318 import com.beust.jcommander.internal.Lists;
2419 import com.beust.jcommander.internal.Maps;
2520 import com.google.common.collect.ImmutableList;
@@ -32,14 +27,18 @@
3227 import org.slf4j.Logger;
3328 import org.slf4j.LoggerFactory;
3429
30+import java.util.List;
31+import java.util.Map;
32+import java.util.TreeSet;
33+import java.util.concurrent.TimeUnit;
34+
35+import static com.datastax.driver.core.Assertions.assertThat;
3536 import static org.scassandra.cql.MapType.map;
3637 import static org.scassandra.cql.PrimitiveType.*;
3738 import static org.scassandra.cql.SetType.set;
3839 import static org.scassandra.http.client.PrimingRequest.then;
3940 import static org.scassandra.http.client.types.ColumnMetadata.column;
4041
41-import static com.datastax.driver.core.Assertions.assertThat;
42-
4342 public class ScassandraCluster {
4443
4544 private static final Logger logger = LoggerFactory.getLogger(ScassandraCluster.class);
@@ -152,12 +151,12 @@
152151 /**
153152 * First stops each node in {@code dc} and then asserts that each node's {@link Host}
154153 * is marked down for the given {@link Cluster} instance within 10 seconds.
155- *
154+ * <p/>
156155 * If any of the nodes are the control host, this node is stopped last, to reduce
157156 * likelihood of control connection choosing a host that will be shut down.
158157 *
159158 * @param cluster cluster to wait for down statuses on.
160- * @param dc DC to stop.
159+ * @param dc DC to stop.
161160 */
162161 public void stopDC(Cluster cluster, int dc) {
163162 logger.debug("Stopping all nodes in {}.", datacenter(dc));
@@ -184,7 +183,7 @@
184183 * for the given {@link Cluster} instance within 10 seconds.
185184 *
186185 * @param cluster cluster to wait for down status on.
187- * @param node Node to stop.
186+ * @param node Node to stop.
188187 */
189188 public void stop(Cluster cluster, int node) {
190189 logger.debug("Stopping node {}.", node);
@@ -198,8 +197,8 @@
198197 * for the given {@link Cluster} instance within 10 seconds.
199198 *
200199 * @param cluster cluster to wait for down status on.
201- * @param dc Data center node is in.
202- * @param node Node to stop.
200+ * @param dc Data center node is in.
201+ * @param node Node to stop.
203202 */
204203 public void stop(Cluster cluster, int dc, int node) {
205204 logger.debug("Stopping node {} in {}.", node, datacenter(dc));
@@ -211,7 +210,7 @@
211210 * is marked up for the given {@link Cluster} instance within 10 seconds.
212211 *
213212 * @param cluster cluster to wait for up statuses on.
214- * @param dc DC to start.
213+ * @param dc DC to start.
215214 */
216215 public void startDC(Cluster cluster, int dc) {
217216 logger.debug("Starting all nodes in {}.", datacenter(dc));
@@ -226,7 +225,7 @@
226225 * for the given {@link Cluster} instance within 10 seconds.
227226 *
228227 * @param cluster cluster to wait for up status on.
229- * @param node Node to start.
228+ * @param node Node to start.
230229 */
231230 public void start(Cluster cluster, int node) {
232231 logger.debug("Starting node {}.", node);
@@ -240,8 +239,8 @@
240239 * for the given {@link Cluster} instance within 10 seconds.
241240 *
242241 * @param cluster cluster to wait for up status on.
243- * @param dc Data center node is in.
244- * @param node Node to start.
242+ * @param dc Data center node is in.
243+ * @param node Node to start.
245244 */
246245 public void start(Cluster cluster, int dc, int node) {
247246 logger.debug("Starting node {} in {}.", node, datacenter(dc));
@@ -254,7 +253,7 @@
254253 int dcNodeCount = nodes(dc).size();
255254 List<Long> tokens = Lists.newArrayList(dcNodeCount);
256255 for (int i = 0; i < dcNodeCount; i++) {
257- tokens.add((i * ((long)Math.pow(2, 64) / dcNodeCount) + offset));
256+ tokens.add((i * ((long) Math.pow(2, 64) / dcNodeCount) + offset));
258257 }
259258 return tokens;
260259 }
@@ -277,69 +276,69 @@
277276 metadata = SELECT_LOCAL;
278277 query = "SELECT * FROM system.local WHERE key='local'";
279278 row = ImmutableMap.<String, Object>builder()
280- .put("key", "local")
281- .put("bootstrapped", "COMPLETED")
282- .put("broadcast_address", address)
283- .put("cluster_name", "scassandra")
284- .put("cql_version", "3.2.0")
285- .put("data_center", datacenter(dc))
286- .put("listen_address", address)
287- .put("partitioner", "org.apache.cassandra.dht.Murmur3Partitioner")
288- .put("rack", "rack1")
289- .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
290- .put("tokens", ImmutableSet.of(tokens.get(n)))
291- .build();
279+ .put("key", "local")
280+ .put("bootstrapped", "COMPLETED")
281+ .put("broadcast_address", address)
282+ .put("cluster_name", "scassandra")
283+ .put("cql_version", "3.2.0")
284+ .put("data_center", datacenter(dc))
285+ .put("listen_address", address)
286+ .put("partitioner", "org.apache.cassandra.dht.Murmur3Partitioner")
287+ .put("rack", "rack1")
288+ .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
289+ .put("tokens", ImmutableSet.of(tokens.get(n)))
290+ .build();
292291 } else { // prime system.peers.
293292 query = "SELECT * FROM system.peers WHERE peer='" + address + "'";
294293 metadata = SELECT_PEERS;
295294 row = ImmutableMap.<String, Object>builder()
296- .put("peer", address)
297- .put("rpc_address", address)
298- .put("data_center", datacenter(dc))
299- .put("rack", "rack1")
300- .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
301- .put("tokens", ImmutableSet.of(Long.toString(tokens.get(n))))
302- .build();
295+ .put("peer", address)
296+ .put("rpc_address", address)
297+ .put("data_center", datacenter(dc))
298+ .put("rack", "rack1")
299+ .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8"))
300+ .put("tokens", ImmutableSet.of(Long.toString(tokens.get(n))))
301+ .build();
303302 rows.add(row);
304303 }
305304 client.prime(PrimingRequest.queryBuilder()
306- .withQuery(query)
307- .withThen(then()
308- .withColumnTypes(metadata)
309- .withRows(row)
310- .build())
311- .build());
305+ .withQuery(query)
306+ .withThen(then()
307+ .withColumnTypes(metadata)
308+ .withRows(row)
309+ .build())
310+ .build());
312311 }
313312 }
314313
315314 client.prime(PrimingRequest.queryBuilder()
316- .withQuery("SELECT * FROM system.peers")
317- .withThen(then()
318- .withColumnTypes(SELECT_PEERS)
319- .withRows(rows.build())
320- .build())
321- .build());
315+ .withQuery("SELECT * FROM system.peers")
316+ .withThen(then()
317+ .withColumnTypes(SELECT_PEERS)
318+ .withRows(rows.build())
319+ .build())
320+ .build());
322321
323322 // Needed to ensure cluster_name matches what we expect on connection.
324323 Map<String, Object> clusterNameRow = ImmutableMap.<String, Object>builder()
325- .put("cluster_name", "scassandra")
326- .build();
324+ .put("cluster_name", "scassandra")
325+ .build();
327326 client.prime(PrimingRequest.queryBuilder()
328- .withQuery("select cluster_name from system.local")
329- .withThen(then()
330- .withColumnTypes(SELECT_CLUSTER_NAME)
331- .withRows(clusterNameRow)
332- .build())
333- .build());
327+ .withQuery("select cluster_name from system.local")
328+ .withThen(then()
329+ .withColumnTypes(SELECT_CLUSTER_NAME)
330+ .withRows(clusterNameRow)
331+ .build())
332+ .build());
334333
335334 // Prime keyspaces
336335 client.prime(PrimingRequest.queryBuilder()
337- .withQuery("SELECT * FROM system.schema_keyspaces")
338- .withThen(then()
339- .withColumnTypes(SELECT_SCHEMA_KEYSPACES)
340- .withRows(keyspaceRows)
341- .build())
342- .build());
336+ .withQuery("SELECT * FROM system.schema_keyspaces")
337+ .withThen(then()
338+ .withColumnTypes(SELECT_SCHEMA_KEYSPACES)
339+ .withRows(keyspaceRows)
340+ .build())
341+ .build());
343342 }
344343
345344 private Object getPeerInfo(int dc, int node, String property, Object defaultValue) {
@@ -352,87 +351,87 @@
352351 return defaultValue;
353352
354353 return (forNode.containsKey(property))
355- ? forNode.get(property)
356- : defaultValue;
354+ ? forNode.get(property)
355+ : defaultValue;
357356 }
358357
359358 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_PEERS = {
360- column("peer", INET),
361- column("rpc_address", INET),
362- column("data_center", TEXT),
363- column("rack", TEXT),
364- column("release_version", TEXT),
365- column("tokens", set(TEXT))
359+ column("peer", INET),
360+ column("rpc_address", INET),
361+ column("data_center", TEXT),
362+ column("rack", TEXT),
363+ column("release_version", TEXT),
364+ column("tokens", set(TEXT))
366365 };
367366
368367 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_LOCAL = {
369- column("key", TEXT),
370- column("bootstrapped", TEXT),
371- column("broadcast_address", INET),
372- column("cluster_name", TEXT),
373- column("cql_version", TEXT),
374- column("data_center", TEXT),
375- column("listen_address", INET),
376- column("partitioner", TEXT),
377- column("rack", TEXT),
378- column("release_version", TEXT),
379- column("tokens", set(TEXT)),
368+ column("key", TEXT),
369+ column("bootstrapped", TEXT),
370+ column("broadcast_address", INET),
371+ column("cluster_name", TEXT),
372+ column("cql_version", TEXT),
373+ column("data_center", TEXT),
374+ column("listen_address", INET),
375+ column("partitioner", TEXT),
376+ column("rack", TEXT),
377+ column("release_version", TEXT),
378+ column("tokens", set(TEXT)),
380379 };
381380
382381 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_CLUSTER_NAME = {
383- column("cluster_name", TEXT)
382+ column("cluster_name", TEXT)
384383 };
385384
386385 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_KEYSPACES = {
387- column("durable_writes", BOOLEAN),
388- column("keyspace_name", TEXT),
389- column("strategy_class", TEXT),
390- column("strategy_options", TEXT)
386+ column("durable_writes", BOOLEAN),
387+ column("keyspace_name", TEXT),
388+ column("strategy_class", TEXT),
389+ column("strategy_options", TEXT)
391390 };
392391
393392 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMN_FAMILIES = {
394- column("bloom_filter_fp_chance", DOUBLE),
395- column("caching", TEXT),
396- column("cf_id", UUID),
397- column("column_aliases", TEXT),
398- column("columnfamily_name", TEXT),
399- column("comment", TEXT),
400- column("compaction_strategy_class", TEXT),
401- column("compaction_strategy_options", TEXT),
402- column("comparator", TEXT),
403- column("compression_parameters", TEXT),
404- column("default_time_to_live", INT),
405- column("default_validator", TEXT),
406- column("dropped_columns", map(TEXT, BIG_INT)),
407- column("gc_grace_seconds", INT),
408- column("index_interval", INT),
409- column("is_dense", BOOLEAN),
410- column("key_aliases", TEXT),
411- column("key_validator", TEXT),
412- column("keyspace_name", TEXT),
413- column("local_read_repair_chance", DOUBLE),
414- column("max_compaction_threshold", INT),
415- column("max_index_interval", INT),
416- column("memtable_flush_period_in_ms", INT),
417- column("min_compaction_threshold", INT),
418- column("min_index_interval", INT),
419- column("read_repair_chance", DOUBLE),
420- column("speculative_retry", TEXT),
421- column("subcomparator", TEXT),
422- column("type", TEXT),
423- column("value_alias", TEXT)
393+ column("bloom_filter_fp_chance", DOUBLE),
394+ column("caching", TEXT),
395+ column("cf_id", UUID),
396+ column("column_aliases", TEXT),
397+ column("columnfamily_name", TEXT),
398+ column("comment", TEXT),
399+ column("compaction_strategy_class", TEXT),
400+ column("compaction_strategy_options", TEXT),
401+ column("comparator", TEXT),
402+ column("compression_parameters", TEXT),
403+ column("default_time_to_live", INT),
404+ column("default_validator", TEXT),
405+ column("dropped_columns", map(TEXT, BIG_INT)),
406+ column("gc_grace_seconds", INT),
407+ column("index_interval", INT),
408+ column("is_dense", BOOLEAN),
409+ column("key_aliases", TEXT),
410+ column("key_validator", TEXT),
411+ column("keyspace_name", TEXT),
412+ column("local_read_repair_chance", DOUBLE),
413+ column("max_compaction_threshold", INT),
414+ column("max_index_interval", INT),
415+ column("memtable_flush_period_in_ms", INT),
416+ column("min_compaction_threshold", INT),
417+ column("min_index_interval", INT),
418+ column("read_repair_chance", DOUBLE),
419+ column("speculative_retry", TEXT),
420+ column("subcomparator", TEXT),
421+ column("type", TEXT),
422+ column("value_alias", TEXT)
424423 };
425424
426425 static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_SCHEMA_COLUMNS = {
427- column("column_name", TEXT),
428- column("columnfamily_name", TEXT),
429- column("component_index", INT),
430- column("index_name", TEXT),
431- column("index_options", TEXT),
432- column("index_type", TEXT),
433- column("keyspace_name", TEXT),
434- column("type", TEXT),
435- column("validator", TEXT),
426+ column("column_name", TEXT),
427+ column("columnfamily_name", TEXT),
428+ column("component_index", INT),
429+ column("index_name", TEXT),
430+ column("index_options", TEXT),
431+ column("index_type", TEXT),
432+ column("keyspace_name", TEXT),
433+ column("type", TEXT),
434+ column("validator", TEXT),
436435 };
437436
438437 public static ScassandraClusterBuilder builder() {
@@ -441,7 +440,7 @@
441440
442441 public static class ScassandraClusterBuilder {
443442
444- private Integer nodes[] = { 1 };
443+ private Integer nodes[] = {1};
445444 private String ipPrefix = CCMBridge.IP_PREFIX;
446445 private final List<Map<String, ? extends Object>> keyspaceRows = Lists.newArrayList();
447446 private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos = Maps.newHashMap();
@@ -458,11 +457,11 @@
458457
459458 public ScassandraClusterBuilder withSimpleKeyspace(String name, int replicationFactor) {
460459 Map<String, Object> simpleKeyspaceRow = ImmutableMap.<String, Object>builder()
461- .put("durable_writes", false)
462- .put("keyspace_name", name)
463- .put("strategy_class", "SimpleStrategy")
464- .put("strategy_options", "{\"replication_factor\":\"" + replicationFactor + "\"}")
465- .build();
460+ .put("durable_writes", false)
461+ .put("keyspace_name", name)
462+ .put("strategy_class", "SimpleStrategy")
463+ .put("strategy_options", "{\"replication_factor\":\"" + replicationFactor + "\"}")
464+ .build();
466465
467466 keyspaceRows.add(simpleKeyspaceRow);
468467 return this;
@@ -481,11 +480,11 @@
481480 String strategyOptions = strategyOptionsBuilder.substring(0, strategyOptionsBuilder.length() - 1) + "}";
482481
483482 Map<String, Object> ntsKeyspaceRow = ImmutableMap.<String, Object>builder()
484- .put("durable_writes", false)
485- .put("keyspace_name", name)
486- .put("strategy_class", "NetworkTopologyStrategy")
487- .put("strategy_options", strategyOptions)
488- .build();
483+ .put("durable_writes", false)
484+ .put("keyspace_name", name)
485+ .put("strategy_class", "NetworkTopologyStrategy")
486+ .put("strategy_options", strategyOptions)
487+ .build();
489488
490489 keyspaceRows.add(ntsKeyspaceRow);
491490 return this;
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +22 −21
@@ -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,30 +84,31 @@
8484
8585 protected Cluster.Builder createClusterBuilder() {
8686 Cluster.Builder builder = Cluster.builder()
87- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
88- // Scassandra does not support V3 yet, and V4 may cause the server to crash
89- .withProtocolVersion(ProtocolVersion.V2)
90- .withPoolingOptions(new PoolingOptions()
91- .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
92- .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
93- .setHeartbeatIntervalSeconds(0))
94- .withPort(scassandra.getBinaryPort());
87+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
88+ // Scassandra does not support V3 yet, and V4 may cause the server to crash
89+ .withProtocolVersion(ProtocolVersion.V2)
90+ .withPoolingOptions(new PoolingOptions()
91+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
92+ .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
93+ .setHeartbeatIntervalSeconds(0))
94+ .withPort(scassandra.getBinaryPort());
9595 return builder;
9696 }
9797
9898 /**
9999 * An overrideable method for building on to the Cluster.Builder used for this
100100 * class.
101+ *
101102 * @param builder
102103 * @return
103104 */
104105 protected Cluster.Builder configure(Cluster.Builder builder) {
105- return builder;
106+ return builder;
106107 }
107108
108109 protected Host retrieveSingleHost(Cluster cluster) {
109110 Host host = cluster.getMetadata().getHost(hostAddress);
110- if(host == null) {
111+ if (host == null) {
111112 fail("Unable to retrieve host");
112113 }
113114 return host;
@@ -125,7 +126,7 @@
125126
126127 protected Host host;
127128
128- @BeforeClass(groups = { "short", "long" }, dependsOnMethods = "startScassandra")
129+ @BeforeClass(groups = {"short", "long"}, dependsOnMethods = "startScassandra")
129130 public void initCluster() {
130131 Cluster.Builder builder = createClusterBuilder();
131132 cluster = builder.build();
@@ -133,13 +134,13 @@
133134 session = cluster.connect();
134135 }
135136
136- @AfterClass(groups = { "short", "long" })
137+ @AfterClass(groups = {"short", "long"})
137138 public void closeCluster() {
138139 if (cluster != null)
139140 cluster.close();
140141 }
141142
142- @AfterClass(groups = { "short", "long" }, dependsOnMethods = "closeCluster")
143+ @AfterClass(groups = {"short", "long"}, dependsOnMethods = "closeCluster")
143144 @Override
144145 public void stopScassandra() {
145146 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- TypeCodec.uuid().format(schemaVersion), TypeCodec.inet().format(peerAddress)));
104+ TypeCodec.uuid().format(schemaVersion), TypeCodec.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 +88 −88
@@ -15,25 +15,23 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.Collections;
20-import java.util.List;
21-
18+import com.datastax.driver.core.utils.Bytes;
19+import com.datastax.driver.core.utils.CassandraVersion;
2220 import com.google.common.collect.Lists;
2321 import com.google.common.util.concurrent.Futures;
2422 import com.google.common.util.concurrent.ListenableFuture;
2523 import org.mockito.ArgumentCaptor;
2624 import org.testng.annotations.*;
2725
28-import static org.mockito.Matchers.any;
29-import static org.mockito.Mockito.*;
30-
31-import com.datastax.driver.core.utils.Bytes;
32-import com.datastax.driver.core.utils.CassandraVersion;
26+import java.util.Collection;
27+import java.util.Collections;
28+import java.util.List;
3329
3430 import static com.datastax.driver.core.Assertions.assertThat;
3531 import static com.datastax.driver.core.Metadata.handleId;
3632 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
33+import static org.mockito.Matchers.any;
34+import static org.mockito.Mockito.*;
3735
3836 public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster {
3937
@@ -45,7 +43,9 @@
4543 private static final String ALTER_TABLE = "ALTER TABLE %s.table1 ADD j int";
4644 private static final String DROP_TABLE = "DROP TABLE %s.table1";
4745
48- /** The maximum time that the test will wait to check that listeners have been notified */
46+ /**
47+ * The maximum time that the test will wait to check that listeners have been notified
48+ */
4949 private static final int NOTIF_TIMEOUT_MS = 5000;
5050
5151 Cluster cluster1;
@@ -75,16 +75,16 @@
7575 @BeforeClass(groups = "short")
7676 public void setup() throws InterruptedException {
7777 Cluster.Builder builder = configure(Cluster.builder())
78- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
79- .withQueryOptions(nonDebouncingQueryOptions());
78+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
79+ .withQueryOptions(nonDebouncingQueryOptions());
8080 cluster1 = builder.build();
8181 cluster2 = builder.build();
8282 schemaDisabledCluster = spy(configure(Cluster.builder())
83- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
84- .withClusterName("schema-disabled")
85- .withQueryOptions(nonDebouncingQueryOptions()
86- .setMetadataEnabled(false)
87- ).build());
83+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
84+ .withClusterName("schema-disabled")
85+ .withQueryOptions(nonDebouncingQueryOptions()
86+ .setMetadataEnabled(false)
87+ ).build());
8888
8989 schemaDisabledSession = schemaDisabledCluster.connect();
9090
@@ -119,12 +119,12 @@
119119
120120 @DataProvider(name = "existingKeyspaceName")
121121 public static Object[][] existingKeyspaceName() {
122- return new Object[][]{ { "lowercase" }, { "\"CaseSensitive\"" } };
122+ return new Object[][]{{"lowercase"}, {"\"CaseSensitive\""}};
123123 }
124124
125125 @DataProvider(name = "newKeyspaceName")
126126 public static Object[][] newKeyspaceName() {
127- return new Object[][]{ { "lowercase2" }, { "\"CaseSensitive2\"" } };
127+ return new Object[][]{{"lowercase2"}, {"\"CaseSensitive2\""}};
128128 }
129129
130130 @BeforeMethod(groups = "short")
@@ -154,8 +154,8 @@
154154 ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class);
155155 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
156156 assertThat(added.getValue())
157- .isInKeyspace(handleId(keyspace))
158- .hasName("table1");
157+ .isInKeyspace(handleId(keyspace))
158+ .hasName("table1");
159159 }
160160
161161 for (Metadata m : metadatas)
@@ -172,8 +172,8 @@
172172 added = ArgumentCaptor.forClass(TableMetadata.class);
173173 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
174174 assertThat(added.getValue())
175- .isInKeyspace(handleId(keyspace))
176- .hasName("table1");
175+ .isInKeyspace(handleId(keyspace))
176+ .hasName("table1");
177177 }
178178 execute(ALTER_TABLE, keyspace);
179179 for (SchemaChangeListener listener : listeners) {
@@ -181,12 +181,12 @@
181181 ArgumentCaptor<TableMetadata> previous = ArgumentCaptor.forClass(TableMetadata.class);
182182 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(current.capture(), previous.capture());
183183 assertThat(previous.getValue())
184- .isEqualTo(added.getValue())
185- .hasNoColumn("j");
184+ .isEqualTo(added.getValue())
185+ .hasNoColumn("j");
186186 assertThat(current.getValue())
187- .isInKeyspace(handleId(keyspace))
188- .hasName("table1")
189- .hasColumn("j");
187+ .isInKeyspace(handleId(keyspace))
188+ .hasName("table1")
189+ .hasColumn("j");
190190 }
191191 for (Metadata m : metadatas)
192192 assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j");
@@ -199,8 +199,8 @@
199199 ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class);
200200 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
201201 assertThat(added.getValue())
202- .hasName("table1")
203- .isInKeyspace(handleId(keyspace));
202+ .hasName("table1")
203+ .isInKeyspace(handleId(keyspace));
204204 }
205205 execute(DROP_TABLE, keyspace);
206206 for (Metadata m : metadatas)
@@ -211,7 +211,7 @@
211211 assertThat(removed.getValue()).hasName("table1");
212212 }
213213 }
214-
214+
215215 @Test(groups = "short", dataProvider = "existingKeyspaceName")
216216 @CassandraVersion(major = 2.1)
217217 public void should_notify_of_udt_creation(String keyspace) {
@@ -220,13 +220,13 @@
220220 for (SchemaChangeListener listener : listeners) {
221221 ArgumentCaptor<UserType> added = ArgumentCaptor.forClass(UserType.class);
222222 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeAdded(added.capture());
223- assertThat((DataType)added.getValue())
224- .isUserType(handleId(keyspace), "type1");
223+ assertThat((DataType) added.getValue())
224+ .isUserType(handleId(keyspace), "type1");
225225 }
226226
227227 for (Metadata m : metadatas)
228- assertThat((DataType)m.getKeyspace(keyspace).getUserType("type1"))
229- .isNotNull();
228+ assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
229+ .isNotNull();
230230 }
231231
232232 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -245,7 +245,7 @@
245245
246246 for (Metadata m : metadatas)
247247 assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j"))
248- .isNotNull();
248+ .isNotNull();
249249 }
250250
251251 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -257,12 +257,12 @@
257257 for (SchemaChangeListener listener : listeners) {
258258 ArgumentCaptor<UserType> removed = ArgumentCaptor.forClass(UserType.class);
259259 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeRemoved(removed.capture());
260- assertThat((DataType)removed.getValue()).isUserType(handleId(keyspace), "type1");
260+ assertThat((DataType) removed.getValue()).isUserType(handleId(keyspace), "type1");
261261 }
262262
263263 for (Metadata m : metadatas)
264264 assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
265- .isNull();
265+ .isNull();
266266 }
267267
268268 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -274,13 +274,13 @@
274274 ArgumentCaptor<FunctionMetadata> added = ArgumentCaptor.forClass(FunctionMetadata.class);
275275 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionAdded(added.capture());
276276 assertThat(added.getValue())
277- .isInKeyspace(handleId(keyspace))
278- .hasSignature("\"ID\"(int)");
277+ .isInKeyspace(handleId(keyspace))
278+ .hasSignature("\"ID\"(int)");
279279 }
280280
281281 for (Metadata m : metadatas)
282282 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()))
283- .isNotNull();
283+ .isNotNull();
284284 }
285285
286286 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -291,10 +291,10 @@
291291
292292 for (Metadata m : metadatas)
293293 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")).getBody())
294- .isEqualTo("return user.getInt(\"ID\");");
294+ .isEqualTo("return user.getInt(\"ID\");");
295295
296296 session.execute(String.format("CREATE OR REPLACE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java "
297- + "AS 'return 1 + user.getInt(\"ID\");'", keyspace));
297+ + "AS 'return 1 + user.getInt(\"ID\");'", keyspace));
298298
299299 for (SchemaChangeListener listener : listeners) {
300300 ArgumentCaptor<FunctionMetadata> current = ArgumentCaptor.forClass(FunctionMetadata.class);
@@ -306,7 +306,7 @@
306306
307307 for (Metadata m : metadatas)
308308 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")).getBody())
309- .isEqualTo("return 1 + user.getInt(\"ID\");");
309+ .isEqualTo("return 1 + user.getInt(\"ID\");");
310310 }
311311
312312 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -320,45 +320,45 @@
320320 ArgumentCaptor<FunctionMetadata> removed = ArgumentCaptor.forClass(FunctionMetadata.class);
321321 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionRemoved(removed.capture());
322322 assertThat(removed.getValue())
323- .isInKeyspace(handleId(keyspace))
324- .hasSignature("\"ID\"(user)");
323+ .isInKeyspace(handleId(keyspace))
324+ .hasSignature("\"ID\"(user)");
325325 }
326326
327327 for (Metadata m : metadatas)
328328 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")))
329- .isNull();
329+ .isNull();
330330 }
331331
332332 @Test(groups = "short", dataProvider = "existingKeyspaceName")
333333 @CassandraVersion(major = 2.2)
334334 public void should_notify_of_aggregate_creation(String keyspace) {
335335 session.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
336- + " AS 'return s+v;'", keyspace));
336+ + " AS 'return s+v;'", keyspace));
337337 session.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0;", keyspace));
338338
339339 for (SchemaChangeListener listener : listeners) {
340340 ArgumentCaptor<AggregateMetadata> added = ArgumentCaptor.forClass(AggregateMetadata.class);
341341 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateAdded(added.capture());
342342 assertThat(added.getValue())
343- .isInKeyspace(handleId(keyspace))
344- .hasSignature("\"SUM\"(int)");
343+ .isInKeyspace(handleId(keyspace))
344+ .hasSignature("\"SUM\"(int)");
345345 }
346346
347347 for (Metadata m : metadatas)
348348 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()))
349- .isNotNull();
349+ .isNotNull();
350350 }
351351
352352 @Test(groups = "short", dataProvider = "existingKeyspaceName")
353353 @CassandraVersion(major = 2.2)
354354 public void should_notify_of_aggregate_update(String keyspace) {
355355 session.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
356- + " AS 'return s+v;'", keyspace));
356+ + " AS 'return s+v;'", keyspace));
357357 session.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
358358
359359 for (Metadata m : metadatas)
360360 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond())
361- .isEqualTo(0);
361+ .isEqualTo(0);
362362
363363 session.execute(String.format("CREATE OR REPLACE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 1", keyspace));
364364
@@ -372,14 +372,14 @@
372372
373373 for (Metadata m : metadatas)
374374 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond())
375- .isEqualTo(1);
375+ .isEqualTo(1);
376376 }
377377
378378 @Test(groups = "short", dataProvider = "existingKeyspaceName")
379379 @CassandraVersion(major = 2.2)
380380 public void should_notify_of_aggregate_drop(String keyspace) {
381381 session.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
382- + " AS 'return s+v;'", keyspace));
382+ + " AS 'return s+v;'", keyspace));
383383 session.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
384384 session.execute(String.format("DROP AGGREGATE %s.\"SUM\"", keyspace));
385385
@@ -387,13 +387,13 @@
387387 ArgumentCaptor<AggregateMetadata> removed = ArgumentCaptor.forClass(AggregateMetadata.class);
388388 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateRemoved(removed.capture());
389389 assertThat(removed.getValue())
390- .isInKeyspace(handleId(keyspace))
391- .hasSignature("\"SUM\"(int)");
390+ .isInKeyspace(handleId(keyspace))
391+ .hasSignature("\"SUM\"(int)");
392392 }
393-
393+
394394 for (Metadata m : metadatas)
395395 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()))
396- .isNull();
396+ .isNull();
397397 }
398398
399399 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -461,11 +461,11 @@
461461 ArgumentCaptor<KeyspaceMetadata> previous = ArgumentCaptor.forClass(KeyspaceMetadata.class);
462462 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(current.capture(), previous.capture());
463463 assertThat(previous.getValue())
464- .isEqualTo(added.getValue())
465- .isDurableWrites();
464+ .isEqualTo(added.getValue())
465+ .isDurableWrites();
466466 assertThat(current.getValue())
467- .hasName(handleId(keyspace))
468- .isNotDurableWrites();
467+ .hasName(handleId(keyspace))
468+ .isNotDurableWrites();
469469 }
470470 for (Metadata m : metadatas)
471471 assertThat(m.getKeyspace(keyspace)).isNotDurableWrites();
@@ -482,13 +482,13 @@
482482 ArgumentCaptor<TableMetadata> table = ArgumentCaptor.forClass(TableMetadata.class);
483483 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(table.capture());
484484 assertThat(table.getValue())
485- .hasName("table1")
486- .isInKeyspace(handleId(keyspace));
485+ .hasName("table1")
486+ .isInKeyspace(handleId(keyspace));
487487
488488 ArgumentCaptor<KeyspaceMetadata> ks = ArgumentCaptor.forClass(KeyspaceMetadata.class);
489489 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(ks.capture());
490490 assertThat(ks.getValue())
491- .hasName(handleId(keyspace));
491+ .hasName(handleId(keyspace));
492492 }
493493 for (Metadata m : metadatas) {
494494 assertThat(m.getKeyspace(keyspace)).isNull();
@@ -507,10 +507,10 @@
507507 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
508508 public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() {
509509 Cluster cluster = configure(Cluster.builder())
510- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
511- .withQueryOptions(nonDebouncingQueryOptions()
512- .setMetadataEnabled(false)
513- ).build();
510+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
511+ .withQueryOptions(nonDebouncingQueryOptions()
512+ .setMetadataEnabled(false)
513+ ).build();
514514
515515 try {
516516 cluster.init();
@@ -531,10 +531,10 @@
531531 @Test(groups = "short", expectedExceptions = IllegalStateException.class)
532532 public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() {
533533 Cluster cluster = configure(Cluster.builder())
534- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
535- .withQueryOptions(nonDebouncingQueryOptions()
536- .setMetadataEnabled(false)
537- ).build();
534+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
535+ .withQueryOptions(nonDebouncingQueryOptions()
536+ .setMetadataEnabled(false)
537+ ).build();
538538
539539 try {
540540 cluster.init();
@@ -605,20 +605,20 @@
605605 @AfterMethod(groups = "short")
606606 public void cleanup() throws InterruptedException {
607607 ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList(
608- session1.executeAsync("DROP TABLE lowercase.table1"),
609- session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
610- session1.executeAsync("DROP TYPE lowercase.type1"),
611- session1.executeAsync("DROP TYPE \"CaseSensitive\".type1"),
612- session1.executeAsync("DROP FUNCTION lowercase.\"ID\""),
613- session1.executeAsync("DROP FUNCTION \"CaseSensitive\".\"ID\""),
614- session1.executeAsync("DROP FUNCTION lowercase.\"PLUS\""),
615- session1.executeAsync("DROP FUNCTION \"CaseSensitive\".\"PLUS\""),
616- session1.executeAsync("DROP AGGREGATE lowercase.\"SUM\""),
617- session1.executeAsync("DROP AGGREGATE \"CaseSensitive\".\"SUM\""),
618- session1.executeAsync("DROP MATERIALIZED VIEW lowercase.mv1"),
619- session1.executeAsync("DROP MATERIALIZED VIEW \"CaseSensitive\".mv1"),
620- session1.executeAsync("DROP KEYSPACE lowercase2"),
621- session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
608+ session1.executeAsync("DROP TABLE lowercase.table1"),
609+ session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
610+ session1.executeAsync("DROP TYPE lowercase.type1"),
611+ session1.executeAsync("DROP TYPE \"CaseSensitive\".type1"),
612+ session1.executeAsync("DROP FUNCTION lowercase.\"ID\""),
613+ session1.executeAsync("DROP FUNCTION \"CaseSensitive\".\"ID\""),
614+ session1.executeAsync("DROP FUNCTION lowercase.\"PLUS\""),
615+ session1.executeAsync("DROP FUNCTION \"CaseSensitive\".\"PLUS\""),
616+ session1.executeAsync("DROP AGGREGATE lowercase.\"SUM\""),
617+ session1.executeAsync("DROP AGGREGATE \"CaseSensitive\".\"SUM\""),
618+ session1.executeAsync("DROP MATERIALIZED VIEW lowercase.mv1"),
619+ session1.executeAsync("DROP MATERIALIZED VIEW \"CaseSensitive\".mv1"),
620+ session1.executeAsync("DROP KEYSPACE lowercase2"),
621+ session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
622622 ));
623623 Futures.getUnchecked(f);
624624 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +27 −28
@@ -15,9 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-import java.util.Collections;
20-
2118 import org.mockito.ArgumentCaptor;
2219 import org.testng.SkipException;
2320 import org.testng.annotations.AfterClass;
@@ -25,14 +22,16 @@
2522 import org.testng.annotations.BeforeClass;
2623 import org.testng.annotations.Test;
2724
28-import static com.google.common.collect.Lists.newArrayList;
29-import static org.mockito.ArgumentCaptor.forClass;
30-import static org.mockito.Mockito.*;
25+import java.util.Collection;
26+import java.util.Collections;
3127
3228 import static com.datastax.driver.core.Assertions.assertThat;
3329 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
3430 import static com.datastax.driver.core.SchemaElement.TABLE;
3531 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
32+import static com.google.common.collect.Lists.newArrayList;
33+import static org.mockito.ArgumentCaptor.forClass;
34+import static org.mockito.Mockito.*;
3635
3736 public class SchemaRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
3837
@@ -64,9 +63,9 @@
6463 queryOptions.setMaxPendingRefreshSchemaRequests(5);
6564 // Create a separate cluster that will receive the schema events on its control connection.
6665 cluster2 = this.configure(Cluster.builder())
67- .addContactPointsWithPorts(newArrayList(hostAddress))
68- .withQueryOptions(queryOptions)
69- .build();
66+ .addContactPointsWithPorts(newArrayList(hostAddress))
67+ .withQueryOptions(queryOptions)
68+ .build();
7069 session2 = cluster2.connect();
7170
7271 // Create a spy of the Cluster's control connection and replace it with the spy.
@@ -91,7 +90,7 @@
9190 public void teardown() {
9291 cluster2.close();
9392 // drop all keyspaces
94- for(String keyspace : keyspaces) {
93+ for (String keyspace : keyspaces) {
9594 session.execute("DROP KEYSPACE " + keyspace);
9695 }
9796 }
@@ -183,7 +182,7 @@
183182 reset(listener);
184183
185184 int tableCount = 3;
186- for(int i =0 ; i < tableCount; i++) {
185+ for (int i = 0; i < tableCount; i++) {
187186 session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + "tbl" + i));
188187 }
189188
@@ -196,7 +195,7 @@
196195 KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
197196 assertThat(ksm).isNotNull();
198197 // metadata is present for each table.
199- for(int i = 0; i < tableCount; i++) {
198+ for (int i = 0; i < tableCount; i++) {
200199 String table = "tbl" + i;
201200 // Should have never been a refreshSchema on the table.
202201 verify(controlConnection, never()).refreshSchema(TABLE, keyspace, table, null);
@@ -237,16 +236,16 @@
237236 ArgumentCaptor<TableMetadata> captor = forClass(TableMetadata.class);
238237 verify(listener, timeout(DEBOUNCE_TIME * 2).times(1)).onTableChanged(captor.capture(), original.capture());
239238 assertThat(captor.getValue())
240- .hasName(table)
241- .isInKeyspace(keyspace)
242- .hasColumn(columnName)
243- .hasComment(comment);
239+ .hasName(table)
240+ .isInKeyspace(keyspace)
241+ .hasColumn(columnName)
242+ .hasComment(comment);
244243
245244 assertThat(original.getValue())
246- .hasName(table)
247- .isInKeyspace(keyspace)
248- .hasNoColumn(columnName)
249- .doesNotHaveComment(comment);
245+ .hasName(table)
246+ .isInKeyspace(keyspace)
247+ .hasNoColumn(columnName)
248+ .doesNotHaveComment(comment);
250249
251250 // Verify a refresh of the table was executed, but only once.
252251 verify(controlConnection, times(1)).refreshSchema(TABLE, keyspace, table, Collections.<String>emptyList());
@@ -255,10 +254,10 @@
255254 assertThat(ksm).isNotNull();
256255 TableMetadata tm = ksm.getTable(table);
257256 assertThat(tm)
258- .hasName(table)
259- .isInKeyspace(keyspace)
260- .hasColumn(columnName)
261- .hasComment(comment);
257+ .hasName(table)
258+ .isInKeyspace(keyspace)
259+ .hasColumn(columnName)
260+ .hasComment(comment);
262261 }
263262
264263 /**
@@ -274,7 +273,7 @@
274273 @Test(groups = "short")
275274 public void should_debounce_and_coalesce_multiple_keyspace_creates_into_refresh_entire_schema() throws Exception {
276275 String prefix = "sdacmkc";
277- for(int i = 0; i < 3; i++) {
276+ for (int i = 0; i < 3; i++) {
278277 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
279278 keyspaces.add(prefix + i);
280279 }
@@ -283,7 +282,7 @@
283282 // Verify a complete schema refresh was executed, but only once.
284283 verify(controlConnection, times(1)).refreshSchema(null, null, null, null);
285284
286- for(int i = 0; i < 3; i++) {
285+ for (int i = 0; i < 3; i++) {
287286 KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
288287 assertThat(ksm).isNotNull().hasName(prefix + i);
289288 }
@@ -301,7 +300,7 @@
301300 @Test(groups = "short")
302301 public void should_refresh_when_max_pending_requests_reached() throws Exception {
303302 String prefix = "srwmprr";
304- for(int i = 0; i < 5; i++) {
303+ for (int i = 0; i < 5; i++) {
305304 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
306305 keyspaces.add(prefix + i);
307306 }
@@ -311,7 +310,7 @@
311310 // Verify a complete schema refresh was executed, but only once.
312311 verify(controlConnection, times(1)).refreshSchema(null, null, null, null);
313312
314- for(int i = 0; i < 5; i++) {
313+ for (int i = 0; i < 5; i++) {
315314 KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
316315 assertThat(ksm).isNotNull().hasName(prefix + i);
317316 }
modified driver-core/src/test/java/com/datastax/driver/core/SessionAssert.java +1 −1
@@ -23,7 +23,7 @@
2323
2424 protected SessionAssert(Session actual) {
2525 // We are cheating a bit by casting, but this is the only implementation anyway
26- super((SessionManager)actual, SessionAssert.class);
26+ super((SessionManager) actual, SessionAssert.class);
2727 }
2828
2929 public SessionAssert hasPoolFor(int hostNumber) {
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +12 −15
@@ -15,30 +15,27 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.InvalidQueryException;
19+import com.datastax.driver.core.utils.SocketChannelMonitor;
20+import com.google.common.collect.Lists;
21+import org.testng.annotations.Test;
22+
1823 import java.net.InetSocketAddress;
1924 import java.util.Collections;
2025 import java.util.List;
2126 import java.util.concurrent.TimeUnit;
2227
23-import static java.util.concurrent.TimeUnit.MINUTES;
24-
25-import com.google.common.collect.Lists;
26-import org.testng.annotations.Test;
27-
28-import static org.assertj.core.api.Assertions.fail;
29-
30-import com.datastax.driver.core.exceptions.InvalidQueryException;
31-import com.datastax.driver.core.utils.SocketChannelMonitor;
32-
3328 import static com.datastax.driver.core.Assertions.assertThat;
3429 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
30+import static java.util.concurrent.TimeUnit.MINUTES;
31+import static org.assertj.core.api.Assertions.fail;
3532
3633 public class SessionLeakTest {
3734
3835 Cluster cluster;
3936 List<InetSocketAddress> nodes = Lists.newArrayList(
40- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
41- new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
37+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
38+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
4239 SocketChannelMonitor channelMonitor;
4340
4441 @Test(groups = "short")
@@ -116,9 +113,9 @@
116113 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
117114 try {
118115 cluster = Cluster.builder()
119- .addContactPointsWithPorts(Collections.singletonList(
120- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
121- .withNettyOptions(channelMonitor.nettyOptions()).build();
116+ .addContactPointsWithPorts(Collections.singletonList(
117+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
118+ .withNettyOptions(channelMonitor.nettyOptions()).build();
122119
123120 cluster.init();
124121
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +2 −2
@@ -212,10 +212,10 @@
212212
213213 // Immediately wait for CloseFutures, this should be very quick since all this work does is call closeAsync.
214214 List<ListenableFuture<Void>> futures = Lists.newArrayListWithCapacity(iterations);
215- for(ListenableFuture<CloseFuture> closeFuture : closeFutures) {
215+ for (ListenableFuture<CloseFuture> closeFuture : closeFutures) {
216216 try {
217217 futures.add(closeFuture.get());
218- } catch(Exception e) {
218+ } catch (Exception e) {
219219 logger.error("Got interrupted exception while waiting on closeFuture.", e);
220220 }
221221 }
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +13 −17
@@ -15,23 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-import java.util.concurrent.CountDownLatch;
20-import java.util.concurrent.ExecutorService;
21-import java.util.concurrent.Executors;
22-import java.util.concurrent.TimeUnit;
23-
2418 import com.datastax.driver.core.utils.CassandraVersion;
25-
2619 import org.slf4j.Logger;
2720 import org.slf4j.LoggerFactory;
2821 import org.testng.annotations.Test;
2922
30-import static org.testng.Assert.assertEquals;
31-import static org.testng.Assert.assertTrue;
32-import static org.testng.Assert.fail;
23+import java.util.*;
24+import java.util.concurrent.CountDownLatch;
25+import java.util.concurrent.ExecutorService;
26+import java.util.concurrent.Executors;
27+import java.util.concurrent.TimeUnit;
3328
3429 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
30+import static org.testng.Assert.*;
3531
3632 /**
3733 * Simple test of the Sessions methods against a one node cluster.
@@ -48,9 +44,9 @@
4844 @Override
4945 protected Collection<String> getTableDefinitions() {
5046 return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE1),
51- String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE2),
52- String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE3),
53- String.format("CREATE TABLE %s (k text PRIMARY KEY, c counter)", COUNTER_TABLE));
47+ String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE2),
48+ String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE3),
49+ String.format("CREATE TABLE %s (k text PRIMARY KEY, c counter)", COUNTER_TABLE));
5450 }
5551
5652 @Test(groups = "short")
@@ -132,7 +128,7 @@
132128 * @expected_result session established and queries made successfully using it.
133129 */
134130 @Test(groups = "short")
135- @CassandraVersion(major=2.0)
131+ @CassandraVersion(major = 2.0)
136132 public void session_should_function_with_lz4_compression() throws Exception {
137133 compressionTest(ProtocolOptions.Compression.LZ4);
138134 }
@@ -172,9 +168,9 @@
172168 // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster
173169 // (note the use of newSession below)
174170 final Cluster cluster = Cluster.builder()
175- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
176- .withNettyOptions(nonQuietClusterCloseOptions)
177- .build();
171+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
172+ .withNettyOptions(nonQuietClusterCloseOptions)
173+ .build();
178174 final Session session = cluster.newSession();
179175
180176 // 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,27 +15,27 @@
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
38- @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class })
38+ @Test(groups = "unit", expectedExceptions = {IndexOutOfBoundsException.class})
3939 public void should_throw_IOOBE_if_getObject_called_with_wrong_index() {
4040 new SimpleStatement("doesn't matter", new Object()).getObject(1);
4141 }
@@ -50,10 +50,10 @@
5050 @Test(groups = "unit")
5151 public void should_return_number_of_values() {
5252 assertThat(
53- new SimpleStatement("doesn't matter").valuesCount()
53+ new SimpleStatement("doesn't matter").valuesCount()
5454 ).isEqualTo(0);
5555 assertThat(
56- new SimpleStatement("doesn't matter", 1, 2).valuesCount()
56+ new SimpleStatement("doesn't matter", 1, 2).valuesCount()
5757 ).isEqualTo(2);
5858 }
5959
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStrategyTest.java +72 −72
@@ -15,15 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.ImmutableList;
19+import com.google.common.collect.ImmutableMap;
20+import org.testng.annotations.Test;
21+
1822 import java.net.InetSocketAddress;
1923 import java.util.List;
2024 import java.util.Map;
2125 import java.util.Set;
2226
23-import com.google.common.collect.ImmutableList;
24-import com.google.common.collect.ImmutableMap;
25-import org.testng.annotations.Test;
26-
2727 public class SimpleStrategyTest extends AbstractReplicationStrategyTest {
2828
2929 private static ReplicationStrategy simpleStrategy(int replicationFactor) {
@@ -73,46 +73,46 @@
7373 private static final ReplicationStrategy exampleStrategyTooManyReplicas = simpleStrategy(8);
7474
7575 private static final List<Token> exampleRing = ImmutableList.<Token>builder()
76- .add(TOKEN01)
77- .add(TOKEN02)
78- .add(TOKEN03)
79- .add(TOKEN04)
80- .add(TOKEN05)
81- .add(TOKEN06)
82- .add(TOKEN07)
83- .add(TOKEN08)
84- .add(TOKEN09)
85- .add(TOKEN10)
86- .add(TOKEN11)
87- .add(TOKEN12)
88- .add(TOKEN13)
89- .add(TOKEN14)
90- .add(TOKEN15)
91- .add(TOKEN16)
92- .add(TOKEN17)
93- .add(TOKEN18)
94- .build();
76+ .add(TOKEN01)
77+ .add(TOKEN02)
78+ .add(TOKEN03)
79+ .add(TOKEN04)
80+ .add(TOKEN05)
81+ .add(TOKEN06)
82+ .add(TOKEN07)
83+ .add(TOKEN08)
84+ .add(TOKEN09)
85+ .add(TOKEN10)
86+ .add(TOKEN11)
87+ .add(TOKEN12)
88+ .add(TOKEN13)
89+ .add(TOKEN14)
90+ .add(TOKEN15)
91+ .add(TOKEN16)
92+ .add(TOKEN17)
93+ .add(TOKEN18)
94+ .build();
9595
9696 private static final Map<Token, Host> exampleTokenToPrimary = ImmutableMap.<Token, Host>builder()
97- .put(TOKEN01, host(IP1))
98- .put(TOKEN02, host(IP1))
99- .put(TOKEN03, host(IP5))
100- .put(TOKEN04, host(IP3))
101- .put(TOKEN05, host(IP1))
102- .put(TOKEN06, host(IP5))
103- .put(TOKEN07, host(IP2))
104- .put(TOKEN08, host(IP6))
105- .put(TOKEN09, host(IP3))
106- .put(TOKEN10, host(IP4))
107- .put(TOKEN11, host(IP5))
108- .put(TOKEN12, host(IP4))
109- .put(TOKEN13, host(IP4))
110- .put(TOKEN14, host(IP2))
111- .put(TOKEN15, host(IP6))
112- .put(TOKEN16, host(IP3))
113- .put(TOKEN17, host(IP2))
114- .put(TOKEN18, host(IP6))
115- .build();
97+ .put(TOKEN01, host(IP1))
98+ .put(TOKEN02, host(IP1))
99+ .put(TOKEN03, host(IP5))
100+ .put(TOKEN04, host(IP3))
101+ .put(TOKEN05, host(IP1))
102+ .put(TOKEN06, host(IP5))
103+ .put(TOKEN07, host(IP2))
104+ .put(TOKEN08, host(IP6))
105+ .put(TOKEN09, host(IP3))
106+ .put(TOKEN10, host(IP4))
107+ .put(TOKEN11, host(IP5))
108+ .put(TOKEN12, host(IP4))
109+ .put(TOKEN13, host(IP4))
110+ .put(TOKEN14, host(IP2))
111+ .put(TOKEN15, host(IP6))
112+ .put(TOKEN16, host(IP3))
113+ .put(TOKEN17, host(IP2))
114+ .put(TOKEN18, host(IP6))
115+ .build();
116116
117117 private static final String keyspace = "excalibur";
118118
@@ -125,18 +125,18 @@
125125 @Test(groups = "unit")
126126 public void simpleStrategySimpleTopologyTest() {
127127 List<Token> ring = ImmutableList.<Token>builder()
128- .add(TOKEN01)
129- .add(TOKEN06)
130- .add(TOKEN14)
131- .add(TOKEN19)
132- .build();
128+ .add(TOKEN01)
129+ .add(TOKEN06)
130+ .add(TOKEN14)
131+ .add(TOKEN19)
132+ .build();
133133
134134 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
135- .put(TOKEN01, host(IP1))
136- .put(TOKEN06, host(IP2))
137- .put(TOKEN14, host(IP1))
138- .put(TOKEN19, host(IP2))
139- .build();
135+ .put(TOKEN01, host(IP1))
136+ .put(TOKEN06, host(IP2))
137+ .put(TOKEN14, host(IP1))
138+ .put(TOKEN19, host(IP2))
139+ .build();
140140
141141 ReplicationStrategy strategy = simpleStrategy(2);
142142
@@ -151,18 +151,18 @@
151151 @Test(groups = "unit")
152152 public void simpleStrategyConsecutiveRingSectionsTest() {
153153 List<Token> ring = ImmutableList.<Token>builder()
154- .add(TOKEN01)
155- .add(TOKEN06)
156- .add(TOKEN14)
157- .add(TOKEN19)
158- .build();
154+ .add(TOKEN01)
155+ .add(TOKEN06)
156+ .add(TOKEN14)
157+ .add(TOKEN19)
158+ .build();
159159
160160 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
161- .put(TOKEN01, host(IP1))
162- .put(TOKEN06, host(IP1))
163- .put(TOKEN14, host(IP2))
164- .put(TOKEN19, host(IP2))
165- .build();
161+ .put(TOKEN01, host(IP1))
162+ .put(TOKEN06, host(IP1))
163+ .put(TOKEN14, host(IP2))
164+ .put(TOKEN19, host(IP2))
165+ .build();
166166
167167 ReplicationStrategy strategy = simpleStrategy(2);
168168
@@ -177,18 +177,18 @@
177177 @Test(groups = "unit")
178178 public void simpleStrategyUnbalancedRingTest() {
179179 List<Token> ring = ImmutableList.<Token>builder()
180- .add(TOKEN01)
181- .add(TOKEN06)
182- .add(TOKEN14)
183- .add(TOKEN19)
184- .build();
180+ .add(TOKEN01)
181+ .add(TOKEN06)
182+ .add(TOKEN14)
183+ .add(TOKEN19)
184+ .build();
185185
186186 Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
187- .put(TOKEN01, host(IP1))
188- .put(TOKEN06, host(IP1))
189- .put(TOKEN14, host(IP2))
190- .put(TOKEN19, host(IP1))
191- .build();
187+ .put(TOKEN01, host(IP1))
188+ .put(TOKEN06, host(IP1))
189+ .put(TOKEN14, host(IP2))
190+ .put(TOKEN19, host(IP1))
191+ .build();
192192
193193 ReplicationStrategy strategy = simpleStrategy(2);
194194
modified driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +6 −7
@@ -15,6 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.CassandraVersion;
19+import org.testng.annotations.Test;
20+import org.testng.collections.Lists;
21+
1822 import java.net.InetSocketAddress;
1923 import java.util.Collection;
2024 import java.util.concurrent.Executors;
@@ -22,14 +26,9 @@
2226 import java.util.concurrent.TimeUnit;
2327 import java.util.concurrent.atomic.AtomicBoolean;
2428
25-import org.testng.annotations.Test;
26-import org.testng.collections.Lists;
27-
2829 import static org.testng.Assert.fail;
2930
30-import com.datastax.driver.core.utils.CassandraVersion;
31-
32-@CassandraVersion(major=2.1)
31+@CassandraVersion(major = 2.1)
3332 public class SingleConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
3433 @Override
3534 protected Collection<String> getTableDefinitions() {
@@ -41,7 +40,7 @@
4140 // Throttle to a very low value. Even a single thread can generate a higher throughput.
4241 final int maxRequests = 10;
4342 cluster.getConfiguration().getPoolingOptions()
44- .setMaxRequestsPerConnection(HostDistance.LOCAL, maxRequests);
43+ .setMaxRequestsPerConnection(HostDistance.LOCAL, maxRequests);
4544
4645 // Track in flight requests in a dedicated thread every second
4746 final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false);
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +17 −18
@@ -15,12 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Set;
20-
18+import com.datastax.driver.core.utils.Bytes;
2119 import org.testng.annotations.Test;
2220
23-import com.datastax.driver.core.utils.Bytes;
21+import java.nio.ByteBuffer;
22+import java.util.Set;
2423
2524 import static com.datastax.driver.core.Assertions.assertThat;
2625
@@ -35,18 +34,18 @@
3534
3635 try {
3736 ccm = CCMBridge.builder("test")
38- // force the initial token to a non-min value to validate that the single range will always be ]minToken, minToken]
39- .withCassandraConfiguration("initial_token", "1")
40- .build();
37+ // force the initial token to a non-min value to validate that the single range will always be ]minToken, minToken]
38+ .withCassandraConfiguration("initial_token", "1")
39+ .build();
4140
4241 cluster = Cluster.builder()
43- .addContactPoint(CCMBridge.ipOfNode(1))
44- .withQueryOptions(new QueryOptions()
45- .setRefreshNodeIntervalMillis(0)
46- .setRefreshNodeListIntervalMillis(0)
47- .setRefreshSchemaIntervalMillis(0)
48- )
49- .build();
42+ .addContactPoint(CCMBridge.ipOfNode(1))
43+ .withQueryOptions(new QueryOptions()
44+ .setRefreshNodeIntervalMillis(0)
45+ .setRefreshNodeListIntervalMillis(0)
46+ .setRefreshSchemaIntervalMillis(0)
47+ )
48+ .build();
5049
5150 Session session = cluster.connect();
5251 session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
@@ -57,10 +56,10 @@
5756 assertThat(tokenRanges).hasSize(1);
5857 TokenRange tokenRange = tokenRanges.iterator().next();
5958 assertThat(tokenRange)
60- .startsWith(Token.M3PToken.FACTORY.minToken())
61- .endsWith(Token.M3PToken.FACTORY.minToken())
62- .isNotEmpty()
63- .isNotWrappedAround();
59+ .startsWith(Token.M3PToken.FACTORY.minToken())
60+ .endsWith(Token.M3PToken.FACTORY.minToken())
61+ .isNotEmpty()
62+ .isNotWrappedAround();
6463
6564 Set<Host> hostsForRange = metadata.getReplicas("test", tokenRange);
6665 Host host1 = TestUtils.findHost(cluster, 1);
modified driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java +5 −6
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.policies.LoadBalancingPolicy;
19+import com.google.common.primitives.UnsignedBytes;
20+
1821 import java.util.Collection;
1922 import java.util.Comparator;
2023 import java.util.Iterator;
2124 import java.util.SortedSet;
2225 import java.util.concurrent.ConcurrentSkipListSet;
2326
24-import com.google.common.primitives.UnsignedBytes;
25-
26-import com.datastax.driver.core.policies.LoadBalancingPolicy;
27-
2827 /**
2928 * A load balancing policy that sorts hosts on the last byte of the address,
3029 * so that the query plan is always [host1, host2, host3].
@@ -37,8 +36,8 @@
3736 byte[] address1 = host1.getAddress().getAddress();
3837 byte[] address2 = host2.getAddress().getAddress();
3938 return UnsignedBytes.compare(
40- address1[address1.length - 1],
41- address2[address2.length - 1]);
39+ address1[address1.length - 1],
40+ address2[address2.length - 1]);
4241 }
4342 });
4443
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +8 −9
@@ -15,18 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
19-
18+import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
19+import com.datastax.driver.core.utils.CassandraVersion;
2020 import com.google.common.collect.Lists;
2121 import org.mockito.Mockito;
2222 import org.testng.annotations.Test;
2323
24+import java.util.Collection;
25+
2426 import static org.assertj.core.api.Assertions.assertThat;
2527 import static org.mockito.Mockito.times;
2628
27-import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
28-import com.datastax.driver.core.utils.CassandraVersion;
29-
3029 /**
3130 * Test that needs a real CCM cluster (as opposed to SCassandra for other specex tests), because
3231 * it uses a protocol v3 feature.
@@ -44,10 +43,10 @@
4443 protected Cluster.Builder configure(Cluster.Builder builder) {
4544 timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE);
4645 return builder
47- .withTimestampGenerator(timestampGenerator)
48- .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
49- // Set an artificially low timeout to force speculative execution
50- .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2));
46+ .withTimestampGenerator(timestampGenerator)
47+ .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
48+ // Set an artificially low timeout to force speculative execution
49+ .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2));
5150 }
5251
5352 /**
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +59 −61
@@ -15,9 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.Map;
20-
18+import com.datastax.driver.core.exceptions.DriverException;
19+import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
20+import com.datastax.driver.core.policies.RetryPolicy;
21+import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2122 import com.google.common.collect.ImmutableList;
2223 import com.google.common.collect.ImmutableMap;
2324 import org.scassandra.http.client.PrimingRequest;
@@ -25,17 +26,12 @@
2526 import org.testng.annotations.BeforeMethod;
2627 import org.testng.annotations.Test;
2728
28-import static org.mockito.Mockito.mock;
29-import static org.mockito.Mockito.times;
30-import static org.mockito.Mockito.verify;
31-
32-import com.datastax.driver.core.exceptions.DriverException;
33-import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
34-import com.datastax.driver.core.policies.RetryPolicy;
35-import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
29+import java.util.List;
30+import java.util.Map;
3631
3732 import static com.datastax.driver.core.Assertions.assertThat;
3833 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
34+import static org.mockito.Mockito.*;
3935
4036 public class SpeculativeExecutionTest {
4137 ScassandraCluster scassandras;
@@ -55,14 +51,14 @@
5551
5652 loadBalancingPolicy = new SortingLoadBalancingPolicy();
5753 cluster = Cluster.builder()
58- .addContactPoint(scassandras.address(2))
59- .withProtocolVersion(ProtocolVersion.V2) // Scassandra does not support V3 nor V4 yet
60- .withLoadBalancingPolicy(loadBalancingPolicy)
61- .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
62- .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
63- .withRetryPolicy(new CustomRetryPolicy())
64- .withNettyOptions(nonQuietClusterCloseOptions)
65- .build();
54+ .addContactPoint(scassandras.address(2))
55+ .withProtocolVersion(ProtocolVersion.V2) // Scassandra does not support V3 nor V4 yet
56+ .withLoadBalancingPolicy(loadBalancingPolicy)
57+ .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
58+ .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
59+ .withRetryPolicy(new CustomRetryPolicy())
60+ .withNettyOptions(nonQuietClusterCloseOptions)
61+ .build();
6662
6763 session = cluster.connect();
6864
@@ -84,9 +80,9 @@
8480 @Test(groups = "short")
8581 public void should_not_start_speculative_execution_if_first_execution_completes_successfully() {
8682 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
87- .withQuery("mock query")
88- .withRows(row("result", "result1"))
89- .build()
83+ .withQuery("mock query")
84+ .withRows(row("result", "result1"))
85+ .build()
9086 );
9187
9288 long execStartCount = errors.getSpeculativeExecutions().getCount();
@@ -103,17 +99,17 @@
10399 public void should_not_start_speculative_execution_if_first_execution_retries_but_is_still_fast_enough() {
104100 // will retry once on this node:
105101 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
106- .withQuery("mock query")
107- .withConsistency(PrimingRequest.Consistency.TWO)
108- .withResult(PrimingRequest.Result.read_request_timeout)
109- .build()
102+ .withQuery("mock query")
103+ .withConsistency(PrimingRequest.Consistency.TWO)
104+ .withResult(PrimingRequest.Result.read_request_timeout)
105+ .build()
110106 );
111107
112108 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
113- .withQuery("mock query")
114- .withConsistency(PrimingRequest.Consistency.ONE)
115- .withRows(row("result", "result1"))
116- .build()
109+ .withQuery("mock query")
110+ .withConsistency(PrimingRequest.Consistency.ONE)
111+ .withRows(row("result", "result1"))
112+ .build()
117113 );
118114
119115 long execStartCount = errors.getSpeculativeExecutions().getCount();
@@ -133,16 +129,16 @@
133129 @Test(groups = "short")
134130 public void should_start_speculative_execution_if_first_execution_takes_too_long() {
135131 scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder()
136- .withQuery("mock query")
137- .withFixedDelay(400)
138- .withRows(row("result", "result1"))
139- .build()
132+ .withQuery("mock query")
133+ .withFixedDelay(400)
134+ .withRows(row("result", "result1"))
135+ .build()
140136 );
141137
142138 scassandras.node(2).primingClient().prime(PrimingRequest.queryBuilder()
143- .withQuery("mock query")
144- .withRows(row("result", "result2"))
145- .build()
139+ .withQuery("mock query")
140+ .withRows(row("result", "result2"))
141+ .build()
146142 );
147143 long execStartCount = errors.getSpeculativeExecutions().getCount();
148144
@@ -160,28 +156,28 @@
160156 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1000);
161157
162158 scassandras.node(1).primingClient()
163- // execution1 starts with host1, which will time out at t=1000
164- .prime(PrimingRequest.queryBuilder()
165- .withQuery("mock query")
166- .withFixedDelay(2000)
167- .withRows(row("result", "result1"))
168- .build());
169- // at t=1000, execution1 moves to host3, which eventually succeeds at t=1500
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
170166 scassandras.node(3).primingClient()
171- .prime(PrimingRequest.queryBuilder()
172- .withQuery("mock query")
173- .withFixedDelay(500)
174- .withRows(row("result", "result3"))
175- .build());
176- // meanwhile, execution2 starts at t=200, using host2 which times out at t=1200
177- // at that time, the query plan is empty so execution2 fails
178- // The goal of this test is to check that execution2 does not fail the query, since execution1 is still running
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
179175 scassandras.node(2).primingClient()
180- .prime(PrimingRequest.queryBuilder()
181- .withQuery("mock query")
182- .withFixedDelay(2000)
183- .withRows(row("result", "result2"))
184- .build());
176+ .prime(PrimingRequest.queryBuilder()
177+ .withQuery("mock query")
178+ .withFixedDelay(2000)
179+ .withRows(row("result", "result2"))
180+ .build());
185181 long execStartCount = errors.getSpeculativeExecutions().getCount();
186182
187183 ResultSet rs = session.execute("mock query");
@@ -201,13 +197,13 @@
201197 * @jira_ticket JAVA-796
202198 * @since 2.0.11, 2.1.7, 2.2.1
203199 */
204- @Test(groups="short")
200+ @Test(groups = "short")
205201 public void should_init_and_close_policy_on_cluster() {
206202 SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class);
207203
208204 Cluster cluster = Cluster.builder()
209205 .addContactPoint(CCMBridge.ipOfNode(2))
210- // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
206+ // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
211207 .withProtocolVersion(ProtocolVersion.V2)
212208 .withSpeculativeExecutionPolicy(mockPolicy)
213209 .build();
@@ -252,10 +248,12 @@
252248 }
253249
254250 @Override
255- public void init(Cluster cluster) {}
251+ public void init(Cluster cluster) {
252+ }
256253
257254 @Override
258- public void close() {}
255+ public void close() {
256+ }
259257 }
260258
261259 private static List<Map<String, ?>> row(String key, String value) {
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +12 −12
@@ -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
@@ -117,11 +115,13 @@
117115 public void onRemove(Host host) {
118116 reportActualEvent(REMOVE);
119117 }
120-
118+
121119 @Override
122- public void onRegister(Cluster cluster) {}
120+ public void onRegister(Cluster cluster) {
121+ }
123122
124123 @Override
125- public void onUnregister(Cluster cluster) {}
124+ public void onUnregister(Cluster cluster) {
125+ }
126126 }
127127 }
modified driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +52 −54
@@ -15,6 +15,7 @@
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;
@@ -22,14 +23,11 @@
2223 import org.testng.annotations.BeforeMethod;
2324 import org.testng.annotations.Test;
2425
26+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2527 import static org.assertj.core.api.Assertions.assertThat;
2628 import static org.mockito.Mockito.mock;
2729 import static org.mockito.Mockito.when;
2830
29-import com.datastax.driver.core.querybuilder.BuiltStatement;
30-
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
32-
3331 public class StatementIdempotenceTest {
3432
3533 private Cluster cluster;
@@ -59,7 +57,7 @@
5957 QueryOptions queryOptions = new QueryOptions();
6058 SimpleStatement statement = new SimpleStatement("", cluster);
6159
62- for (boolean valueInOptions : new boolean[]{ true, false }) {
60+ for (boolean valueInOptions : new boolean[]{true, false}) {
6361 queryOptions.setDefaultIdempotence(valueInOptions);
6462 assertThat(statement.isIdempotentWithDefault(queryOptions)).isEqualTo(valueInOptions);
6563 }
@@ -70,8 +68,8 @@
7068 QueryOptions queryOptions = new QueryOptions();
7169 SimpleStatement statement = new SimpleStatement("", cluster);
7270
73- for (boolean valueInOptions : new boolean[]{ true, false })
74- for (boolean valueInStatement : new boolean[]{ true, false }) {
71+ for (boolean valueInOptions : new boolean[]{true, false})
72+ for (boolean valueInStatement : new boolean[]{true, false}) {
7573 queryOptions.setDefaultIdempotence(valueInOptions);
7674 statement.setIdempotent(valueInStatement);
7775 assertThat(statement.isIdempotentWithDefault(queryOptions)).isEqualTo(valueInStatement);
@@ -82,18 +80,18 @@
8280 public void should_infer_for_built_statement() {
8381 for (BuiltStatement statement : idempotentBuiltStatements())
8482 assertThat(statement.isIdempotent())
85- .as(statement.getQueryString())
86- .isTrue();
83+ .as(statement.getQueryString())
84+ .isTrue();
8785
8886 for (BuiltStatement statement : nonIdempotentBuiltStatements())
8987 assertThat(statement.isIdempotent())
90- .as(statement.getQueryString())
91- .isFalse();
88+ .as(statement.getQueryString())
89+ .isFalse();
9290 }
9391
9492 @Test(groups = "unit")
9593 public void should_override_inferred_value_when_manually_set_on_built_statement() {
96- for (boolean manualValue : new boolean[]{ true, false }) {
94+ for (boolean manualValue : new boolean[]{true, false}) {
9795 for (BuiltStatement statement : idempotentBuiltStatements()) {
9896 statement.setIdempotent(manualValue);
9997 assertThat(statement.isIdempotent()).isEqualTo(manualValue);
@@ -108,66 +106,66 @@
108106
109107 private ImmutableList<BuiltStatement> idempotentBuiltStatements() {
110108 return ImmutableList.<BuiltStatement>of(
111- update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
112- update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
113- update("foo").with(put("m", "a", 1)).where(eq("k", 1)), // put in map
114-
115- // select statements should be idempotent even with function calls
116- select().countAll() .from("foo").where(eq("k", 1)),
117- select().ttl("v") .from("foo").where(eq("k", 1)),
118- select().writeTime("v") .from("foo").where(eq("k", 1)),
119- select().fcall("token", "k").from("foo").where(eq("k", 1))
109+ update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
110+ update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
111+ update("foo").with(put("m", "a", 1)).where(eq("k", 1)), // put in map
112+
113+ // select statements should be idempotent even with function calls
114+ select().countAll().from("foo").where(eq("k", 1)),
115+ select().ttl("v").from("foo").where(eq("k", 1)),
116+ select().writeTime("v").from("foo").where(eq("k", 1)),
117+ select().fcall("token", "k").from("foo").where(eq("k", 1))
120118
121119 );
122120 }
123121
124122 private ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() {
125123 return ImmutableList.of(
126- update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
127- update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
128- update("foo").with(incr("c")).where(eq("k", 1)), // counter update
124+ update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
125+ update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
126+ update("foo").with(incr("c")).where(eq("k", 1)), // counter update
129127
130- // function calls
128+ // function calls
131129
132- insertInto("foo").value("k", 1).value("v", fcall("token", "k")),
133- insertInto("foo").value("k", 1).value("v", now()),
134- insertInto("foo").value("k", 1).value("v", uuid()),
130+ insertInto("foo").value("k", 1).value("v", fcall("token", "k")),
131+ insertInto("foo").value("k", 1).value("v", now()),
132+ insertInto("foo").value("k", 1).value("v", uuid()),
135133
136- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(fcall("token", "k"))),
137- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())),
138- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(uuid())),
134+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(fcall("token", "k"))),
135+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())),
136+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(uuid())),
139137
140- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, fcall("token", "k")}),
141- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, now()}),
142- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, uuid()}),
138+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, fcall("token", "k")}),
139+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, now()}),
140+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, uuid()}),
143141
144- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", fcall("token", "k"))}),
145- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", now())}),
146- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", uuid())}),
142+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", fcall("token", "k"))}),
143+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", now())}),
144+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", uuid())}),
147145
148- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(fcall("token", "k"), "foo")}),
149- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(now() , "foo")}),
150- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(uuid() , "foo")}),
146+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(fcall("token", "k"), "foo")}),
147+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(now(), "foo")}),
148+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(uuid(), "foo")}),
151149
152- update("foo").with(set("v", fcall("token", "k"))) .where(eq("k", 1)),
153- update("foo").with(set("v", now())) .where(eq("k", 1)),
154- update("foo").with(set("v", uuid())) .where(eq("k", 1)),
150+ update("foo").with(set("v", fcall("token", "k"))).where(eq("k", 1)),
151+ update("foo").with(set("v", now())).where(eq("k", 1)),
152+ update("foo").with(set("v", uuid())).where(eq("k", 1)),
155153
156- update("foo").with(set("v", Lists.newArrayList(fcall("token", "k")))).where(eq("k", 1)),
157- update("foo").with(set("v", Lists.newArrayList(now()))) .where(eq("k", 1)),
158- update("foo").with(set("v", Lists.newArrayList(uuid()))) .where(eq("k", 1)),
154+ update("foo").with(set("v", Lists.newArrayList(fcall("token", "k")))).where(eq("k", 1)),
155+ update("foo").with(set("v", Lists.newArrayList(now()))).where(eq("k", 1)),
156+ update("foo").with(set("v", Lists.newArrayList(uuid()))).where(eq("k", 1)),
159157
160- // raw() calls
158+ // raw() calls
161159
162- insertInto("foo").value("k", 1).value("v", raw("foo()")),
163- insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
160+ insertInto("foo").value("k", 1).value("v", raw("foo()")),
161+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
164162
165- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, raw("foo()")}),
166- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", raw("foo()"))}),
167- insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(raw("foo()"), "foo")}),
163+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, raw("foo()")}),
164+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", raw("foo()"))}),
165+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(raw("foo()"), "foo")}),
168166
169- update("foo").with(set("v", raw("foo()"))) .where(eq("k", 1)),
170- update("foo").with(set("v", Lists.newArrayList(raw("foo()")))).where(eq("k", 1))
167+ update("foo").with(set("v", raw("foo()"))).where(eq("k", 1)),
168+ update("foo").with(set("v", Lists.newArrayList(raw("foo()")))).where(eq("k", 1))
171169
172170 );
173171 }
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +21 −14
@@ -15,18 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.exceptions.DriverException;
19+import com.datastax.driver.core.policies.*;
20+import com.google.common.collect.Lists;
21+import org.testng.annotations.Test;
22+
1823 import java.util.Collection;
1924 import java.util.Iterator;
2025 import java.util.concurrent.atomic.AtomicInteger;
2126
22-import com.google.common.collect.Lists;
23-import org.testng.annotations.Test;
24-
2527 import static org.assertj.core.api.Assertions.assertThat;
2628
27-import com.datastax.driver.core.exceptions.DriverException;
28-import com.datastax.driver.core.policies.*;
29-
3029 public class StatementWrapperTest extends CCMBridge.PerClassSingleNodeCluster {
3130 @Override
3231 protected Collection<String> getTableDefinitions() {
@@ -40,9 +39,9 @@
4039 @Override
4140 protected Cluster.Builder configure(Cluster.Builder builder) {
4241 return builder
43- .withLoadBalancingPolicy(loadBalancingPolicy)
44- .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
45- .withRetryPolicy(retryPolicy);
42+ .withLoadBalancingPolicy(loadBalancingPolicy)
43+ .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
44+ .withRetryPolicy(retryPolicy);
4645 }
4746
4847 @Test(groups = "short")
@@ -76,7 +75,7 @@
7675 // Set CL TWO with only one node, so the statement will always cause UNAVAILABLE,
7776 // which our custom policy ignores.
7877 Statement s = new SimpleStatement("select * from system.local")
79- .setConsistencyLevel(ConsistencyLevel.TWO);
78+ .setConsistencyLevel(ConsistencyLevel.TWO);
8079
8180 session.execute(s);
8281 assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(0);
@@ -85,14 +84,18 @@
8584 assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(1);
8685 }
8786
88- /** A custom wrapper that's just used to mark statements. */
87+ /**
88+ * A custom wrapper that's just used to mark statements.
89+ */
8990 static class CustomStatement extends StatementWrapper {
9091 protected CustomStatement(Statement wrapped) {
9192 super(wrapped);
9293 }
9394 }
9495
95- /** A load balancing policy that counts how many times it has seen the custom wrapper */
96+ /**
97+ * A load balancing policy that counts how many times it has seen the custom wrapper
98+ */
9699 static class CustomLoadBalancingPolicy extends DelegatingLoadBalancingPolicy {
97100 final AtomicInteger customStatementsHandled = new AtomicInteger();
98101
@@ -108,7 +111,9 @@
108111 }
109112 }
110113
111- /** A speculative execution policy that counts how many times it has seen the custom wrapper */
114+ /**
115+ * A speculative execution policy that counts how many times it has seen the custom wrapper
116+ */
112117 static class CustomSpeculativeExecutionPolicy extends DelegatingSpeculativeExecutionPolicy {
113118 final AtomicInteger customStatementsHandled = new AtomicInteger();
114119
@@ -124,7 +129,9 @@
124129 }
125130 }
126131
127- /** A retry policy that counts how many times it has seen the custom wrapper for UNAVAILABLE errors. */
132+ /**
133+ * A retry policy that counts how many times it has seen the custom wrapper for UNAVAILABLE errors.
134+ */
128135 static class CustomRetryPolicy implements RetryPolicy {
129136 final AtomicInteger customStatementsHandled = new AtomicInteger();
130137
modified driver-core/src/test/java/com/datastax/driver/core/StreamIdGeneratorTest.java +1 −3
@@ -16,10 +16,8 @@
1616 package com.datastax.driver.core;
1717
1818 import org.testng.annotations.Test;
19-import static org.testng.Assert.assertEquals;
20-import static org.testng.Assert.fail;
2119
22-import com.datastax.driver.core.exceptions.BusyConnectionException;
20+import static org.testng.Assert.assertEquals;
2321
2422 public class StreamIdGeneratorTest {
2523
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java +1 −1
@@ -60,7 +60,7 @@
6060 assertThat(actual.getOptions().getComment()).isNotEqualTo(comment);
6161 return this;
6262 }
63-
63+
6464 public TableMetadataAssert isCompactStorage() {
6565 assertThat(actual.getOptions().isCompactStorage()).isTrue();
6666 return this;
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +184 −186
@@ -15,21 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.nio.ByteBuffer;
19-import java.util.Collection;
20-import java.util.Collections;
21-
18+import com.datastax.driver.core.utils.CassandraVersion;
2219 import com.google.common.collect.ImmutableMap;
2320 import org.testng.annotations.Test;
2421
25-import static org.assertj.core.api.Assertions.entry;
26-
27-import com.datastax.driver.core.utils.CassandraVersion;
22+import java.nio.ByteBuffer;
23+import java.util.Collection;
24+import java.util.Collections;
2825
2926 import static com.datastax.driver.core.Assertions.assertThat;
30-import static com.datastax.driver.core.DataType.*;
3127 import static com.datastax.driver.core.ClusteringOrder.ASC;
3228 import static com.datastax.driver.core.ClusteringOrder.DESC;
29+import static com.datastax.driver.core.DataType.*;
30+import static org.assertj.core.api.Assertions.entry;
3331
3432 public class TableMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
3533 @Override
@@ -41,12 +39,12 @@
4139 public void should_parse_table_without_clustering_columns() {
4240 // given
4341 String cql = String.format("CREATE TABLE %s.static (\n"
44- + " k text,\n"
45- + " i int,\n"
46- + " m map<text, timeuuid>,\n"
47- + " v int,\n"
48- + " PRIMARY KEY (k)\n"
49- + ");", keyspace);
42+ + " k text,\n"
43+ + " i int,\n"
44+ + " m map<text, timeuuid>,\n"
45+ + " v int,\n"
46+ + " PRIMARY KEY (k)\n"
47+ + ");", keyspace);
5048 // when
5149 session.execute(cql);
5250 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("static");
@@ -61,9 +59,9 @@
6159 @Override
6260 protected Cluster.Builder configure(Cluster.Builder builder) {
6361 return builder.withQueryOptions(new QueryOptions()
64- .setRefreshNodeIntervalMillis(0)
65- .setRefreshNodeListIntervalMillis(0)
66- .setRefreshSchemaIntervalMillis(0)
62+ .setRefreshNodeIntervalMillis(0)
63+ .setRefreshNodeListIntervalMillis(0)
64+ .setRefreshSchemaIntervalMillis(0)
6765 );
6866 }
6967
@@ -71,13 +69,13 @@
7169 public void should_parse_table_with_clustering_columns() {
7270 // given
7371 String cql = String.format("CREATE TABLE %s.sparse (\n"
74- + " k text,\n"
75- + " c1 int,\n"
76- + " c2 float,\n"
77- + " l list<text>,\n"
78- + " v int,\n"
79- + " PRIMARY KEY (k, c1, c2)\n"
80- + ") WITH CLUSTERING ORDER BY (c1 ASC, c2 DESC);", keyspace);
72+ + " k text,\n"
73+ + " c1 int,\n"
74+ + " c2 float,\n"
75+ + " l list<text>,\n"
76+ + " v int,\n"
77+ + " PRIMARY KEY (k, c1, c2)\n"
78+ + ") WITH CLUSTERING ORDER BY (c1 ASC, c2 DESC);", keyspace);
8179 // when
8280 session.execute(cql);
8381 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("sparse");
@@ -94,10 +92,10 @@
9492 public void should_parse_counter_table() {
9593 // given
9694 String cql = String.format("CREATE TABLE %s.counters (\n"
97- + " k text,\n"
98- + " c counter,\n"
99- + " PRIMARY KEY (k)\n"
100- + ");", keyspace);
95+ + " k text,\n"
96+ + " c counter,\n"
97+ + " PRIMARY KEY (k)\n"
98+ + ");", keyspace);
10199 // when
102100 session.execute(cql);
103101 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("counters");
@@ -111,12 +109,12 @@
111109 public void should_parse_compact_static_table() {
112110 // given
113111 String cql = String.format("CREATE TABLE %s.compact_static (\n"
114- + " k text,\n"
115- + " i int,\n"
116- + " t timeuuid,\n"
117- + " v int,\n"
118- + " PRIMARY KEY (k)\n"
119- + ") WITH COMPACT STORAGE;", keyspace);
112+ + " k text,\n"
113+ + " i int,\n"
114+ + " t timeuuid,\n"
115+ + " v int,\n"
116+ + " PRIMARY KEY (k)\n"
117+ + ") WITH COMPACT STORAGE;", keyspace);
120118 // when
121119 session.execute(cql);
122120 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("compact_static");
@@ -132,10 +130,10 @@
132130 public void should_parse_dense_table() {
133131 // given
134132 String cql = String.format("CREATE TABLE %s.dense (\n"
135- + " k int,\n"
136- + " c int,\n"
137- + " PRIMARY KEY (k, c)\n"
138- + " ) WITH COMPACT STORAGE;", keyspace);
133+ + " k int,\n"
134+ + " c int,\n"
135+ + " PRIMARY KEY (k, c)\n"
136+ + " ) WITH COMPACT STORAGE;", keyspace);
139137 // when
140138 session.execute(cql);
141139 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("dense");
@@ -149,11 +147,11 @@
149147 public void should_parse_compact_dynamic_table() {
150148 // given
151149 String cql = String.format("CREATE TABLE %s.compact_dynamic (\n"
152- + " k text,\n"
153- + " c int,\n"
154- + " v timeuuid,\n"
155- + " PRIMARY KEY (k, c)\n"
156- + ") WITH COMPACT STORAGE;", keyspace);
150+ + " k text,\n"
151+ + " c int,\n"
152+ + " v timeuuid,\n"
153+ + " PRIMARY KEY (k, c)\n"
154+ + ") WITH COMPACT STORAGE;", keyspace);
157155 // when
158156 session.execute(cql);
159157 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("compact_dynamic");
@@ -168,13 +166,13 @@
168166 public void should_parse_compact_table_with_multiple_clustering_columns() {
169167 // given
170168 String cql = String.format("CREATE TABLE %s.compact_composite (\n"
171- + " k text,\n"
172- + " c1 int,\n"
173- + " c2 float,\n"
174- + " c3 double,\n"
175- + " v timeuuid,\n"
176- + " PRIMARY KEY (k, c1, c2, c3)\n"
177- + ") WITH COMPACT STORAGE;", keyspace);
169+ + " k text,\n"
170+ + " c1 int,\n"
171+ + " c2 float,\n"
172+ + " c3 double,\n"
173+ + " v timeuuid,\n"
174+ + " PRIMARY KEY (k, c1, c2, c3)\n"
175+ + ") WITH COMPACT STORAGE;", keyspace);
178176 // when
179177 session.execute(cql);
180178 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("compact_composite");
@@ -197,45 +195,45 @@
197195 // Cassandra 3.0 +
198196 if (version.getMajor() > 2) {
199197 cql = String.format("CREATE TABLE %s.with_options (\n"
200- + " k text,\n"
201- + " c1 int,\n"
202- + " c2 int,\n"
203- + " i int,\n"
204- + " PRIMARY KEY (k, c1, c2)\n"
205- + ") WITH CLUSTERING ORDER BY (c1 DESC, c2 ASC)\n"
206- + " AND read_repair_chance = 0.5\n"
207- + " AND dclocal_read_repair_chance = 0.6\n"
208- + " AND speculative_retry = '99.9PERCENTILE'\n"
209- // replicate_on_write not supported anymore in 3.0
210- + " AND gc_grace_seconds = 42\n"
211- + " AND bloom_filter_fp_chance = 0.01\n"
212- // older caching formats not supported anymore in 3.0
213- + " AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 10 }\n"
214- + " AND comment = 'My awesome table'\n"
215- + " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n"
216- + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 }\n"
217- + " AND crc_check_chance = 0.5;", // available from C* 3.0
218- keyspace);
219-
220- // older versions
198+ + " k text,\n"
199+ + " c1 int,\n"
200+ + " c2 int,\n"
201+ + " i int,\n"
202+ + " PRIMARY KEY (k, c1, c2)\n"
203+ + ") WITH CLUSTERING ORDER BY (c1 DESC, c2 ASC)\n"
204+ + " AND read_repair_chance = 0.5\n"
205+ + " AND dclocal_read_repair_chance = 0.6\n"
206+ + " AND speculative_retry = '99.9PERCENTILE'\n"
207+ // replicate_on_write not supported anymore in 3.0
208+ + " AND gc_grace_seconds = 42\n"
209+ + " AND bloom_filter_fp_chance = 0.01\n"
210+ // older caching formats not supported anymore in 3.0
211+ + " AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 10 }\n"
212+ + " AND comment = 'My awesome table'\n"
213+ + " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n"
214+ + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 }\n"
215+ + " AND crc_check_chance = 0.5;", // available from C* 3.0
216+ keyspace);
217+
218+ // older versions
221219 } else {
222220 cql = String.format("CREATE TABLE %s.with_options (\n"
223- + " k text,\n"
224- + " c1 int,\n"
225- + " c2 int,\n"
226- + " i int,\n"
227- + " PRIMARY KEY (k, c1, c2)\n"
228- + ") WITH CLUSTERING ORDER BY (c1 DESC, c2 ASC)\n"
229- + " AND read_repair_chance = 0.5\n"
230- + " AND dclocal_read_repair_chance = 0.6\n"
231- + " AND replicate_on_write = true\n"
232- + " AND gc_grace_seconds = 42\n"
233- + " AND bloom_filter_fp_chance = 0.01\n"
234- + " AND caching = 'ALL'\n"
235- + " AND comment = 'My awesome table'\n"
236- + " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n"
237- + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 };",
238- keyspace);
221+ + " k text,\n"
222+ + " c1 int,\n"
223+ + " c2 int,\n"
224+ + " i int,\n"
225+ + " PRIMARY KEY (k, c1, c2)\n"
226+ + ") WITH CLUSTERING ORDER BY (c1 DESC, c2 ASC)\n"
227+ + " AND read_repair_chance = 0.5\n"
228+ + " AND dclocal_read_repair_chance = 0.6\n"
229+ + " AND replicate_on_write = true\n"
230+ + " AND gc_grace_seconds = 42\n"
231+ + " AND bloom_filter_fp_chance = 0.01\n"
232+ + " AND caching = 'ALL'\n"
233+ + " AND comment = 'My awesome table'\n"
234+ + " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n"
235+ + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 };",
236+ keyspace);
239237 }
240238
241239 // when
@@ -258,7 +256,7 @@
258256 assertThat(table.getOptions().getGcGraceInSeconds()).isEqualTo(42);
259257 assertThat(table.getOptions().getBloomFilterFalsePositiveChance()).isEqualTo(0.01);
260258 assertThat(table.getOptions().getComment()).isEqualTo("My awesome table");
261- assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL" ));
259+ assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL"));
262260 assertThat(table.getOptions().getCaching()).contains(entry("rows_per_partition", "10"));
263261 assertThat(table.getOptions().getCompaction()).contains(entry("class", "org.apache.cassandra.db.compaction.LeveledCompactionStrategy"));
264262 assertThat(table.getOptions().getCompaction()).contains(entry("sstable_size_in_mb", "15"));
@@ -273,26 +271,26 @@
273271 assertThat(table.getOptions().getCrcCheckChance()).isEqualTo(0.5);
274272 assertThat(table.getOptions().getExtensions()).isEmpty(); // default
275273 assertThat(table.asCQLQuery())
276- .contains("read_repair_chance = 0.5")
277- .contains("dclocal_read_repair_chance = 0.6")
278- .contains("gc_grace_seconds = 42")
279- .contains("bloom_filter_fp_chance = 0.01")
280- .contains("comment = 'My awesome table'")
281- .contains("'keys' : 'ALL'")
282- .contains("'rows_per_partition' : 10")
283- .contains("'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy'")
284- .contains("'sstable_size_in_mb' : 15")
285- .contains("'class' : 'org.apache.cassandra.io.compress.SnappyCompressor'") // sstable_compression becomes class
286- .contains("'chunk_length_in_kb' : 128") // note the "in" prefix
287- .contains("default_time_to_live = 0")
288- .contains("speculative_retry = '99.9PERCENTILE'")
289- .contains("min_index_interval = 128")
290- .contains("max_index_interval = 2048")
291- .contains("crc_check_chance = 0.5")
292- .doesNotContain(" index_interval")
293- .doesNotContain("replicate_on_write");
294-
295- // Cassandra 2.1 and 2.2
274+ .contains("read_repair_chance = 0.5")
275+ .contains("dclocal_read_repair_chance = 0.6")
276+ .contains("gc_grace_seconds = 42")
277+ .contains("bloom_filter_fp_chance = 0.01")
278+ .contains("comment = 'My awesome table'")
279+ .contains("'keys' : 'ALL'")
280+ .contains("'rows_per_partition' : 10")
281+ .contains("'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy'")
282+ .contains("'sstable_size_in_mb' : 15")
283+ .contains("'class' : 'org.apache.cassandra.io.compress.SnappyCompressor'") // sstable_compression becomes class
284+ .contains("'chunk_length_in_kb' : 128") // note the "in" prefix
285+ .contains("default_time_to_live = 0")
286+ .contains("speculative_retry = '99.9PERCENTILE'")
287+ .contains("min_index_interval = 128")
288+ .contains("max_index_interval = 2048")
289+ .contains("crc_check_chance = 0.5")
290+ .doesNotContain(" index_interval")
291+ .doesNotContain("replicate_on_write");
292+
293+ // Cassandra 2.1 and 2.2
296294 } else if (version.getMajor() == 2 && version.getMinor() > 0) {
297295
298296 // With 2.1 we have different options, the caching option changes and replicate_on_write disappears
@@ -301,7 +299,7 @@
301299 assertThat(table.getOptions().getGcGraceInSeconds()).isEqualTo(42);
302300 assertThat(table.getOptions().getBloomFilterFalsePositiveChance()).isEqualTo(0.01);
303301 assertThat(table.getOptions().getComment()).isEqualTo("My awesome table");
304- assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL" ));
302+ assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL"));
305303 assertThat(table.getOptions().getCaching()).contains(entry("rows_per_partition", "ALL"));
306304 assertThat(table.getOptions().getCompaction()).contains(entry("class", "org.apache.cassandra.db.compaction.LeveledCompactionStrategy"));
307305 assertThat(table.getOptions().getCompaction()).contains(entry("sstable_size_in_mb", "15"));
@@ -315,25 +313,25 @@
315313 assertThat(table.getOptions().getReplicateOnWrite()).isTrue(); // default
316314 assertThat(table.getOptions().getExtensions()).isEmpty();
317315 assertThat(table.asCQLQuery())
318- .contains("read_repair_chance = 0.5")
319- .contains("dclocal_read_repair_chance = 0.6")
320- .contains("gc_grace_seconds = 42")
321- .contains("bloom_filter_fp_chance = 0.01")
322- .contains("comment = 'My awesome table'")
323- .contains("'keys' : 'ALL'")
324- .contains("'rows_per_partition' : 'ALL'")
325- .contains("'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy'")
326- .contains("'sstable_size_in_mb' : 15")
327- .contains("'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor'")
328- .contains("'chunk_length_kb' : 128")
329- .contains("default_time_to_live = 0")
330- .contains("speculative_retry = '99.0PERCENTILE'")
331- .contains("min_index_interval = 128")
332- .contains("max_index_interval = 2048")
333- .doesNotContain(" index_interval")
334- .doesNotContain("replicate_on_write");
335-
336- // Cassandra 2.0
316+ .contains("read_repair_chance = 0.5")
317+ .contains("dclocal_read_repair_chance = 0.6")
318+ .contains("gc_grace_seconds = 42")
319+ .contains("bloom_filter_fp_chance = 0.01")
320+ .contains("comment = 'My awesome table'")
321+ .contains("'keys' : 'ALL'")
322+ .contains("'rows_per_partition' : 'ALL'")
323+ .contains("'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy'")
324+ .contains("'sstable_size_in_mb' : 15")
325+ .contains("'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor'")
326+ .contains("'chunk_length_kb' : 128")
327+ .contains("default_time_to_live = 0")
328+ .contains("speculative_retry = '99.0PERCENTILE'")
329+ .contains("min_index_interval = 128")
330+ .contains("max_index_interval = 2048")
331+ .doesNotContain(" index_interval")
332+ .doesNotContain("replicate_on_write");
333+
334+ // Cassandra 2.0
337335 } else if (version.getMajor() == 2 && version.getMinor() == 0) {
338336
339337 assertThat(table.getOptions().getReadRepairChance()).isEqualTo(0.5);
@@ -341,7 +339,7 @@
341339 assertThat(table.getOptions().getGcGraceInSeconds()).isEqualTo(42);
342340 assertThat(table.getOptions().getBloomFilterFalsePositiveChance()).isEqualTo(0.01);
343341 assertThat(table.getOptions().getComment()).isEqualTo("My awesome table");
344- assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL" ));
342+ assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL"));
345343 assertThat(table.getOptions().getCaching()).doesNotContain(entry("rows_per_partition", "ALL")); // 2.1 +
346344 assertThat(table.getOptions().getCompaction()).contains(entry("class", "org.apache.cassandra.db.compaction.LeveledCompactionStrategy"));
347345 assertThat(table.getOptions().getCompaction()).contains(entry("sstable_size_in_mb", "15"));
@@ -355,24 +353,24 @@
355353 assertThat(table.getOptions().getReplicateOnWrite()).isTrue(); // explicitly set
356354 assertThat(table.getOptions().getExtensions()).isEmpty();
357355 assertThat(table.asCQLQuery())
358- .contains("read_repair_chance = 0.5")
359- .contains("dclocal_read_repair_chance = 0.6")
360- .contains("gc_grace_seconds = 42")
361- .contains("bloom_filter_fp_chance = 0.01")
362- .contains("comment = 'My awesome table'")
363- .contains("caching = 'ALL'")
364- .contains("'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy'")
365- .contains("'sstable_size_in_mb' : 15")
366- .contains("'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor'")
367- .contains("'chunk_length_kb' : 128")
368- .contains("replicate_on_write = true")
369- .contains("index_interval = 128")
370- .contains("speculative_retry = '99.0PERCENTILE'")
371- .contains("default_time_to_live = 0")
372- .doesNotContain("min_index_interval") // 2.1 +
373- .doesNotContain("max_index_interval"); // 2.1 +
374-
375- // Cassandra 1.2
356+ .contains("read_repair_chance = 0.5")
357+ .contains("dclocal_read_repair_chance = 0.6")
358+ .contains("gc_grace_seconds = 42")
359+ .contains("bloom_filter_fp_chance = 0.01")
360+ .contains("comment = 'My awesome table'")
361+ .contains("caching = 'ALL'")
362+ .contains("'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy'")
363+ .contains("'sstable_size_in_mb' : 15")
364+ .contains("'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor'")
365+ .contains("'chunk_length_kb' : 128")
366+ .contains("replicate_on_write = true")
367+ .contains("index_interval = 128")
368+ .contains("speculative_retry = '99.0PERCENTILE'")
369+ .contains("default_time_to_live = 0")
370+ .doesNotContain("min_index_interval") // 2.1 +
371+ .doesNotContain("max_index_interval"); // 2.1 +
372+
373+ // Cassandra 1.2
376374 } else {
377375
378376 assertThat(table.getOptions().getReadRepairChance()).isEqualTo(0.5);
@@ -380,7 +378,7 @@
380378 assertThat(table.getOptions().getGcGraceInSeconds()).isEqualTo(42);
381379 assertThat(table.getOptions().getBloomFilterFalsePositiveChance()).isEqualTo(0.01);
382380 assertThat(table.getOptions().getComment()).isEqualTo("My awesome table");
383- assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL" ));
381+ assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL"));
384382 assertThat(table.getOptions().getCaching()).doesNotContain(entry("rows_per_partition", "ALL")); // 2.1 +
385383 assertThat(table.getOptions().getCompaction()).contains(entry("class", "org.apache.cassandra.db.compaction.LeveledCompactionStrategy"));
386384 assertThat(table.getOptions().getCompaction()).contains(entry("sstable_size_in_mb", "15"));
@@ -394,22 +392,22 @@
394392 assertThat(table.getOptions().getReplicateOnWrite()).isTrue(); // explicitly set
395393 assertThat(table.getOptions().getExtensions()).isEmpty();
396394 assertThat(table.asCQLQuery())
397- .contains("read_repair_chance = 0.5")
398- .contains("dclocal_read_repair_chance = 0.6")
399- .contains("gc_grace_seconds = 42")
400- .contains("bloom_filter_fp_chance = 0.01")
401- .contains("comment = 'My awesome table'")
402- .contains("caching = 'ALL'")
403- .contains("'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy'")
404- .contains("'sstable_size_in_mb' : 15")
405- .contains("'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor'")
406- .contains("'chunk_length_kb' : 128")
407- .contains("replicate_on_write = true")
408- .doesNotContain("index_interval") // 2.0
409- .doesNotContain("min_index_interval") // 2.1 +
410- .doesNotContain("max_index_interval") // 2.1 +
411- .doesNotContain("speculative_retry") // 2.0 +
412- .doesNotContain("default_time_to_live"); // 2.0 +
395+ .contains("read_repair_chance = 0.5")
396+ .contains("dclocal_read_repair_chance = 0.6")
397+ .contains("gc_grace_seconds = 42")
398+ .contains("bloom_filter_fp_chance = 0.01")
399+ .contains("comment = 'My awesome table'")
400+ .contains("caching = 'ALL'")
401+ .contains("'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy'")
402+ .contains("'sstable_size_in_mb' : 15")
403+ .contains("'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor'")
404+ .contains("'chunk_length_kb' : 128")
405+ .contains("replicate_on_write = true")
406+ .doesNotContain("index_interval") // 2.0
407+ .doesNotContain("min_index_interval") // 2.1 +
408+ .doesNotContain("max_index_interval") // 2.1 +
409+ .doesNotContain("speculative_retry") // 2.0 +
410+ .doesNotContain("default_time_to_live"); // 2.0 +
413411
414412 }
415413
@@ -422,19 +420,19 @@
422420 *
423421 * @jira_ticket CASSANDRA-9424
424422 */
425- @Test(groups="short")
426- @CassandraVersion(major=3.0)
423+ @Test(groups = "short")
424+ @CassandraVersion(major = 3.0)
427425 public void should_parse_new_compression_options() {
428426 // given
429427 String cql = String.format("CREATE TABLE %s.new_compression_options (\n"
430- + " k text,\n"
431- + " c1 int,\n"
432- + " c2 int,\n"
433- + " i int,\n"
434- + " PRIMARY KEY (k, c1, c2)\n"
435- + ") WITH CLUSTERING ORDER BY (c1 DESC, c2 ASC)\n"
436- + " AND compression = { 'class' : 'DeflateCompressor', 'chunk_length_in_kb' : 128 };",
437- keyspace);
428+ + " k text,\n"
429+ + " c1 int,\n"
430+ + " c2 int,\n"
431+ + " i int,\n"
432+ + " PRIMARY KEY (k, c1, c2)\n"
433+ + ") WITH CLUSTERING ORDER BY (c1 DESC, c2 ASC)\n"
434+ + " AND compression = { 'class' : 'DeflateCompressor', 'chunk_length_in_kb' : 128 };",
435+ keyspace);
438436
439437 // when
440438 session.execute(cql);
@@ -442,17 +440,17 @@
442440
443441 // then
444442 assertThat(table.getOptions().getCompression())
445- .contains(entry("class", "org.apache.cassandra.io.compress.DeflateCompressor"))
446- .contains(entry("chunk_length_in_kb", "128"));
443+ .contains(entry("class", "org.apache.cassandra.io.compress.DeflateCompressor"))
444+ .contains(entry("chunk_length_in_kb", "128"));
447445 }
448446
449447 @Test(groups = "short")
450448 public void should_escape_single_quote_table_comment() {
451449 // given
452450 String cql = String.format("CREATE TABLE %s.single_quote (\n"
453- + " c1 int PRIMARY KEY\n"
454- + ") WITH comment = 'comment with single quote '' should work'",
455- keyspace);
451+ + " c1 int PRIMARY KEY\n"
452+ + ") WITH comment = 'comment with single quote '' should work'",
453+ keyspace);
456454 // when
457455 session.execute(cql);
458456 TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote");
@@ -469,7 +467,7 @@
469467 "CREATE TABLE test_cd (c int PRIMARY KEY, d int);",
470468 "CREATE INDEX test_d on test_cd (d);",
471469 };
472- for (String statement: statements)
470+ for (String statement : statements)
473471 session.execute(statement);
474472
475473 TableMetadata table_ab = cluster.getMetadata().getKeyspace(keyspace).getTable("test_ab");
@@ -491,16 +489,16 @@
491489 * @test_category metadata
492490 */
493491 @Test(groups = "short")
494- @CassandraVersion(major=3.0)
492+ @CassandraVersion(major = 3.0)
495493 public void should_parse_extensions_from_table_options() throws Exception {
496494 // given
497495 // create a simple table and retrieve it's metadata from system_schema.tables.
498496 String cql = String.format("CREATE TABLE %s.table_with_extensions (\n"
499- + " k text,\n"
500- + " c int,\n"
501- + " v timeuuid,\n"
502- + " PRIMARY KEY (k, c)\n"
503- + ");", keyspace);
497+ + " k text,\n"
498+ + " c int,\n"
499+ + " v timeuuid,\n"
500+ + " PRIMARY KEY (k, c)\n"
501+ + ");", keyspace);
504502 session.execute(cql);
505503
506504 // Manually change column value in system_schema.tables and force a schema refresh on that table.
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 +89 −72
@@ -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,31 +57,31 @@
5857 public static void setValue(SettableByIndexData<?> data, int i, DataType type, Object value) {
5958 switch (type.getName()) {
6059 case ASCII:
61- data.setString(i, (String)value);
60+ data.setString(i, (String) value);
6261 break;
6362 case BIGINT:
64- data.setLong(i, (Long)value);
63+ data.setLong(i, (Long) value);
6564 break;
6665 case BLOB:
67- data.setBytes(i, (ByteBuffer)value);
66+ data.setBytes(i, (ByteBuffer) value);
6867 break;
6968 case BOOLEAN:
70- data.setBool(i, (Boolean)value);
69+ data.setBool(i, (Boolean) value);
7170 break;
7271 case COUNTER:
7372 // Just a no-op, we shouldn't handle counters the same way than other types
7473 break;
7574 case DECIMAL:
76- data.setDecimal(i, (BigDecimal)value);
75+ data.setDecimal(i, (BigDecimal) value);
7776 break;
7877 case DOUBLE:
79- data.setDouble(i, (Double)value);
78+ data.setDouble(i, (Double) value);
8079 break;
8180 case FLOAT:
82- data.setFloat(i, (Float)value);
81+ data.setFloat(i, (Float) value);
8382 break;
8483 case INET:
85- data.setInet(i, (InetAddress)value);
84+ data.setInet(i, (InetAddress) value);
8685 break;
8786 case TINYINT:
8887 data.setByte(i, (Byte) value);
@@ -100,66 +99,66 @@
10099 data.setTimestamp(i, (Date) value);
101100 break;
102101 case DATE:
103- data.setDate(i, (LocalDate)value);
102+ data.setDate(i, (LocalDate) value);
104103 break;
105104 case TIME:
106105 data.setTime(i, (Long) value);
107106 break;
108107 case UUID:
109- data.setUUID(i, (UUID)value);
108+ data.setUUID(i, (UUID) value);
110109 break;
111110 case VARCHAR:
112- data.setString(i, (String)value);
111+ data.setString(i, (String) value);
113112 break;
114113 case VARINT:
115- data.setVarint(i, (BigInteger)value);
114+ data.setVarint(i, (BigInteger) value);
116115 break;
117116 case TIMEUUID:
118- data.setUUID(i, (UUID)value);
117+ data.setUUID(i, (UUID) value);
119118 break;
120119 case LIST:
121- data.setList(i, (List)value);
120+ data.setList(i, (List) value);
122121 break;
123122 case SET:
124- data.setSet(i, (Set)value);
123+ data.setSet(i, (Set) value);
125124 break;
126125 case MAP:
127- data.setMap(i, (Map)value);
126+ data.setMap(i, (Map) value);
128127 break;
129128 default:
130129 throw new RuntimeException("Missing handling of " + type);
131130 }
132131 }
133132
134- @SuppressWarnings({ "unchecked", "rawtypes" })
133+ @SuppressWarnings({"unchecked", "rawtypes"})
135134 public static void setValue(SettableByNameData<?> data, String name, DataType type, Object value) {
136135 switch (type.getName()) {
137136 case ASCII:
138- data.setString(name, (String)value);
137+ data.setString(name, (String) value);
139138 break;
140139 case BIGINT:
141- data.setLong(name, (Long)value);
140+ data.setLong(name, (Long) value);
142141 break;
143142 case BLOB:
144- data.setBytes(name, (ByteBuffer)value);
143+ data.setBytes(name, (ByteBuffer) value);
145144 break;
146145 case BOOLEAN:
147- data.setBool(name, (Boolean)value);
146+ data.setBool(name, (Boolean) value);
148147 break;
149148 case COUNTER:
150149 // Just a no-op, we shouldn't handle counters the same way than other types
151150 break;
152151 case DECIMAL:
153- data.setDecimal(name, (BigDecimal)value);
152+ data.setDecimal(name, (BigDecimal) value);
154153 break;
155154 case DOUBLE:
156- data.setDouble(name, (Double)value);
155+ data.setDouble(name, (Double) value);
157156 break;
158157 case FLOAT:
159- data.setFloat(name, (Float)value);
158+ data.setFloat(name, (Float) value);
160159 break;
161160 case INET:
162- data.setInet(name, (InetAddress)value);
161+ data.setInet(name, (InetAddress) value);
163162 break;
164163 case TINYINT:
165164 data.setByte(name, (Byte) value);
@@ -177,31 +176,31 @@
177176 data.setTimestamp(name, (Date) value);
178177 break;
179178 case DATE:
180- data.setDate(name, (LocalDate)value);
179+ data.setDate(name, (LocalDate) value);
181180 break;
182181 case TIME:
183182 data.setTime(name, (Long) value);
184183 break;
185184 case UUID:
186- data.setUUID(name, (UUID)value);
185+ data.setUUID(name, (UUID) value);
187186 break;
188187 case VARCHAR:
189- data.setString(name, (String)value);
188+ data.setString(name, (String) value);
190189 break;
191190 case VARINT:
192- data.setVarint(name, (BigInteger)value);
191+ data.setVarint(name, (BigInteger) value);
193192 break;
194193 case TIMEUUID:
195- data.setUUID(name, (UUID)value);
194+ data.setUUID(name, (UUID) value);
196195 break;
197196 case LIST:
198- data.setList(name, (List)value);
197+ data.setList(name, (List) value);
199198 break;
200199 case SET:
201- data.setSet(name, (Set)value);
200+ data.setSet(name, (Set) value);
202201 break;
203202 case MAP:
204- data.setMap(name, (Map)value);
203+ data.setMap(name, (Map) value);
205204 break;
206205 default:
207206 throw new RuntimeException("Missing handling of " + type);
@@ -330,7 +329,7 @@
330329 case BIGINT:
331330 return 42L;
332331 case BLOB:
333- return ByteBuffer.wrap(new byte[]{ (byte)4, (byte)12, (byte)1 });
332+ return ByteBuffer.wrap(new byte[]{(byte) 4, (byte) 12, (byte) 1});
334333 case BOOLEAN:
335334 return true;
336335 case COUNTER:
@@ -342,11 +341,11 @@
342341 case FLOAT:
343342 return 3.142519f;
344343 case INET:
345- return InetAddress.getByAddress(new byte[]{ (byte)127, (byte)0, (byte)0, (byte)1 });
344+ return InetAddress.getByAddress(new byte[]{(byte) 127, (byte) 0, (byte) 0, (byte) 1});
346345 case TINYINT:
347- return (byte)25;
346+ return (byte) 25;
348347 case SMALLINT:
349- return (short)26;
348+ return (short) 26;
350349 case INT:
351350 return 24;
352351 case TEXT:
@@ -366,11 +365,17 @@
366365 case TIMEUUID:
367366 return UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66");
368367 case LIST:
369- return new ArrayList<Object>(){{ add(getFixedValue(type.getTypeArguments().get(0))); }};
368+ return new ArrayList<Object>() {{
369+ add(getFixedValue(type.getTypeArguments().get(0)));
370+ }};
370371 case SET:
371- return new HashSet<Object>(){{ add(getFixedValue(type.getTypeArguments().get(0))); }};
372+ return new HashSet<Object>() {{
373+ add(getFixedValue(type.getTypeArguments().get(0)));
374+ }};
372375 case MAP:
373- return new HashMap<Object, Object>(){{ put(getFixedValue(type.getTypeArguments().get(0)), getFixedValue(type.getTypeArguments().get(1))); }};
376+ return new HashMap<Object, Object>() {{
377+ put(getFixedValue(type.getTypeArguments().get(0)), getFixedValue(type.getTypeArguments().get(1)));
378+ }};
374379 }
375380 } catch (Exception e) {
376381 throw new RuntimeException(e);
@@ -428,11 +433,17 @@
428433 case TIMEUUID:
429434 return UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66");
430435 case LIST:
431- return new ArrayList<Object>(){{ add(getFixedValue2(type.getTypeArguments().get(0))); }};
436+ return new ArrayList<Object>() {{
437+ add(getFixedValue2(type.getTypeArguments().get(0)));
438+ }};
432439 case SET:
433- return new HashSet<Object>(){{ add(getFixedValue2(type.getTypeArguments().get(0))); }};
440+ return new HashSet<Object>() {{
441+ add(getFixedValue2(type.getTypeArguments().get(0)));
442+ }};
434443 case MAP:
435- return new HashMap<Object, Object>(){{ put(getFixedValue2(type.getTypeArguments().get(0)), getFixedValue2(type.getTypeArguments().get(1))); }};
444+ return new HashMap<Object, Object>() {{
445+ put(getFixedValue2(type.getTypeArguments().get(0)), getFixedValue2(type.getTypeArguments().get(1)));
446+ }};
436447 }
437448 } catch (Exception e) {
438449 throw new RuntimeException(e);
@@ -489,8 +500,8 @@
489500 logger.info("Waiting for stopped node: " + node);
490501 else if (waitForOut)
491502 logger.info("Waiting for decommissioned node: " + node);
492- else
493- logger.info("Waiting for upcoming node: " + node);
503+ else
504+ logger.info("Waiting for upcoming node: " + node);
494505
495506 // In the case where the we've killed the last node in the cluster, if we haven't
496507 // tried doing an actual query, the driver won't realize that last node is dead until
@@ -502,7 +513,7 @@
502513
503514 InetAddress address;
504515 try {
505- address = InetAddress.getByName(node);
516+ address = InetAddress.getByName(node);
506517 } catch (Exception e) {
507518 // That's a problem but that's not *our* problem
508519 return;
@@ -512,11 +523,17 @@
512523 for (int i = 0; i < maxTry; ++i) {
513524 for (Host host : metadata.getAllHosts()) {
514525 if (host.getAddress().equals(address) && testHost(host, waitForDead)) {
515- try { Thread.sleep(10000); } catch (Exception e) {}
526+ try {
527+ Thread.sleep(10000);
528+ } catch (Exception e) {
529+ }
516530 return;
517531 }
518532 }
519- try { Thread.sleep(1000); } catch (Exception e) {}
533+ try {
534+ Thread.sleep(1000);
535+ } catch (Exception e) {
536+ }
520537 }
521538
522539 for (Host host : metadata.getAllHosts()) {
@@ -531,7 +548,7 @@
531548 }
532549 }
533550
534- if (waitForOut){
551+ if (waitForOut) {
535552 return;
536553 } else {
537554 logger.info(node + " is not part of the cluster after " + maxTry + 's');
@@ -560,12 +577,12 @@
560577
561578 public static Host findOrWaitForHost(final Cluster cluster, final String address, long duration, TimeUnit unit) {
562579 Host host = findHost(cluster, address);
563- if(host == null) {
580+ if (host == null) {
564581 final CountDownLatch addSignal = new CountDownLatch(1);
565582 Host.StateListener addListener = new StateListenerBase() {
566583 @Override
567584 public void onAdd(Host host) {
568- if(host.getAddress().getHostAddress().equals(address)) {
585+ if (host.getAddress().getHostAddress().equals(address)) {
569586 // for a new node, because of this we also listen for add events.
570587 addSignal.countDown();
571588 }
@@ -605,8 +622,8 @@
605622 ControlConnection controlConnection = cluster.manager.controlConnection;
606623 long durationNs = TimeUnit.NANOSECONDS.convert(duration, unit);
607624 long start = System.nanoTime();
608- while(System.nanoTime() - start < durationNs) {
609- if(controlConnection.isOpen()) {
625+ while (System.nanoTime() - start < durationNs) {
626+ if (controlConnection.isOpen()) {
610627 return controlConnection.connectedHost();
611628 }
612629 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
@@ -615,7 +632,7 @@
615632 }
616633
617634 public static HostConnectionPool poolOf(Session session, int hostNumber) {
618- SessionManager sessionManager = (SessionManager)session;
635+ SessionManager sessionManager = (SessionManager) session;
619636 return sessionManager.pools.get(findHost(session.getCluster(), hostNumber));
620637 }
621638
@@ -661,7 +678,7 @@
661678 String version = System.getProperty("cassandra.version");
662679 String[] versionArray = version.split("\\.|-");
663680 double major = Double.parseDouble(versionArray[0] + "." + versionArray[1]);
664- if(major < 2.0) {
681+ if (major < 2.0) {
665682 return ProtocolVersion.V1;
666683 } else if (major < 2.1) {
667684 return ProtocolVersion.V2;
@@ -688,9 +705,9 @@
688705 Host controlHost = cluster.manager.controlConnection.connectedHost();
689706 List<InetSocketAddress> singleAddress = Collections.singletonList(controlHost.getSocketAddress());
690707 return Cluster.builder()
691- .addContactPointsWithPorts(singleAddress)
692- .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
693- .build();
708+ .addContactPointsWithPorts(singleAddress)
709+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
710+ .build();
694711 }
695712
696713 /**
@@ -698,8 +715,8 @@
698715 */
699716 public static QueryOptions nonDebouncingQueryOptions() {
700717 return new QueryOptions().setRefreshNodeIntervalMillis(0)
701- .setRefreshNodeListIntervalMillis(0)
702- .setRefreshSchemaIntervalMillis(0);
718+ .setRefreshNodeListIntervalMillis(0)
719+ .setRefreshSchemaIntervalMillis(0);
703720 }
704721
705722 /**
modified driver-core/src/test/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGeneratorTest.java +17 −18
@@ -15,20 +15,19 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.List;
19-import java.util.concurrent.ExecutionException;
20-import java.util.concurrent.Executors;
21-import java.util.concurrent.TimeUnit;
22-
2318 import com.google.common.collect.Lists;
2419 import com.google.common.util.concurrent.Futures;
2520 import com.google.common.util.concurrent.ListenableFuture;
2621 import com.google.common.util.concurrent.ListeningExecutorService;
2722 import com.google.common.util.concurrent.MoreExecutors;
2823 import org.testng.annotations.Test;
29-import static org.testng.Assert.assertEquals;
30-import static org.testng.Assert.assertTrue;
31-import static org.testng.Assert.fail;
24+
25+import java.util.List;
26+import java.util.concurrent.ExecutionException;
27+import java.util.concurrent.Executors;
28+import java.util.concurrent.TimeUnit;
29+
30+import static org.testng.Assert.*;
3231
3332 public class ThreadLocalMonotonicTimestampGeneratorTest {
3433
@@ -46,15 +45,15 @@
4645 List<ListenableFuture<?>> futures = Lists.newArrayListWithExpectedSize(testThreadsCount);
4746 for (int i = 0; i < testThreadsCount; i++) {
4847 futures.add(executor.submit(
49- new Runnable() {
50- @Override
51- public void run() {
52- // Ensure that each thread gets the 1000 microseconds for the mocked millisecond value,
53- // in order
54- for (int i = 0; i < 1000; i++)
55- assertEquals(generator.next(), fixedTime * 1000 + i);
56- }
57- }));
48+ new Runnable() {
49+ @Override
50+ public void run() {
51+ // Ensure that each thread gets the 1000 microseconds for the mocked millisecond value,
52+ // in order
53+ for (int i = 0; i < 1000; i++)
54+ assertEquals(generator.next(), fixedTime * 1000 + i);
55+ }
56+ }));
5857 }
5958 executor.shutdown();
6059 executor.awaitTermination(1, TimeUnit.SECONDS);
@@ -64,7 +63,7 @@
6463 } catch (ExecutionException e) {
6564 Throwable cause = e.getCause();
6665 if (cause instanceof AssertionError)
67- throw (AssertionError)cause;
66+ throw (AssertionError) cause;
6867 else
6968 fail("Error in a test thread", cause);
7069 }
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +23 −23
@@ -74,9 +74,9 @@
7474 ccmBridge = CCMBridge.builder("test").withNodes(3).build();
7575 channelMonitor = new SocketChannelMonitor();
7676 nodes = Lists.newArrayList(
77- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
78- new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
79- new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
77+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
78+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
79+ new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
8080 );
8181
8282 PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, 8, 8);
@@ -91,33 +91,33 @@
9191
9292 @AfterClass(groups = "stress")
9393 public void afterClass() {
94- if(ccmBridge != null) {
94+ if (ccmBridge != null) {
9595 ccmBridge.stop();
9696 }
97- if(channelMonitor != null) {
97+ if (channelMonitor != null) {
9898 channelMonitor.stop();
9999 }
100- if(cluster != null) {
100+ if (cluster != null) {
101101 cluster.close();
102102 }
103103 }
104104
105105 /**
106- * <p>
106+ * <p/>
107107 * Validates that under extreme timeout conditions the driver is able to properly maintain connection pools in
108108 * addition to not leaking connections.
109- *
110- * <p>
109+ * <p/>
110+ * <p/>
111111 * Does the following:
112112 * <ol>
113- * <li>Creates a table and loads 30k rows in a single partition.</li>
114- * <li>Sets the connection and read timeout {@link SocketOptions} to very low values.</li>
115- * <li>Spawns workers that concurrently execute queries.</li>
116- * <li>For some duration, repeatedly measures number of open socket connections and warns if exceeded.</li>
117- * <li>After a duration, resets {@link SocketOptions} to defaults.</li>
118- * <li>Wait for 20 seconds for reaper to remove old connections and restore pools.</li>
119- * <li>Ensure pools are restored.</li>
120- * <li>Shutdown session and ensure that there remains only 1 open connection.</li>
113+ * <li>Creates a table and loads 30k rows in a single partition.</li>
114+ * <li>Sets the connection and read timeout {@link SocketOptions} to very low values.</li>
115+ * <li>Spawns workers that concurrently execute queries.</li>
116+ * <li>For some duration, repeatedly measures number of open socket connections and warns if exceeded.</li>
117+ * <li>After a duration, resets {@link SocketOptions} to defaults.</li>
118+ * <li>Wait for 20 seconds for reaper to remove old connections and restore pools.</li>
119+ * <li>Ensure pools are restored.</li>
120+ * <li>Shutdown session and ensure that there remains only 1 open connection.</li>
121121 * </ol>
122122 *
123123 * @test_category connection:connection_pool
@@ -163,7 +163,7 @@
163163
164164 // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing
165165 // factor between retrieving open connections and checking the reaper.
166- if(openChannels.size() > maxConnections) {
166+ if (openChannels.size() > maxConnections) {
167167 logger.warn("{} of open channels: {} exceeds maximum expected: {}. " +
168168 "This could be because there are connections to be cleaned up in the reaper.",
169169 openChannels.size(), maxConnections, openChannels);
@@ -179,7 +179,7 @@
179179 .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
180180
181181 logger.debug("Sleeping 20 seconds to allow connection reaper to clean up connections " +
182- "and for the pools to recover.");
182+ "and for the pools to recover.");
183183 Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
184184
185185 Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
@@ -249,7 +249,7 @@
249249 @Override
250250 public void run() {
251251
252- while(!stopped.get()) {
252+ while (!stopped.get()) {
253253 try {
254254 concurrentQueries.acquire();
255255 ResultSetFuture future = session.executeAsync(statement.bind("0"));
@@ -258,21 +258,21 @@
258258 @Override
259259 public void onSuccess(ResultSet result) {
260260 concurrentQueries.release();
261- if(executedQueries.incrementAndGet() % 1000 == 0)
261+ if (executedQueries.incrementAndGet() % 1000 == 0)
262262 logger.debug("Successfully executed {}. rows: {}", executedQueries.get(), result.getAvailableWithoutFetching());
263263 }
264264
265265 @Override
266266 public void onFailure(Throwable t) {
267267 concurrentQueries.release();
268- if(t instanceof NoHostAvailableException) {
268+ if (t instanceof NoHostAvailableException) {
269269 //logger.error("NHAE: {}", t.getMessage());
270270 } else {
271271 //logger.error("Exception", t);
272272 }
273273 }
274274 });
275- } catch(Exception e) {
275+ } catch (Exception e) {
276276 logger.error("Failure while submitting query.", e);
277277 }
278278 }

Next files