Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 2.2
Changeset91831b0b2feb8a6401699e6d76e368606862a581f10063b2b28c4df72bb8383f
Authorolim7t <omichallat+github@gmail.com> · 2015-07-15 21:19 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-07-16 10:50 +02:00
Parents37f021e9afe6, 6a5e82da7ff4

Browse the files at this changeset

132 files changed

modified README.md +4 −4
@@ -51,18 +51,18 @@
5151 - driver-examples: example applications using the other modules which are
5252 only meant for demonstration purposes.
5353
54-Please refer to the README of each module for more information.
55-
5654 **Community:**
5755
5856 - JIRA: https://datastax-oss.atlassian.net/browse/JAVA
5957 - MAILING LIST: https://groups.google.com/a/lists.datastax.com/forum/#!forum/java-driver-user
6058 - IRC: #datastax-drivers on [irc.freenode.net](http://freenode.net)
6159 - TWITTER: Follow the latest news about DataStax Drivers - [@olim7t](http://twitter.com/olim7t), [@mfiguiere](http://twitter.com/mfiguiere)
62-- DOCS: http://www.datastax.com/documentation/developer/java-driver/2.2/index.html
60+- DOCS: the [user guide](http://docs.datastax.com/en/developer/java-driver/2.2/java-driver/whatsNew2.html)
61+ has introductory material. We are progressively migrating the doc
62+ [here](features/) with more technical details.
6363 - API: http://www.datastax.com/drivers/java/2.2
6464
65-**Feeback requested:** help us focus our efforts, provide your input on the [Platform and Runtime Survey](http://goo.gl/forms/qwUE6qnL7U) (we kept it short).
65+**Feeback requested:** help us focus our efforts, provide your input on the [Platform and Runtime Survey](http://goo.gl/forms/qwUE6qnL7U) (we kept it short).
6666
6767
6868 ## Maven
modified changelog/README.md +116 −0
@@ -4,6 +4,48 @@
44
55 - [improvement] Rename DateWithoutTime to LocalDate (JAVA-810)
66
7+Merged from 2.1 branch:
8+
9+- [improvement] Improve QueryBuilder API for SELECT DISTINCT (JAVA-475)
10+- [improvement] Make NativeColumnType a top-level class (JAVA-715)
11+- [improvement] Expose ProtocolVersion#toInt (JAVA-700)
12+- [bug] Handle void return types in accessors (JAVA-542)
13+- [improvement] Create values() function for Insert builder using List (JAVA-225)
14+- [improvement] HashMap throws an OOM Exception when logging level is set to TRACE (JAVA-713)
15+- [bug] Support bind marker in QueryBuilder DELETE's list index (JAVA-679)
16+- [improvement] Expose KEYS and FULL indexing options in IndexMetadata (JAVA-732)
17+- [improvement] Allow @Enumerated in Accessor method parameters (JAVA-589)
18+- [improvement] Allow access to table metadata from Mapper (JAVA-554)
19+- [improvement] Provide a way to map computed fields (JAVA-661)
20+- [improvement] Ignore missing columns in mapper (JAVA-824)
21+- [bug] Preserve default timestamp for retries and speculative executions (JAVA-724)
22+- [improvement] Use same pool implementation for protocol v2 and v3
23+ (JAVA-738).
24+- [improvement] Support CONTAINS / CONTAINS KEY in QueryBuilder (JAVA-677)
25+- [improvement] Add USING options in mapper for delete and save
26+ operations (JAVA-477/JAVA-540)
27+- [improvement] Add mapper option to configure whether to save null fields (JAVA-473)
28+
29+Merged from 2.0 branch:
30+
31+- [bug] DowngradingConsistencyRetryPolicy ignores write timeouts (JAVA-737)
32+- [bug] Forbid bind marker in QueryBuilder add/append/prepend (JAVA-736)
33+- [bug] Prevent QueryBuilder.quote() from applying duplicate double quotes (JAVA-712)
34+- [bug] Prevent QueryBuilder from trying to serialize raw string (JAVA-688)
35+- [bug] Support bind marker in QueryBuilder DELETE's list index (JAVA-679)
36+- [improvement] Improve QueryBuilder API for SELECT DISTINCT (JAVA-475)
37+- [improvement] Create values() function for Insert builder using List (JAVA-225)
38+- [improvement] Warn when ReplicationStrategy encounters invalid
39+ replication factors (JAVA-702)
40+- [improvement] Add PoolingOptions method to set both core and max
41+ connections (JAVA-662).
42+- [improvement] Do not include epoll JAR in binary distribution (JAVA-766)
43+- [improvement] Optimize internal copies of Request objects (JAVA-726)
44+- [bug] Preserve tracing across retries (JAVA-815)
45+- [improvement] New RetryDecision.tryNextHost() (JAVA-709)
46+- [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733)
47+
48+
749 ### 2.2.0-rc1
850
951 - [new feature] Protocol V4 enum support (JAVA-783)
@@ -22,6 +64,49 @@
2264 - [improvement] Unify "Target" enum for schema elements (JAVA-782)
2365
2466
67+### 2.1.7
68+
69+- [improvement] Improve QueryBuilder API for SELECT DISTINCT (JAVA-475)
70+- [improvement] Make NativeColumnType a top-level class (JAVA-715)
71+- [improvement] Unify "Target" enum for schema elements (JAVA-782)
72+- [improvement] Expose ProtocolVersion#toInt (JAVA-700)
73+- [bug] Handle void return types in accessors (JAVA-542)
74+- [improvement] Create values() function for Insert builder using List (JAVA-225)
75+- [improvement] HashMap throws an OOM Exception when logging level is set to TRACE (JAVA-713)
76+- [bug] Support bind marker in QueryBuilder DELETE's list index (JAVA-679)
77+- [improvement] Expose KEYS and FULL indexing options in IndexMetadata (JAVA-732)
78+- [improvement] Allow @Enumerated in Accessor method parameters (JAVA-589)
79+- [improvement] Allow access to table metadata from Mapper (JAVA-554)
80+- [improvement] Provide a way to map computed fields (JAVA-661)
81+- [improvement] Ignore missing columns in mapper (JAVA-824)
82+- [bug] Preserve default timestamp for retries and speculative executions (JAVA-724)
83+- [improvement] Use same pool implementation for protocol v2 and v3
84+ (JAVA-738).
85+- [improvement] Support CONTAINS / CONTAINS KEY in QueryBuilder (JAVA-677)
86+- [improvement] Add USING options in mapper for delete and save
87+ operations (JAVA-477/JAVA-540)
88+- [improvement] Add mapper option to configure whether to save null fields (JAVA-473)
89+
90+Merged from 2.0 branch:
91+
92+- [bug] DowngradingConsistencyRetryPolicy ignores write timeouts (JAVA-737)
93+- [bug] Forbid bind marker in QueryBuilder add/append/prepend (JAVA-736)
94+- [bug] Prevent QueryBuilder.quote() from applying duplicate double quotes (JAVA-712)
95+- [bug] Prevent QueryBuilder from trying to serialize raw string (JAVA-688)
96+- [bug] Support bind marker in QueryBuilder DELETE's list index (JAVA-679)
97+- [improvement] Improve QueryBuilder API for SELECT DISTINCT (JAVA-475)
98+- [improvement] Create values() function for Insert builder using List (JAVA-225)
99+- [improvement] Warn when ReplicationStrategy encounters invalid
100+ replication factors (JAVA-702)
101+- [improvement] Add PoolingOptions method to set both core and max
102+ connections (JAVA-662).
103+- [improvement] Do not include epoll JAR in binary distribution (JAVA-766)
104+- [improvement] Optimize internal copies of Request objects (JAVA-726)
105+- [bug] Preserve tracing across retries (JAVA-815)
106+- [improvement] New RetryDecision.tryNextHost() (JAVA-709)
107+- [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733)
108+
109+
25110 ### 2.1.6
26111
27112 Merged from 2.0 branch:
@@ -234,6 +319,37 @@
234319 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
235320
236321
322+### 2.0.11 (in progress)
323+
324+- [bug] Fix SpeculativeExecutionPolicy.init() and close() are never called (JAVA-796)
325+- [improvement] Suppress unnecessary warning at shutdown (JAVA-710)
326+- [improvement] Allow DNS name with multiple A-records as contact point (#340)
327+- [bug] Allow tracing across multiple result pages (JAVA-794)
328+- [bug] DowngradingConsistencyRetryPolicy ignores write timeouts (JAVA-737)
329+- [bug] Forbid bind marker in QueryBuilder add/append/prepend (JAVA-736)
330+- [bug] Prevent QueryBuilder.quote() from applying duplicate double quotes (JAVA-712)
331+- [bug] Prevent QueryBuilder from trying to serialize raw string (JAVA-688)
332+- [bug] Support bind marker in QueryBuilder DELETE's list index (JAVA-679)
333+- [improvement] Improve QueryBuilder API for SELECT DISTINCT (JAVA-475)
334+- [improvement] Create values() function for Insert builder using List (JAVA-225)
335+- [improvement] Warn when ReplicationStrategy encounters invalid
336+ replication factors (JAVA-702)
337+- [improvement] Add PoolingOptions method to set both core and max
338+ connections (JAVA-662).
339+- [improvement] Do not include epoll JAR in binary distribution (JAVA-766)
340+- [improvement] Optimize internal copies of Request objects (JAVA-726)
341+- [bug] Preserve tracing across retries (JAVA-815)
342+- [improvement] New RetryDecision.tryNextHost() (JAVA-709)
343+- [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733)
344+
345+Merged from 2.0.10_fixes branch:
346+
347+- [improvement] Use Netty's pooled ByteBufAllocator by default (JAVA-756)
348+- [improvement] Expose "unsafe" paging state API (JAVA-759)
349+- [bug] Fix getObject by name (JAVA-767)
350+- [bug] Prevent race during pool initialization (JAVA-768)
351+
352+
237353 ### 2.0.10.1
238354
239355 - [improvement] Use Netty's pooled ByteBufAllocator by default (JAVA-756)
modified clirr-ignores.xml +1 −53
@@ -6,59 +6,7 @@
66 To update this file:
77 * run `mvn clirr:clirr` at the root directory
88 * check the reports in `<module>/target/site/clirr-report.html`
9- * add new differences if needed. Difference types are explained at http://mojo.codehaus.org/clirr-maven-plugin/examples/ignored-differences.html
9+ * add new differences if needed. Difference types are explained at http://www.mojohaus.org/clirr-maven-plugin/examples/ignored-differences.html
1010 -->
1111 <differences>
12- <difference>
13- <differenceType>7006</differenceType> <!-- return type changed -->
14- <className>com/datastax/driver/core/BatchStatement</className>
15- <method>com.datastax.driver.core.Statement setSerialConsistencyLevel(com.datastax.driver.core.ConsistencyLevel)</method>
16- <to>com.datastax.driver.core.BatchStatement</to>
17- <justification>A covariant return makes the API more fluent. It's unlikely that any client has extended this class</justification>
18- </difference>
19-
20- <difference>
21- <differenceType>6002</differenceType> <!-- no longer a compile-time constant -->
22- <className>com/datastax/driver/core/ProtocolOptions</className>
23- <field>NEWEST_SUPPORTED_PROTOCOL_VERSION</field>
24- <justification>It calls an enum's method that is known to have a constant result</justification>
25- </difference>
26-
27- <difference>
28- <differenceType>7004</differenceType> <!-- argument count changed -->
29- <className>com/datastax/driver/core/exceptions/UnsupportedFeatureException</className>
30- <method>UnsupportedFeatureException(java.lang.String)</method>
31- <justification>A client has no reason to call this constructor</justification>
32- </difference>
33-
34- <difference>
35- <differenceType>7012</differenceType> <!-- method added to interface -->
36- <className>com/datastax/driver/core/ResultSet</className>
37- <method>boolean wasApplied()</method>
38- <justification>This interface is not meant to be extended by clients</justification>
39- </difference>
40-
41- <difference>
42- <differenceType>7013</differenceType> <!-- abstract method added -->
43- <className>com/datastax/driver/core/RegularStatement</className>
44- <method>java.nio.ByteBuffer[] getValues(com.datastax.driver.core.ProtocolVersion)</method>
45- <justification>Indeed a breaking change, but extending this class from a client should be rarely needed</justification>
46- </difference>
47-
48- <difference>
49- <differenceType>7005</differenceType> <!-- argument type changed -->
50- <className>com/datastax/driver/core/SimpleStatement</className>
51- <method>java.nio.ByteBuffer[] getValues(int)</method>
52- <to>java.nio.ByteBuffer[] getValues(com.datastax.driver.core.ProtocolVersion)</to>
53- <justification>A backward compatible version has been added to the parent class RegularStatement</justification>
54- </difference>
55-
56- <difference>
57- <differenceType>7005</differenceType> <!-- argument type changed -->
58- <className>com/datastax/driver/core/querybuilder/*</className>
59- <method>java.nio.ByteBuffer[] getValues(int)</method>
60- <to>java.nio.ByteBuffer[] getValues(com.datastax.driver.core.ProtocolVersion)</to>
61- <justification>A backward compatible version has been added to the parent class RegularStatement</justification>
62- </difference>
63-
6412 </differences>
added driver-core/CHANGELOG.rst +1 −0
@@ -0,0 +1,1 @@
1+The changelog has moved `here <../changelog/>`_.
added driver-core/Upgrade_guide_to_2.0.rst +1 −0
@@ -0,0 +1,1 @@
1+The upgrade guide has moved `here <../upgrade_guide/>`_.
added driver-core/Upgrade_guide_to_2.1.rst +1 −0
@@ -0,0 +1,1 @@
1+The upgrade guide has moved `here <../upgrade_guide/>`_.
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +22 −18
@@ -281,14 +281,16 @@
281281 long timeout = getConfiguration().getSocketOptions().getConnectTimeoutMillis();
282282 Session session = connect();
283283 try {
284- ResultSetFuture future = session.executeAsync("USE " + keyspace);
285- // Note: using the connection timeout isn't perfectly correct, we should probably change that someday
286- Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
287- return session;
288- } catch (TimeoutException e) {
289- throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout));
290- } catch (ExecutionException e) {
291- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
284+ try {
285+ ResultSetFuture future = session.executeAsync("USE " + keyspace);
286+ // Note: using the connection timeout isn't perfectly correct, we should probably change that someday
287+ Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
288+ return session;
289+ } catch (TimeoutException e) {
290+ throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout));
291+ } catch (ExecutionException e) {
292+ throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
293+ }
292294 } catch (RuntimeException e) {
293295 session.close();
294296 throw e;
@@ -1114,14 +1116,14 @@
11141116 */
11151117 @Override
11161118 public Configuration getConfiguration() {
1117- Policies policies = new Policies(
1118- loadBalancingPolicy == null ? Policies.defaultLoadBalancingPolicy() : loadBalancingPolicy,
1119- Objects.firstNonNull(reconnectionPolicy, Policies.defaultReconnectionPolicy()),
1120- Objects.firstNonNull(retryPolicy, Policies.defaultRetryPolicy()),
1121- Objects.firstNonNull(addressTranslator, Policies.defaultAddressTranslator()),
1122- Objects.firstNonNull(timestampGenerator, Policies.defaultTimestampGenerator()),
1123- Objects.firstNonNull(speculativeExecutionPolicy, Policies.defaultSpeculativeExecutionPolicy())
1124- );
1119+ Policies policies = Policies.builder()
1120+ .withLoadBalancingPolicy(loadBalancingPolicy)
1121+ .withReconnectionPolicy(reconnectionPolicy)
1122+ .withRetryPolicy(retryPolicy)
1123+ .withAddressTranslator(addressTranslator)
1124+ .withTimestampGenerator(timestampGenerator)
1125+ .withSpeculativeExecutionPolicy(speculativeExecutionPolicy)
1126+ .build();
11251127 return new Configuration(policies,
11261128 new ProtocolOptions(port, protocolVersion, maxSchemaAgreementWaitSeconds, sslOptions, authProvider).setCompression(compression),
11271129 poolingOptions == null ? new PoolingOptions() : poolingOptions,
@@ -1300,6 +1302,8 @@
13001302 listener.onDown(host);
13011303 }
13021304
1305+ configuration.getPoolingOptions().setProtocolVersion(protocolVersion());
1306+
13031307 for (Host host : metadata.allHosts()) {
13041308 // If the host is down at this stage, it's a contact point that the control connection failed to reach.
13051309 // Reconnection attempts are already scheduled, and the LBP and listeners have been notified above.
@@ -1553,7 +1557,7 @@
15531557 } catch (ExecutionException e) {
15541558 Throwable t = e.getCause();
15551559 // That future is not really supposed to throw unexpected exceptions
1556- if (!(t instanceof InterruptedException))
1560+ if (!(t instanceof InterruptedException) && !(t instanceof CancellationException))
15571561 logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
15581562 }
15591563
@@ -1824,7 +1828,7 @@
18241828 } catch (ExecutionException e) {
18251829 Throwable t = e.getCause();
18261830 // That future is not really supposed to throw unexpected exceptions
1827- if (!(t instanceof InterruptedException))
1831+ if (!(t instanceof InterruptedException) && !(t instanceof CancellationException))
18281832 logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
18291833 }
18301834
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +112 −20
@@ -18,23 +18,27 @@
1818 import java.util.Arrays;
1919 import java.util.Collections;
2020 import java.util.HashMap;
21+import java.util.Iterator;
2122 import java.util.Map;
23+import java.util.Map.Entry;
2224
2325 /**
2426 * Describes a Column.
2527 */
2628 public class ColumnMetadata {
2729
28- private static final String COLUMN_NAME = "column_name";
29- private static final String VALIDATOR = "validator";
30- private static final String COMPONENT_INDEX = "component_index";
31- private static final String KIND = "type";
32-
33- private static final String INDEX_TYPE = "index_type";
34- private static final String INDEX_OPTIONS = "index_options";
35- private static final String INDEX_NAME = "index_name";
30+ static final String COLUMN_NAME = "column_name";
31+ static final String VALIDATOR = "validator";
32+ static final String COMPONENT_INDEX = "component_index";
33+ static final String KIND = "type";
34+
35+ static final String INDEX_TYPE = "index_type";
36+ static final String INDEX_OPTIONS = "index_options";
37+ static final String INDEX_NAME = "index_name";
3638 private static final String CUSTOM_INDEX_CLASS = "class_name";
3739
40+ private static final String INDEX_MAP_KEYS = "index_keys";
41+ private static final String INDEX_MAP_ENTRIES = "index_keys_and_values";
3842 private final TableMetadata table;
3943 private final String name;
4044 private final DataType type;
@@ -110,12 +114,16 @@
110114
111115 private final ColumnMetadata column;
112116 private final String name;
113- private final String customClassName; // will be null, unless it's a custom index
117+ private final Map<String, String> indexOptions;
114118
115- private IndexMetadata(ColumnMetadata column, String name, String customClassName) {
119+ private IndexMetadata(ColumnMetadata column, String name) {
120+ this(column, name, null);
121+ }
122+
123+ private IndexMetadata(ColumnMetadata column, String name, Map<String, String> indexOptions) {
116124 this.column = column;
117125 this.name = name;
118- this.customClassName = customClassName;
126+ this.indexOptions = indexOptions;
119127 }
120128
121129 /**
@@ -146,7 +154,7 @@
146154 * @return {@code true} if this metadata represents a custom index.
147155 */
148156 public boolean isCustomIndex() {
149- return customClassName != null;
157+ return getIndexClassName() != null;
150158 }
151159
152160 /**
@@ -156,7 +164,54 @@
156164 * custom index if {@code isCustomIndex() == true}, {@code null} otherwise.
157165 */
158166 public String getIndexClassName() {
159- return customClassName;
167+ return getOption(CUSTOM_INDEX_CLASS);
168+ }
169+
170+ /**
171+ * Return whether this index is a 'KEYS' index on a map, e.g.,
172+ * CREATE INDEX ON mytable (KEYS(mymap))
173+ *
174+ * @return {@code true} if this is a 'KEYS' index on a map.
175+ */
176+ public boolean isKeys() {
177+ return getOption(INDEX_MAP_KEYS) != null;
178+ }
179+
180+ /**
181+ * Return whether this index is a 'FULL' index on a frozen collection, e.g.,
182+ * CREATE INDEX ON mytable (FULL(mymap))
183+ *
184+ * @return {@code true} if this is a 'FULL' index on a frozen collection.
185+ */
186+ public boolean isFull() {
187+ /*
188+ * This check is analogous to the Cassandra counterpart
189+ * in IndexTarget#fromColumnDefinition.
190+ */
191+ return !isKeys()
192+ && !isEntries()
193+ && column.getType().isCollection()
194+ && column.getType().isFrozen();
195+ }
196+
197+ /**
198+ * Return whether this index is a 'ENTRIES' index on a map, e.g.,
199+ * CREATE INDEX ON mytable (ENTRIES(mymap))
200+ *
201+ * @return {@code true} if this is an 'ENTRIES' index on a map.
202+ */
203+ public boolean isEntries() {
204+ return getOption(INDEX_MAP_ENTRIES) != null;
205+ }
206+
207+ /**
208+ * Return the value for the given option name.
209+ *
210+ * @param name Option name
211+ * @return Option value
212+ */
213+ public String getOption(String name) {
214+ return indexOptions != null ? indexOptions.get(name) : null;
160215 }
161216
162217 /**
@@ -173,8 +228,45 @@
173228 String cfName = Metadata.escapeId(table.getName());
174229 String colName = Metadata.escapeId(column.getName());
175230 return isCustomIndex()
176- ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s';", name, ksName, cfName, colName, customClassName)
177- : String.format("CREATE INDEX %s ON %s.%s (%s);", name, ksName, cfName, colName);
231+ ? String.format("CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s' WITH OPTIONS = %s;",
232+ name, ksName, cfName, colName, getIndexClassName(), getOptionsAsCql())
233+ : String.format("CREATE INDEX %s ON %s.%s (%s);", name, ksName, cfName, getIndexFunction(colName));
234+ }
235+
236+ /**
237+ * Builds a string representation of the custom index options.
238+ *
239+ * @return String representation of the custom index options, similar to what Cassandra stores in
240+ * the 'index_options' column of the 'schema_columns' table in the 'system' keyspace.
241+ */
242+ private String getOptionsAsCql() {
243+ StringBuilder builder = new StringBuilder();
244+ builder.append("{");
245+ Iterator<Entry<String, String>> it = indexOptions.entrySet().iterator();
246+ while (it.hasNext()) {
247+ Entry<String, String> option = it.next();
248+ builder.append(String.format("'%s' : '%s'", option.getKey(), option.getValue()));
249+ if (it.hasNext())
250+ builder.append(", ");
251+ }
252+ builder.append("}");
253+ return builder.toString();
254+ }
255+
256+ /**
257+ * Wraps the column name with the appropriate index function (KEYS, FULL, ENTRIES),
258+ * if necessary.
259+ *
260+ * @return Column name wrapped with the appropriate index function.
261+ */
262+ private String getIndexFunction(String colName) {
263+ if (isKeys())
264+ return String.format("KEYS(%s)", colName);
265+ else if (isFull())
266+ return String.format("FULL(%s)", colName);
267+ else if (isEntries())
268+ return String.format("ENTRIES(%s)", colName);
269+ return colName;
178270 }
179271
180272 private static IndexMetadata build(ColumnMetadata column, Map<String, String> indexColumns) {
@@ -185,11 +277,11 @@
185277 if (type == null)
186278 return null;
187279
188- if (!type.equalsIgnoreCase("CUSTOM") || !indexColumns.containsKey(INDEX_OPTIONS))
189- return new IndexMetadata(column, indexColumns.get(INDEX_NAME), null);
280+ if (!indexColumns.containsKey(INDEX_OPTIONS))
281+ return new IndexMetadata(column, indexColumns.get(INDEX_NAME));
190282
191283 Map<String, String> indexOptions = SimpleJSONParser.parseStringMap(indexColumns.get(INDEX_OPTIONS));
192- return new IndexMetadata(column, indexColumns.get(INDEX_NAME), indexOptions.get(CUSTOM_INDEX_CLASS));
284+ return new IndexMetadata(column, indexColumns.get(INDEX_NAME), indexOptions);
193285 }
194286 }
195287
@@ -224,8 +316,8 @@
224316
225317 String name = row.getString(COLUMN_NAME);
226318 Kind kind = version.getMajor() < 2 || row.isNull(KIND)
227- ? Kind.REGULAR
228- : Enum.valueOf(Kind.class, row.getString(KIND).toUpperCase());
319+ ? Kind.REGULAR
320+ : Enum.valueOf(Kind.class, row.getString(KIND).toUpperCase());
229321 int componentIndex = row.isNull(COMPONENT_INDEX) ? 0 : row.getInt(COMPONENT_INDEX);
230322 String validatorStr = row.getString(VALIDATOR);
231323 boolean reversed = CassandraTypeParser.isReversed(validatorStr);
modified driver-core/src/main/java/com/datastax/driver/core/Configuration.java +1 −1
@@ -46,7 +46,7 @@
4646 * Creates a configuration object.
4747 */
4848 public Configuration() {
49- this(new Policies(),
49+ this(Policies.builder().build(),
5050 new ProtocolOptions(),
5151 new PoolingOptions(),
5252 new SocketOptions(),
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +4 −13
@@ -835,8 +835,6 @@
835835 final Queue<FlushItem> queued = new ConcurrentLinkedQueue<FlushItem>();
836836 final AtomicBoolean running = new AtomicBoolean(false);
837837 final HashSet<Channel> channels = new HashSet<Channel>();
838- final List<FlushItem> flushed = Lists.newArrayListWithExpectedSize(50);
839- int runsSinceFlush = 0;
840838 int runsWithNoWork = 0;
841839
842840 private Flusher(EventLoop eventLoop) {
@@ -859,20 +857,13 @@
859857 while (null != (flush = queued.poll())) {
860858 channels.add(flush.channel);
861859 flush.channel.write(flush.request).addListener(flush.listener);
862- flushed.add(flush);
863860 doneWork = true;
864861 }
865862
866- runsSinceFlush++;
867-
868- if (!doneWork || runsSinceFlush > 2 || flushed.size() > 50) {
869- for (Channel channel : channels)
870- channel.flush();
871-
872- channels.clear();
873- flushed.clear();
874- runsSinceFlush = 0;
875- }
863+ // Always flush what we have (don't artificially delay to try to coalesce more messages)
864+ for (Channel channel : channels)
865+ channel.flush();
866+ channels.clear();
876867
877868 if (doneWork) {
878869 runsWithNoWork = 0;
deleted driver-core/src/main/java/com/datastax/driver/core/DynamicConnectionPool.java +0 −602
@@ -1,602 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-
19-import java.util.*;
20-import java.util.concurrent.*;
21-import java.util.concurrent.atomic.AtomicInteger;
22-import java.util.concurrent.locks.*;
23-
24-import com.google.common.annotations.VisibleForTesting;
25-import com.google.common.collect.Lists;
26-import com.google.common.util.concurrent.*;
27-import org.slf4j.Logger;
28-import org.slf4j.LoggerFactory;
29-
30-import com.datastax.driver.core.exceptions.AuthenticationException;
31-import com.datastax.driver.core.utils.MoreFutures;
32-
33-import static com.datastax.driver.core.Connection.State.*;
34-
35-/**
36- * A connection pool with a varying number of connections.
37- *
38- * This is used with {@link ProtocolVersion#V2} and lower.
39- */
40-class DynamicConnectionPool extends HostConnectionPool {
41-
42- private static final Logger logger = LoggerFactory.getLogger(DynamicConnectionPool.class);
43-
44- private static final int MAX_SIMULTANEOUS_CREATION = 1;
45-
46- // When a request timeout, we may never release its stream ID. So over time, a given connection
47- // may get less an less available streams. When the number of available ones go below the
48- // following threshold, we just replace the connection by a new one.
49- private static final int MIN_AVAILABLE_STREAMS = 96;
50-
51- final List<Connection> connections;
52- private final AtomicInteger open;
53- /** The total number of in-flight requests on all connections of this pool. */
54- final AtomicInteger totalInFlight = new AtomicInteger();
55- /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
56- private final AtomicInteger maxTotalInFlight = new AtomicInteger();
57-
58- @VisibleForTesting
59- final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
60-
61- private volatile int waiter = 0;
62- private final Lock waitLock = new ReentrantLock(true);
63- private final Condition hasAvailableConnection = waitLock.newCondition();
64-
65- private final Runnable newConnectionTask;
66-
67- private final AtomicInteger scheduledForCreation = new AtomicInteger();
68-
69- public DynamicConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
70- super(host, hostDistance, manager);
71-
72- this.newConnectionTask = new Runnable() {
73- @Override
74- public void run() {
75- addConnectionIfUnderMaximum();
76- scheduledForCreation.decrementAndGet();
77- }
78- };
79-
80- this.connections = new CopyOnWriteArrayList<Connection>();
81- this.open = new AtomicInteger();
82- }
83-
84- @Override
85- ListenableFuture<Void> initAsync(Connection reusedConnection) {
86- // Create initial core connections
87- int capacity = options().getCoreConnectionsPerHost(hostDistance);
88- final List<Connection> connections = Lists.newArrayListWithCapacity(capacity);
89- final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
90- for (int i = 0; i < capacity; i++) {
91- Connection connection;
92- ListenableFuture<Void> connectionFuture;
93- // reuse the existing connection only once
94- if (reusedConnection != null && reusedConnection.setPool(this)) {
95- connection = reusedConnection;
96- connectionFuture = MoreFutures.VOID_SUCCESS;
97- } else {
98- connection = manager.connectionFactory().newConnection(this);
99- connectionFuture = connection.initAsync();
100- }
101- reusedConnection = null;
102- connections.add(connection);
103- connectionFutures.add(connectionFuture);
104- }
105-
106- Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
107-
108- ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
109-
110- final SettableFuture<Void> initFuture = SettableFuture.create();
111- Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
112- @Override
113- public void onSuccess(List<Void> l) {
114- DynamicConnectionPool.this.connections.addAll(connections);
115- open.set(l.size());
116- if (isClosed()) {
117- initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
118- // we're not sure if closeAsync() saw the connections, so ensure they get closed
119- forceClose(connections);
120- } else {
121- logger.trace("Created connection pool to host {}", host);
122- phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
123- initFuture.set(null);
124- }
125- }
126-
127- @Override
128- public void onFailure(Throwable t) {
129- phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED);
130- forceClose(connections);
131- initFuture.setException(t);
132- }
133- }, initExecutor);
134- return initFuture;
135- }
136-
137- // Clean up if we got an error at construction time but still created part of the core connections
138- private void forceClose(List<Connection> connections) {
139- for (Connection connection : connections) {
140- connection.closeAsync().force();
141- }
142- }
143-
144- private PoolingOptions options() {
145- return manager.configuration().getPoolingOptions();
146- }
147-
148- @Override
149- public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
150- Phase phase = this.phase.get();
151- if (phase != Phase.READY)
152- // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
153- // That being said, maybe having a specific exception could be cleaner.
154- throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
155-
156- if (connections.isEmpty()) {
157- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
158- // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
159- // protect against creating connection in excess of core too quickly
160- scheduledForCreation.incrementAndGet();
161- manager.blockingExecutor().submit(newConnectionTask);
162- }
163- Connection c = waitForConnection(timeout, unit);
164- totalInFlight.incrementAndGet();
165- c.setKeyspace(manager.poolsState.keyspace);
166- return c;
167- }
168-
169- int minInFlight = Integer.MAX_VALUE;
170- Connection leastBusy = null;
171- for (Connection connection : connections) {
172- int inFlight = connection.inFlight.get();
173- if (inFlight < minInFlight) {
174- minInFlight = inFlight;
175- leastBusy = connection;
176- }
177- }
178-
179- if (leastBusy == null) {
180- // We could have raced with a shutdown since the last check
181- if (isClosed())
182- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
183- // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
184- // the previous check to connections and now. But in that case, the line above will have trigger the creation of
185- // a new connection, so just wait that connection and move on
186- leastBusy = waitForConnection(timeout, unit);
187- } else {
188- while (true) {
189- int inFlight = leastBusy.inFlight.get();
190-
191- if (inFlight >= leastBusy.maxAvailableStreams()) {
192- leastBusy = waitForConnection(timeout, unit);
193- break;
194- }
195-
196- if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
197- break;
198- }
199- }
200-
201- int totalInFlightCount = totalInFlight.incrementAndGet();
202- // update max atomically:
203- while (true) {
204- int oldMax = maxTotalInFlight.get();
205- if (totalInFlightCount <= oldMax || maxTotalInFlight.compareAndSet(oldMax, totalInFlightCount))
206- break;
207- }
208-
209- int connectionCount = open.get() + scheduledForCreation.get();
210- if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
211- // Add a connection if we fill the first n-1 connections and almost fill the last one
212- int currentCapacity = (connectionCount - 1) * StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2
213- + options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance);
214- if (totalInFlightCount > currentCapacity)
215- maybeSpawnNewConnection();
216- }
217-
218- leastBusy.setKeyspace(manager.poolsState.keyspace);
219- return leastBusy;
220- }
221-
222- private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException {
223- waitLock.lock();
224- waiter++;
225- try {
226- hasAvailableConnection.await(timeout, unit);
227- } finally {
228- waiter--;
229- waitLock.unlock();
230- }
231- }
232-
233- private void signalAvailableConnection() {
234- // Quick check if it's worth signaling to avoid locking
235- if (waiter == 0)
236- return;
237-
238- waitLock.lock();
239- try {
240- hasAvailableConnection.signal();
241- } finally {
242- waitLock.unlock();
243- }
244- }
245-
246- private void signalAllAvailableConnection() {
247- // Quick check if it's worth signaling to avoid locking
248- if (waiter == 0)
249- return;
250-
251- waitLock.lock();
252- try {
253- hasAvailableConnection.signalAll();
254- } finally {
255- waitLock.unlock();
256- }
257- }
258-
259- private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
260- if (timeout == 0)
261- throw new TimeoutException();
262-
263- long start = System.nanoTime();
264- long remaining = timeout;
265- do {
266- try {
267- awaitAvailableConnection(remaining, unit);
268- } catch (InterruptedException e) {
269- Thread.currentThread().interrupt();
270- // If we're interrupted fine, check if there is a connection available but stop waiting otherwise
271- timeout = 0; // this will make us stop the loop if we don't get a connection right away
272- }
273-
274- if (isClosed())
275- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
276-
277- int minInFlight = Integer.MAX_VALUE;
278- Connection leastBusy = null;
279- for (Connection connection : connections) {
280- int inFlight = connection.inFlight.get();
281- if (inFlight < minInFlight) {
282- minInFlight = inFlight;
283- leastBusy = connection;
284- }
285- }
286-
287- // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next
288- // iteration anyway
289- if (leastBusy != null) {
290- while (true) {
291- int inFlight = leastBusy.inFlight.get();
292-
293- if (inFlight >= leastBusy.maxAvailableStreams())
294- break;
295-
296- if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
297- return leastBusy;
298- }
299- }
300-
301- remaining = timeout - Cluster.timeSince(start, unit);
302- } while (remaining > 0);
303-
304- throw new TimeoutException();
305- }
306-
307- @Override
308- public void returnConnection(Connection connection) {
309- connection.inFlight.decrementAndGet();
310- totalInFlight.decrementAndGet();
311-
312- if (isClosed()) {
313- close(connection);
314- return;
315- }
316-
317- if (connection.isDefunct()) {
318- // As part of making it defunct, we have already replaced it or
319- // closed the pool.
320- return;
321- }
322-
323- if (connection.state.get() != TRASHED) {
324- if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
325- replaceConnection(connection);
326- } else {
327- signalAvailableConnection();
328- }
329- }
330- }
331-
332- // Trash the connection and create a new one, but we don't call trashConnection
333- // directly because we want to make sure the connection is always trashed.
334- private void replaceConnection(Connection connection) {
335- if (!connection.state.compareAndSet(OPEN, TRASHED))
336- return;
337- open.decrementAndGet();
338- maybeSpawnNewConnection();
339- connection.maxIdleTime = Long.MIN_VALUE;
340- doTrashConnection(connection);
341- }
342-
343- private boolean trashConnection(Connection connection) {
344- if (!connection.state.compareAndSet(OPEN, TRASHED))
345- return true;
346-
347- // First, make sure we don't go below core connections
348- for (;;) {
349- int opened = open.get();
350- if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
351- connection.state.set(OPEN);
352- return false;
353- }
354-
355- if (open.compareAndSet(opened, opened - 1))
356- break;
357- }
358- logger.trace("Trashing {}", connection);
359- connection.maxIdleTime = System.currentTimeMillis() + options().getIdleTimeoutSeconds() * 1000;
360- doTrashConnection(connection);
361- return true;
362- }
363-
364- private void doTrashConnection(Connection connection) {
365- connections.remove(connection);
366- trash.add(connection);
367- }
368-
369- private boolean addConnectionIfUnderMaximum() {
370-
371- // First, make sure we don't cross the allowed limit of open connections
372- for(;;) {
373- int opened = open.get();
374- if (opened >= options().getMaxConnectionsPerHost(hostDistance))
375- return false;
376-
377- if (open.compareAndSet(opened, opened + 1))
378- break;
379- }
380-
381- if (phase.get() != Phase.READY) {
382- open.decrementAndGet();
383- return false;
384- }
385-
386- // Now really open the connection
387- try {
388- Connection newConnection = tryResurrectFromTrash();
389- if (newConnection == null) {
390- logger.debug("Creating new connection on busy pool to {}", host);
391- newConnection = manager.connectionFactory().open(this);
392- }
393- connections.add(newConnection);
394-
395- newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN
396-
397- // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
398- if (isClosed() && !newConnection.isClosed()) {
399- close(newConnection);
400- open.decrementAndGet();
401- return false;
402- }
403-
404- signalAvailableConnection();
405- return true;
406- } catch (InterruptedException e) {
407- Thread.currentThread().interrupt();
408- // Skip the open but ignore otherwise
409- open.decrementAndGet();
410- return false;
411- } catch (ConnectionException e) {
412- open.decrementAndGet();
413- logger.debug("Connection error to {} while creating additional connection", host);
414- return false;
415- } catch (AuthenticationException e) {
416- // This shouldn't really happen in theory
417- open.decrementAndGet();
418- logger.error("Authentication error while creating additional connection (error is: {})", e.getMessage());
419- return false;
420- } catch (UnsupportedProtocolVersionException e) {
421- // This shouldn't happen since we shouldn't have been able to connect in the first place
422- open.decrementAndGet();
423- logger.error("UnsupportedProtocolVersionException error while creating additional connection (error is: {})", e.getMessage());
424- return false;
425- } catch (ClusterNameMismatchException e) {
426- open.decrementAndGet();
427- logger.error("ClusterNameMismatchException error while creating additional connection (error is: {})", e.getMessage());
428- return false;
429- }
430- }
431-
432- private Connection tryResurrectFromTrash() {
433- long highestMaxIdleTime = System.currentTimeMillis();
434- Connection chosen = null;
435-
436- while (true) {
437- for (Connection connection : trash)
438- if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > MIN_AVAILABLE_STREAMS) {
439- chosen = connection;
440- highestMaxIdleTime = connection.maxIdleTime;
441- }
442-
443- if (chosen == null)
444- return null;
445- else if (chosen.state.compareAndSet(TRASHED, RESURRECTING))
446- break;
447- }
448- logger.trace("Resurrecting {}", chosen);
449- trash.remove(chosen);
450- return chosen;
451- }
452-
453- private void maybeSpawnNewConnection() {
454- while (true) {
455- int inCreation = scheduledForCreation.get();
456- if (inCreation >= MAX_SIMULTANEOUS_CREATION)
457- return;
458- if (scheduledForCreation.compareAndSet(inCreation, inCreation + 1))
459- break;
460- }
461-
462- manager.blockingExecutor().submit(newConnectionTask);
463- }
464-
465- @Override
466- void replaceDefunctConnection(final Connection connection) {
467- if (connection.state.compareAndSet(OPEN, GONE))
468- open.decrementAndGet();
469- if (connections.remove(connection))
470- manager.blockingExecutor().submit(new Runnable() {
471- @Override
472- public void run() {
473- addConnectionIfUnderMaximum();
474- }
475- });
476- }
477-
478- @Override
479- void cleanupIdleConnections(long now) {
480- if (isClosed())
481- return;
482-
483- shrinkIfBelowCapacity();
484- cleanupTrash(now);
485- }
486-
487- /** If we have more active connections than needed, trash some of them */
488- private void shrinkIfBelowCapacity() {
489- int currentLoad = maxTotalInFlight.getAndSet(totalInFlight.get());
490-
491- int needed = currentLoad / StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2 + 1;
492- if (currentLoad % StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2 > options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance))
493- needed += 1;
494- needed = Math.max(needed, options().getCoreConnectionsPerHost(hostDistance));
495- int actual = open.get();
496- int toTrash = Math.max(0, actual - needed);
497-
498- logger.trace("Current inFlight = {}, {} connections needed, {} connections available, trashing {}",
499- currentLoad, needed, actual, toTrash);
500-
501- if (toTrash <= 0)
502- return;
503-
504- for (Connection connection : connections)
505- if (trashConnection(connection)) {
506- toTrash -= 1;
507- if (toTrash == 0)
508- return;
509- }
510- }
511-
512- /** Close connections that have been sitting in the trash for too long */
513- private void cleanupTrash(long now) {
514- for (Connection connection : trash) {
515- if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
516- if (connection.inFlight.get() == 0) {
517- logger.trace("Cleaning up {}", connection);
518- trash.remove(connection);
519- close(connection);
520- } else {
521- // Given that idleTimeout >> request timeout, all outstanding requests should
522- // have finished by now, so we should not get here.
523- // Restore the status so that it's retried on the next cleanup.
524- connection.state.set(TRASHED);
525- }
526- }
527- }
528- }
529-
530- private void close(final Connection connection) {
531- connection.closeAsync();
532- }
533-
534- protected CloseFuture makeCloseFuture() {
535- // Wake up all threads that wait
536- signalAllAvailableConnection();
537-
538- return new CloseFuture.Forwarding(discardAvailableConnections());
539- }
540-
541- private List<CloseFuture> discardAvailableConnections() {
542- // Note: if this gets called before initialization has completed, both connections and trash will be empty,
543- // so this will return an empty list
544-
545- List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size());
546-
547- for (final Connection connection : connections) {
548- CloseFuture future = connection.closeAsync();
549- future.addListener(new Runnable() {
550- public void run() {
551- if (connection.state.compareAndSet(OPEN, GONE))
552- open.decrementAndGet();
553- }
554- }, MoreExecutors.sameThreadExecutor());
555- futures.add(future);
556- }
557-
558- // Some connections in the trash might still be open if they hadn't reached their idle timeout
559- for (Connection connection : trash)
560- futures.add(connection.closeAsync());
561-
562- return futures;
563- }
564-
565- // This creates connections if we have less than core connections (if we
566- // have more than core, connection will just get trash when we can).
567- @Override
568- public void ensureCoreConnections() {
569- if (isClosed())
570- return;
571-
572- // Note: this process is a bit racy, but it doesn't matter since we're still guaranteed to not create
573- // more connection than maximum (and if we create more than core connection due to a race but this isn't
574- // justified by the load, the connection in excess will be quickly trashed anyway)
575- int opened = open.get();
576- for (int i = opened; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
577- // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
578- // protect against creating connection in excess of core too quickly
579- scheduledForCreation.incrementAndGet();
580- manager.blockingExecutor().submit(newConnectionTask);
581- }
582- }
583-
584- @Override
585- public int opened() {
586- return open.get();
587- }
588-
589- @Override
590- int trashed() {
591- return trash.size();
592- }
593-
594- @Override
595- public int inFlightQueriesCount() {
596- int count = 0;
597- for (Connection connection : connections) {
598- count += connection.inFlight.get();
599- }
600- return count;
601- }
602-}
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +554 −35
@@ -15,46 +15,86 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.TimeUnit;
19-import java.util.concurrent.TimeoutException;
18+import java.util.ArrayList;
19+import java.util.List;
20+import java.util.Set;
21+import java.util.concurrent.*;
22+import java.util.concurrent.atomic.AtomicInteger;
2023 import java.util.concurrent.atomic.AtomicReference;
24+import java.util.concurrent.locks.Condition;
25+import java.util.concurrent.locks.Lock;
26+import java.util.concurrent.locks.ReentrantLock;
2127
22-import com.google.common.util.concurrent.ListenableFuture;
28+import com.google.common.annotations.VisibleForTesting;
29+import com.google.common.collect.Lists;
30+import com.google.common.util.concurrent.*;
31+import org.slf4j.Logger;
32+import org.slf4j.LoggerFactory;
2333
24-/**
25- * A set of connections to a live host.
26- *
27- * We use different strategies depending of the protocol version in use.
28- */
29-abstract class HostConnectionPool {
34+import com.datastax.driver.core.exceptions.AuthenticationException;
35+import com.datastax.driver.core.utils.MoreFutures;
3036
31- static HostConnectionPool newInstance(Host host, HostDistance hostDistance, SessionManager manager, ProtocolVersion version) {
32- switch (version) {
33- case V1:
34- case V2:
35- return new DynamicConnectionPool(host, hostDistance, manager);
36- case V3:
37- case V4:
38- return new SingleConnectionPool(host, hostDistance, manager);
39- default:
40- throw version.unsupported();
41- }
42- }
37+import static com.datastax.driver.core.Connection.State.GONE;
38+import static com.datastax.driver.core.Connection.State.OPEN;
39+import static com.datastax.driver.core.Connection.State.RESURRECTING;
40+import static com.datastax.driver.core.Connection.State.TRASHED;
41+
42+class HostConnectionPool {
43+
44+ private static final Logger logger = LoggerFactory.getLogger(HostConnectionPool.class);
45+
46+ private static final int MAX_SIMULTANEOUS_CREATION = 1;
4347
4448 final Host host;
4549 volatile HostDistance hostDistance;
4650 protected final SessionManager manager;
4751
52+ final List<Connection> connections;
53+ private final AtomicInteger open;
54+ /** The total number of in-flight requests on all connections of this pool. */
55+ final AtomicInteger totalInFlight = new AtomicInteger();
56+ /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
57+ private final AtomicInteger maxTotalInFlight = new AtomicInteger();
58+ @VisibleForTesting
59+ final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
60+
61+ private volatile int waiter = 0;
62+ private final Lock waitLock = new ReentrantLock(true);
63+ private final Condition hasAvailableConnection = waitLock.newCondition();
64+
65+ private final Runnable newConnectionTask;
66+
67+ private final AtomicInteger scheduledForCreation = new AtomicInteger();
68+
4869 protected final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
4970
50- protected enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING }
71+ private enum Phase {INITIALIZING, READY, INIT_FAILED, CLOSING}
72+
5173 protected final AtomicReference<Phase> phase = new AtomicReference<Phase>(Phase.INITIALIZING);
5274
53- protected HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
75+ // When a request times out, we may never release its stream ID. So over time, a given connection
76+ // may get less an less available streams. When the number of available ones go below the
77+ // following threshold, we just replace the connection by a new one.
78+ private final int minAllowedStreams;
79+
80+ public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
5481 assert hostDistance != HostDistance.IGNORED;
5582 this.host = host;
5683 this.hostDistance = hostDistance;
5784 this.manager = manager;
85+
86+ this.newConnectionTask = new Runnable() {
87+ @Override
88+ public void run() {
89+ addConnectionIfUnderMaximum();
90+ scheduledForCreation.decrementAndGet();
91+ }
92+ };
93+
94+ this.connections = new CopyOnWriteArrayList<Connection>();
95+ this.open = new AtomicInteger();
96+
97+ this.minAllowedStreams = options().getMaxRequestsPerConnection(hostDistance) * 3 / 4;
5898 }
5999
60100 /**
@@ -62,25 +102,451 @@
62102 * reuse as part of this pool. Might be null or already used by another
63103 * pool.
64104 */
65- abstract ListenableFuture<Void> initAsync(Connection reusedConnection);
105+ ListenableFuture<Void> initAsync(Connection reusedConnection) {
106+ // Create initial core connections
107+ int capacity = options().getCoreConnectionsPerHost(hostDistance);
108+ final List<Connection> connections = Lists.newArrayListWithCapacity(capacity);
109+ final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
110+ for (int i = 0; i < capacity; i++) {
111+ Connection connection;
112+ ListenableFuture<Void> connectionFuture;
113+ // reuse the existing connection only once
114+ if (reusedConnection != null && reusedConnection.setPool(this)) {
115+ connection = reusedConnection;
116+ connectionFuture = MoreFutures.VOID_SUCCESS;
117+ } else {
118+ connection = manager.connectionFactory().newConnection(this);
119+ connectionFuture = connection.initAsync();
120+ }
121+ reusedConnection = null;
122+ connections.add(connection);
123+ connectionFutures.add(connectionFuture);
124+ }
125+
126+ Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
127+
128+ ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
129+
130+ final SettableFuture<Void> initFuture = SettableFuture.create();
131+ Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
132+ @Override
133+ public void onSuccess(List<Void> l) {
134+ HostConnectionPool.this.connections.addAll(connections);
135+ open.set(l.size());
136+ if (isClosed()) {
137+ initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
138+ // we're not sure if closeAsync() saw the connections, so ensure they get closed
139+ forceClose(connections);
140+ } else {
141+ logger.trace("Created connection pool to host {}", host);
142+ phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
143+ initFuture.set(null);
144+ }
145+ }
146+
147+ @Override
148+ public void onFailure(Throwable t) {
149+ phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED);
150+ forceClose(connections);
151+ initFuture.setException(t);
152+ }
153+ }, initExecutor);
154+ return initFuture;
155+ }
156+
157+ // Clean up if we got an error at construction time but still created part of the core connections
158+ private void forceClose(List<Connection> connections) {
159+ for (Connection connection : connections) {
160+ connection.closeAsync().force();
161+ }
162+ }
163+
164+ private PoolingOptions options() {
165+ return manager.configuration().getPoolingOptions();
166+ }
167+
168+ public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
169+ Phase phase = this.phase.get();
170+ if (phase != Phase.READY)
171+ // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
172+ // That being said, maybe having a specific exception could be cleaner.
173+ throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
174+
175+ if (connections.isEmpty()) {
176+ for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
177+ // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
178+ // protect against creating connection in excess of core too quickly
179+ scheduledForCreation.incrementAndGet();
180+ manager.blockingExecutor().submit(newConnectionTask);
181+ }
182+ Connection c = waitForConnection(timeout, unit);
183+ totalInFlight.incrementAndGet();
184+ c.setKeyspace(manager.poolsState.keyspace);
185+ return c;
186+ }
187+
188+ int minInFlight = Integer.MAX_VALUE;
189+ Connection leastBusy = null;
190+ for (Connection connection : connections) {
191+ int inFlight = connection.inFlight.get();
192+ if (inFlight < minInFlight) {
193+ minInFlight = inFlight;
194+ leastBusy = connection;
195+ }
196+ }
197+
198+ if (leastBusy == null) {
199+ // We could have raced with a shutdown since the last check
200+ if (isClosed())
201+ throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
202+ // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
203+ // the previous check to connections and now. But in that case, the line above will have trigger the creation of
204+ // a new connection, so just wait that connection and move on
205+ leastBusy = waitForConnection(timeout, unit);
206+ } else {
207+ while (true) {
208+ int inFlight = leastBusy.inFlight.get();
209+
210+ if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
211+ leastBusy = waitForConnection(timeout, unit);
212+ break;
213+ }
214+
215+ if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
216+ break;
217+ }
218+ }
219+
220+ int totalInFlightCount = totalInFlight.incrementAndGet();
221+ // update max atomically:
222+ while (true) {
223+ int oldMax = maxTotalInFlight.get();
224+ if (totalInFlightCount <= oldMax || maxTotalInFlight.compareAndSet(oldMax, totalInFlightCount))
225+ break;
226+ }
227+
228+ int connectionCount = open.get() + scheduledForCreation.get();
229+ if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
230+ // Add a connection if we fill the first n-1 connections and almost fill the last one
231+ int currentCapacity = (connectionCount - 1) * options().getMaxRequestsPerConnection(hostDistance)
232+ + options().getNewConnectionThreshold(hostDistance);
233+ if (totalInFlightCount > currentCapacity)
234+ maybeSpawnNewConnection();
235+ }
236+
237+ leastBusy.setKeyspace(manager.poolsState.keyspace);
238+ return leastBusy;
239+ }
240+
241+ private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException {
242+ waitLock.lock();
243+ waiter++;
244+ try {
245+ hasAvailableConnection.await(timeout, unit);
246+ } finally {
247+ waiter--;
248+ waitLock.unlock();
249+ }
250+ }
251+
252+ private void signalAvailableConnection() {
253+ // Quick check if it's worth signaling to avoid locking
254+ if (waiter == 0)
255+ return;
256+
257+ waitLock.lock();
258+ try {
259+ hasAvailableConnection.signal();
260+ } finally {
261+ waitLock.unlock();
262+ }
263+ }
264+
265+ private void signalAllAvailableConnection() {
266+ // Quick check if it's worth signaling to avoid locking
267+ if (waiter == 0)
268+ return;
269+
270+ waitLock.lock();
271+ try {
272+ hasAvailableConnection.signalAll();
273+ } finally {
274+ waitLock.unlock();
275+ }
276+ }
277+
278+ private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
279+ if (timeout == 0)
280+ throw new TimeoutException();
281+
282+ long start = System.nanoTime();
283+ long remaining = timeout;
284+ do {
285+ try {
286+ awaitAvailableConnection(remaining, unit);
287+ } catch (InterruptedException e) {
288+ Thread.currentThread().interrupt();
289+ // If we're interrupted fine, check if there is a connection available but stop waiting otherwise
290+ timeout = 0; // this will make us stop the loop if we don't get a connection right away
291+ }
292+
293+ if (isClosed())
294+ throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
295+
296+ int minInFlight = Integer.MAX_VALUE;
297+ Connection leastBusy = null;
298+ for (Connection connection : connections) {
299+ int inFlight = connection.inFlight.get();
300+ if (inFlight < minInFlight) {
301+ minInFlight = inFlight;
302+ leastBusy = connection;
303+ }
304+ }
305+
306+ // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next
307+ // iteration anyway
308+ if (leastBusy != null) {
309+ while (true) {
310+ int inFlight = leastBusy.inFlight.get();
311+
312+ if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance)))
313+ break;
314+
315+ if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
316+ return leastBusy;
317+ }
318+ }
319+
320+ remaining = timeout - Cluster.timeSince(start, unit);
321+ } while (remaining > 0);
322+
323+ throw new TimeoutException();
324+ }
66325
67- abstract Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException;
326+ public void returnConnection(Connection connection) {
327+ connection.inFlight.decrementAndGet();
328+ totalInFlight.decrementAndGet();
68329
69- abstract void returnConnection(Connection connection);
330+ if (isClosed()) {
331+ close(connection);
332+ return;
333+ }
334+
335+ if (connection.isDefunct()) {
336+ // As part of making it defunct, we have already replaced it or
337+ // closed the pool.
338+ return;
339+ }
340+
341+ if (connection.state.get() != TRASHED) {
342+ if (connection.maxAvailableStreams() < minAllowedStreams) {
343+ replaceConnection(connection);
344+ } else {
345+ signalAvailableConnection();
346+ }
347+ }
348+ }
349+
350+ // Trash the connection and create a new one, but we don't call trashConnection
351+ // directly because we want to make sure the connection is always trashed.
352+ private void replaceConnection(Connection connection) {
353+ if (!connection.state.compareAndSet(OPEN, TRASHED))
354+ return;
355+ open.decrementAndGet();
356+ maybeSpawnNewConnection();
357+ connection.maxIdleTime = Long.MIN_VALUE;
358+ doTrashConnection(connection);
359+ }
360+
361+ private boolean trashConnection(Connection connection) {
362+ if (!connection.state.compareAndSet(OPEN, TRASHED))
363+ return true;
364+
365+ // First, make sure we don't go below core connections
366+ for (; ; ) {
367+ int opened = open.get();
368+ if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
369+ connection.state.set(OPEN);
370+ return false;
371+ }
372+
373+ if (open.compareAndSet(opened, opened - 1))
374+ break;
375+ }
376+ logger.trace("Trashing {}", connection);
377+ connection.maxIdleTime = System.currentTimeMillis() + options().getIdleTimeoutSeconds() * 1000;
378+ doTrashConnection(connection);
379+ return true;
380+ }
381+
382+ private void doTrashConnection(Connection connection) {
383+ connections.remove(connection);
384+ trash.add(connection);
385+ }
386+
387+ private boolean addConnectionIfUnderMaximum() {
388+
389+ // First, make sure we don't cross the allowed limit of open connections
390+ for (; ; ) {
391+ int opened = open.get();
392+ if (opened >= options().getMaxConnectionsPerHost(hostDistance))
393+ return false;
394+
395+ if (open.compareAndSet(opened, opened + 1))
396+ break;
397+ }
398+
399+ if (phase.get() != Phase.READY) {
400+ open.decrementAndGet();
401+ return false;
402+ }
403+
404+ // Now really open the connection
405+ try {
406+ Connection newConnection = tryResurrectFromTrash();
407+ if (newConnection == null) {
408+ logger.debug("Creating new connection on busy pool to {}", host);
409+ newConnection = manager.connectionFactory().open(this);
410+ }
411+ connections.add(newConnection);
412+
413+ newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN
414+
415+ // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
416+ if (isClosed() && !newConnection.isClosed()) {
417+ close(newConnection);
418+ open.decrementAndGet();
419+ return false;
420+ }
421+
422+ signalAvailableConnection();
423+ return true;
424+ } catch (InterruptedException e) {
425+ Thread.currentThread().interrupt();
426+ // Skip the open but ignore otherwise
427+ open.decrementAndGet();
428+ return false;
429+ } catch (ConnectionException e) {
430+ open.decrementAndGet();
431+ logger.debug("Connection error to {} while creating additional connection", host);
432+ return false;
433+ } catch (AuthenticationException e) {
434+ // This shouldn't really happen in theory
435+ open.decrementAndGet();
436+ logger.error("Authentication error while creating additional connection (error is: {})", e.getMessage());
437+ return false;
438+ } catch (UnsupportedProtocolVersionException e) {
439+ // This shouldn't happen since we shouldn't have been able to connect in the first place
440+ open.decrementAndGet();
441+ logger.error("UnsupportedProtocolVersionException error while creating additional connection (error is: {})", e.getMessage());
442+ return false;
443+ } catch (ClusterNameMismatchException e) {
444+ open.decrementAndGet();
445+ logger.error("ClusterNameMismatchException error while creating additional connection (error is: {})", e.getMessage());
446+ return false;
447+ }
448+ }
449+
450+ private Connection tryResurrectFromTrash() {
451+ long highestMaxIdleTime = System.currentTimeMillis();
452+ Connection chosen = null;
453+
454+ while (true) {
455+ for (Connection connection : trash)
456+ if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > minAllowedStreams) {
457+ chosen = connection;
458+ highestMaxIdleTime = connection.maxIdleTime;
459+ }
460+
461+ if (chosen == null)
462+ return null;
463+ else if (chosen.state.compareAndSet(TRASHED, RESURRECTING))
464+ break;
465+ }
466+ logger.trace("Resurrecting {}", chosen);
467+ trash.remove(chosen);
468+ return chosen;
469+ }
470+
471+ private void maybeSpawnNewConnection() {
472+ while (true) {
473+ int inCreation = scheduledForCreation.get();
474+ if (inCreation >= MAX_SIMULTANEOUS_CREATION)
475+ return;
476+ if (scheduledForCreation.compareAndSet(inCreation, inCreation + 1))
477+ break;
478+ }
479+
480+ manager.blockingExecutor().submit(newConnectionTask);
481+ }
482+
483+ void replaceDefunctConnection(final Connection connection) {
484+ if (connection.state.compareAndSet(OPEN, GONE))
485+ open.decrementAndGet();
486+ if (connections.remove(connection))
487+ manager.blockingExecutor().submit(new Runnable() {
488+ @Override
489+ public void run() {
490+ addConnectionIfUnderMaximum();
491+ }
492+ });
493+ }
494+
495+ void cleanupIdleConnections(long now) {
496+ if (isClosed())
497+ return;
498+
499+ shrinkIfBelowCapacity();
500+ cleanupTrash(now);
501+ }
70502
71- abstract void ensureCoreConnections();
503+ /** If we have more active connections than needed, trash some of them */
504+ private void shrinkIfBelowCapacity() {
505+ int currentLoad = maxTotalInFlight.getAndSet(totalInFlight.get());
72506
73- abstract void replaceDefunctConnection(final Connection connection);
507+ int maxRequestsPerConnection = options().getMaxRequestsPerConnection(hostDistance);
508+ int needed = currentLoad / maxRequestsPerConnection + 1;
509+ if (currentLoad % maxRequestsPerConnection > options().getNewConnectionThreshold(hostDistance))
510+ needed += 1;
511+ needed = Math.max(needed, options().getCoreConnectionsPerHost(hostDistance));
512+ int actual = open.get();
513+ int toTrash = Math.max(0, actual - needed);
74514
75- abstract void cleanupIdleConnections(long now);
515+ logger.trace("Current inFlight = {}, {} connections needed, {} connections available, trashing {}",
516+ currentLoad, needed, actual, toTrash);
76517
77- abstract int opened();
518+ if (toTrash <= 0)
519+ return;
78520
79- abstract int trashed();
521+ for (Connection connection : connections)
522+ if (trashConnection(connection)) {
523+ toTrash -= 1;
524+ if (toTrash == 0)
525+ return;
526+ }
527+ }
80528
81- abstract int inFlightQueriesCount();
529+ /** Close connections that have been sitting in the trash for too long */
530+ private void cleanupTrash(long now) {
531+ for (Connection connection : trash) {
532+ if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
533+ if (connection.inFlight.get() == 0) {
534+ logger.trace("Cleaning up {}", connection);
535+ trash.remove(connection);
536+ close(connection);
537+ } else {
538+ // Given that idleTimeout >> request timeout, all outstanding requests should
539+ // have finished by now, so we should not get here.
540+ // Restore the status so that it's retried on the next cleanup.
541+ connection.state.set(TRASHED);
542+ }
543+ }
544+ }
545+ }
82546
83- protected abstract CloseFuture makeCloseFuture();
547+ private void close(final Connection connection) {
548+ connection.closeAsync();
549+ }
84550
85551 public final boolean isClosed() {
86552 return closeFuture.get() != null;
@@ -94,13 +560,66 @@
94560
95561 phase.set(Phase.CLOSING);
96562
97- future = makeCloseFuture();
563+ // Wake up all threads that wait
564+ signalAllAvailableConnection();
565+
566+ future = new CloseFuture.Forwarding(discardAvailableConnections());
98567
99568 return closeFuture.compareAndSet(null, future)
100569 ? future
101570 : closeFuture.get(); // We raced, it's ok, return the future that was actually set
102571 }
103572
573+ public int opened() {
574+ return open.get();
575+ }
576+
577+ int trashed() {
578+ return trash.size();
579+ }
580+
581+ private List<CloseFuture> discardAvailableConnections() {
582+ // Note: if this gets called before initialization has completed, both connections and trash will be empty,
583+ // so this will return an empty list
584+
585+ List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size());
586+
587+ for (final Connection connection : connections) {
588+ CloseFuture future = connection.closeAsync();
589+ future.addListener(new Runnable() {
590+ public void run() {
591+ if (connection.state.compareAndSet(OPEN, GONE))
592+ open.decrementAndGet();
593+ }
594+ }, MoreExecutors.sameThreadExecutor());
595+ futures.add(future);
596+ }
597+
598+ // Some connections in the trash might still be open if they hadn't reached their idle timeout
599+ for (Connection connection : trash)
600+ futures.add(connection.closeAsync());
601+
602+ return futures;
603+ }
604+
605+ // This creates connections if we have less than core connections (if we
606+ // have more than core, connection will just get trash when we can).
607+ public void ensureCoreConnections() {
608+ if (isClosed())
609+ return;
610+
611+ // Note: this process is a bit racy, but it doesn't matter since we're still guaranteed to not create
612+ // more connection than maximum (and if we create more than core connection due to a race but this isn't
613+ // justified by the load, the connection in excess will be quickly trashed anyway)
614+ int opened = open.get();
615+ for (int i = opened; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
616+ // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
617+ // protect against creating connection in excess of core too quickly
618+ scheduledForCreation.incrementAndGet();
619+ manager.blockingExecutor().submit(newConnectionTask);
620+ }
621+ }
622+
104623 static class PoolState {
105624 volatile String keyspace;
106625
@@ -108,4 +627,4 @@
108627 this.keyspace = keyspace;
109628 }
110629 }
111-}
No newline at the end of the file
630+}
modified driver-core/src/main/java/com/datastax/driver/core/Message.java +13 −4
@@ -97,14 +97,15 @@
9797 }
9898
9999 public final Type type;
100- protected boolean tracingRequested;
100+ private final boolean tracingRequested;
101101
102102 protected Request(Type type) {
103- this.type = type;
103+ this(type, false);
104104 }
105105
106- public void setTracingRequested() {
107- this.tracingRequested = true;
106+ protected Request(Type type, boolean tracingRequested) {
107+ this.type = type;
108+ this.tracingRequested = tracingRequested;
108109 }
109110
110111 public boolean isTracingRequested() {
@@ -145,6 +146,14 @@
145146 default: return null;
146147 }
147148 }
149+
150+ Request copy() {
151+ throw new UnsupportedOperationException();
152+ }
153+
154+ Request copy(ConsistencyLevel newConsistencyLevel) {
155+ throw new UnsupportedOperationException();
156+ }
148157 }
149158
150159 public static abstract class Response extends Message {
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +309 −159
@@ -15,51 +15,66 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.Map;
1819 import java.util.concurrent.Executor;
1920
2021 import com.google.common.base.Preconditions;
22+import com.google.common.collect.ImmutableMap;
2123 import com.google.common.util.concurrent.MoreExecutors;
2224
25+import static com.datastax.driver.core.HostDistance.LOCAL;
26+import static com.datastax.driver.core.HostDistance.REMOTE;
27+
2328 /**
2429 * Options related to connection pooling.
2530 * <p>
26- * The driver uses connections in an asynchronous manner. Meaning that
31+ * The driver uses connections in an asynchronous manner, meaning that
2732 * multiple requests can be submitted on the same connection at the same
28- * time. This means that the driver only needs to maintain a relatively
29- * small number of connections to each Cassandra host. These options allow
30- * the driver to control how many connections are kept exactly.
33+ * time. Therefore only a relatively small number of connections is needed.
34+ * For each host, the driver uses a connection pool that may have a variable
35+ * size (it will automatically adjust to the current load).
3136 * <p>
32- * <b>With {@code ProtocolVersion#V2} or below:</b>
33- * for each host, the driver keeps a core pool of connections open at all
34- * times determined by calling ({@link #getCoreConnectionsPerHost}).
35- * If the use of those connections reaches a configurable threshold
36- * ({@link #getMaxSimultaneousRequestsPerConnectionThreshold}),
37- * more connections are created up to the configurable maximum number of
38- * connections ({@link #getMaxConnectionsPerHost}). When the pool exceeds
39- * the maximum number of connections, connections in excess are
40- * reclaimed.
37+ * With {@code ProtocolVersion#V2} or below, there are at most 128 simultaneous
38+ * requests per connection, so the pool defaults to a variable size. You will
39+ * typically raise the maximum capacity by adding more connections with
40+ * {@link #setMaxRequestsPerConnection(HostDistance, int)}.
4141 * <p>
42- * <b>With {@code ProtocolVersion#V3} or above:</b>
43- * the driver uses a single connection for each {@code LOCAL} or {@code REMOTE}
44- * host. This connection can handle a larger amount of simultaneous requests,
45- * limited by {@link #getMaxSimultaneousRequestsPerHostThreshold(HostDistance)}.
42+ * With {@code ProtocolVersion#V3} or above, there are up to 32768 requests per
43+ * connection, and the pool defaults to a fixed size of 1. You will typically
44+ * raise the maximum capacity by allowing more simultaneous requests per connection
45+ * ({@link #setMaxRequestsPerConnection(HostDistance, int)}).
4646 * <p>
47- * Each of these parameters can be separately set for {@code LOCAL} and
47+ * All parameters can be separately set for {@code LOCAL} and
4848 * {@code REMOTE} hosts ({@link HostDistance}). For {@code IGNORED} hosts,
49- * the default for all those settings is 0 and cannot be changed.
49+ * no connections are created so these settings cannot be changed.
5050 */
5151 public class PoolingOptions {
5252
53- private static final int DEFAULT_MAX_REQUESTS_PER_CONNECTION = 100;
54-
55- private static final int DEFAULT_CORE_POOL_LOCAL = 2;
56- private static final int DEFAULT_CORE_POOL_REMOTE = 1;
57-
58- private static final int DEFAULT_MAX_POOL_LOCAL = 8;
59- private static final int DEFAULT_MAX_POOL_REMOTE = 2;
60-
61- private static final int DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL = 1024;
62- private static final int DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE = 256;
53+ static final int UNSET = Integer.MIN_VALUE;
54+
55+ 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()
77+ );
6378
6479 private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
6580 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
@@ -68,82 +83,31 @@
6883 private static final Executor DEFAULT_INITIALIZATION_EXECUTOR = MoreExecutors.sameThreadExecutor();
6984
7085 private volatile Cluster.Manager manager;
86+ private volatile ProtocolVersion protocolVersion;
87+
88+ // The defaults for these fields depend on the protocol version, which is only known after control connection initialization.
89+ // 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 };
93+ private volatile int maxRequestsPerConnectionLocal = UNSET;
94+ private volatile int maxRequestsPerConnectionRemote = UNSET;
7195
72- private final int[] maxSimultaneousRequestsPerConnection = new int[]{ DEFAULT_MAX_REQUESTS_PER_CONNECTION, DEFAULT_MAX_REQUESTS_PER_CONNECTION, 0 };
73-
74- private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 };
75- private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 };
76-
77- private volatile int maxSimultaneousRequestsPerHostLocal = DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL;
78- private volatile int maxSimultaneousRequestsPerHostRemote = DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE;
79-
8096 private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
8197 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
8298 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
8399
84100 private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR;
85101
86- public PoolingOptions() {}
102+ public PoolingOptions() {
103+ }
87104
88105 void register(Cluster.Manager manager) {
89106 this.manager = manager;
90107 }
91108
92- /**
93- * Returns the number of simultaneous requests on all connections to an host after
94- * which more connections are created.
95- * <p>
96- * This option is only used with {@code ProtocolVersion#V2} or below.
97- * <p>
98- * If all the connections opened to an host at distance {@code
99- * distance} connection are handling more than this number of
100- * simultaneous requests and there is less than
101- * {@link #getMaxConnectionsPerHost} connections open to this host, a
102- * new connection is open.
103- * <p>
104- * Note that a given connection cannot handle more than 128
105- * simultaneous requests (protocol limitation).
106- * <p>
107- * The default value for this option is 100 for {@code LOCAL} and
108- * {@code REMOTE} hosts.
109- *
110- * @param distance the {@code HostDistance} for which to return this threshold.
111- * @return the configured threshold, or the default one if none have been set.
112- */
113- public int getMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
114- return maxSimultaneousRequestsPerConnection[distance.ordinal()];
115- }
116-
117- /**
118- * Sets number of simultaneous requests on all connections to an host after
119- * which more connections are created.
120- * <p>
121- * This option is only used with {@code ProtocolVersion#V2} or below.
122- *
123- * @param distance the {@code HostDistance} for which to configure this threshold.
124- * @param newMaxSimultaneousRequests the value to set (between 0 and 128).
125- * @return this {@code PoolingOptions}.
126- *
127- * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code maxSimultaneousRequests}
128- * is not in range, or if {@code newMaxSimultaneousRequests} is less than the minimum value for this distance.
129- */
130- public synchronized PoolingOptions setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMaxSimultaneousRequests) {
131- if (distance == HostDistance.IGNORED)
132- throw new IllegalArgumentException("Cannot set max simultaneous requests per connection threshold for " + distance + " hosts");
133-
134- checkRequestsPerConnectionRange(newMaxSimultaneousRequests, "Max simultaneous requests per connection", distance);
135- maxSimultaneousRequestsPerConnection[distance.ordinal()] = newMaxSimultaneousRequests;
136- return this;
137- }
138-
139109 /**
140110 * Returns the core number of connections per host.
141- * <p>
142- * This option is only used with {@code ProtocolVersion#V2} or below.
143- * <p>
144- * For the provided {@code distance}, this correspond to the number of
145- * connections initially created and kept open to each host of that
146- * distance.
147111 *
148112 * @param distance the {@code HostDistance} for which to return this threshold.
149113 * @return the core number of connections per host at distance {@code distance}.
@@ -155,7 +119,15 @@
155119 /**
156120 * Sets the core number of connections per host.
157121 * <p>
158- * This option is only used with {@code ProtocolVersion#V2} or below.
122+ * For the provided {@code distance}, this corresponds to the number of
123+ * connections initially created and kept open to each host of that
124+ * distance.
125+ * <p>
126+ * The default value is:
127+ * <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>
130+ * </ul>
159131 *
160132 * @param distance the {@code HostDistance} for which to set this threshold.
161133 * @param newCoreConnections the value to set
@@ -163,12 +135,16 @@
163135 *
164136 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
165137 * or if {@code newCoreConnections} is greater than the maximum value for this distance.
138+ *
139+ * @see #setConnectionsPerHost(HostDistance, int, int)
166140 */
167141 public synchronized PoolingOptions setCoreConnectionsPerHost(HostDistance distance, int newCoreConnections) {
168142 if (distance == HostDistance.IGNORED)
169- throw new IllegalArgumentException("Cannot set core connections per host for " + distance + " hosts");
143+ throw new IllegalArgumentException("Cannot set core connections per host for " + distance + " hosts");
144+
145+ if (maxConnections[distance.ordinal()] != UNSET)
146+ checkConnectionsPerHostOrder(newCoreConnections, maxConnections[distance.ordinal()], distance);
170147
171- checkConnectionsPerHostOrder(newCoreConnections, maxConnections[distance.ordinal()], distance);
172148 int oldCore = coreConnections[distance.ordinal()];
173149 coreConnections[distance.ordinal()] = newCoreConnections;
174150 if (oldCore < newCoreConnections && manager != null)
@@ -178,11 +154,6 @@
178154
179155 /**
180156 * Returns the maximum number of connections per host.
181- * <p>
182- * This option is only used with {@code ProtocolVersion#V2} or below.
183- * <p>
184- * For the provided {@code distance}, this correspond to the maximum
185- * number of connections that can be created per host at that distance.
186157 *
187158 * @param distance the {@code HostDistance} for which to return this threshold.
188159 * @return the maximum number of connections per host at distance {@code distance}.
@@ -194,7 +165,14 @@
194165 /**
195166 * Sets the maximum number of connections per host.
196167 * <p>
197- * This option is only used with {@code ProtocolVersion#V2} or below.
168+ * For the provided {@code distance}, this corresponds to the maximum
169+ * number of connections that can be created per host at that distance.
170+ * <p>
171+ * The default value is:
172+ * <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>
175+ * </ul>
198176 *
199177 * @param distance the {@code HostDistance} for which to set this threshold.
200178 * @param newMaxConnections the value to set
@@ -202,16 +180,147 @@
202180 *
203181 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
204182 * or if {@code newMaxConnections} is less than the core value for this distance.
183+ *
184+ * @see #setConnectionsPerHost(HostDistance, int, int)
205185 */
206186 public synchronized PoolingOptions setMaxConnectionsPerHost(HostDistance distance, int newMaxConnections) {
207187 if (distance == HostDistance.IGNORED)
208188 throw new IllegalArgumentException("Cannot set max connections per host for " + distance + " hosts");
209189
210- checkConnectionsPerHostOrder(coreConnections[distance.ordinal()], newMaxConnections, distance);
190+ if (coreConnections[distance.ordinal()] != UNSET)
191+ checkConnectionsPerHostOrder(coreConnections[distance.ordinal()], newMaxConnections, distance);
192+
211193 maxConnections[distance.ordinal()] = newMaxConnections;
212194 return this;
213195 }
214196
197+ /**
198+ * Sets the core and maximum number of connections per host in one call.
199+ * <p>
200+ * This is a convenience method that is equivalent to calling {@link #setCoreConnectionsPerHost(HostDistance, int)}
201+ * and {@link #setMaxConnectionsPerHost(HostDistance, int)}.
202+ *
203+ * @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.
206+ * @return this {@code PoolingOptions}.
207+ *
208+ * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
209+ * or if {@code core} > {@code max}.
210+ */
211+ public synchronized PoolingOptions setConnectionsPerHost(HostDistance distance, int core, int max) {
212+ if (distance == HostDistance.IGNORED)
213+ throw new IllegalArgumentException("Cannot set connections per host for " + distance + " hosts");
214+
215+ checkConnectionsPerHostOrder(core, max, distance);
216+ coreConnections[distance.ordinal()] = core;
217+ maxConnections[distance.ordinal()] = max;
218+ return this;
219+ }
220+
221+ /**
222+ * Returns the threshold that triggers the creation of a new connection to a host.
223+ *
224+ * @param distance the {@code HostDistance} for which to return this threshold.
225+ * @return the configured threshold, or the default one if none have been set.
226+ *
227+ * @see #setNewConnectionThreshold(HostDistance, int)
228+ */
229+ public int getNewConnectionThreshold(HostDistance distance) {
230+ return newConnectionThreshold[distance.ordinal()];
231+ }
232+
233+ /**
234+ * Sets the threshold that triggers the creation of a new connection to a host.
235+ * <p>
236+ * A new connection gets created if:
237+ * <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>
243+ * </ul>
244+ * In other words, if all but the last connection are full, and the last connection is above this threshold.
245+ * <p>
246+ * The default value is:
247+ * <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>
250+ * </ul>
251+ *
252+ * @param distance the {@code HostDistance} for which to configure this threshold.
253+ * @param newValue the value to set (between 0 and 128).
254+ * @return this {@code PoolingOptions}.
255+ *
256+ * @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.
258+ */
259+ public synchronized PoolingOptions setNewConnectionThreshold(HostDistance distance, int newValue) {
260+ if (distance == HostDistance.IGNORED)
261+ throw new IllegalArgumentException("Cannot set new connection threshold for " + distance + " hosts");
262+
263+ checkRequestsPerConnectionRange(newValue, "New connection threshold", distance);
264+ newConnectionThreshold[distance.ordinal()] = newValue;
265+ return this;
266+ }
267+
268+ /**
269+ * Returns the maximum number of requests per connection.
270+ *
271+ * @param distance the {@code HostDistance} for which to return this threshold.
272+ * @return the maximum number of requests per connection at distance {@code distance}.
273+ *
274+ * @see #setMaxRequestsPerConnection(HostDistance, int)
275+ */
276+ public int getMaxRequestsPerConnection(HostDistance distance) {
277+ switch (distance) {
278+ case LOCAL:
279+ return maxRequestsPerConnectionLocal;
280+ case REMOTE:
281+ return maxRequestsPerConnectionRemote;
282+ default:
283+ return 0;
284+ }
285+ }
286+
287+ /**
288+ * Sets the maximum number of requests per connection.
289+ * <p>
290+ * The default value is:
291+ * <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>
299+ * </ul>
300+ *
301+ * @param distance the {@code HostDistance} for which to set this threshold.
302+ * @param newMaxRequests the value to set.
303+ * @return this {@code PoolingOptions}.
304+ *
305+ * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
306+ * or if {@code newMaxConnections} is not within the allowed range.
307+ */
308+ public PoolingOptions setMaxRequestsPerConnection(HostDistance distance, int newMaxRequests) {
309+ checkRequestsPerConnectionRange(newMaxRequests, "Max requests per connection", distance);
310+
311+ switch (distance) {
312+ case LOCAL:
313+ maxRequestsPerConnectionLocal = newMaxRequests;
314+ break;
315+ case REMOTE:
316+ maxRequestsPerConnectionRemote = newMaxRequests;
317+ break;
318+ default:
319+ throw new IllegalArgumentException("Cannot set max requests per host for " + distance + " hosts");
320+ }
321+ return this;
322+ }
323+
215324 /**
216325 * Returns the timeout before an idle connection is removed.
217326 *
@@ -254,7 +363,7 @@
254363 * If no connection is available within that time, the driver will try the
255364 * next host from the query plan.
256365 * <p>
257- * If this option is set to zero, the driver won't wait at all.
366+ * The default is 5 seconds. If this option is set to zero, the driver won't wait at all.
258367 *
259368 * @param poolTimeoutMillis the new value in milliseconds.
260369 * @return this {@code PoolingOptions}
@@ -299,58 +408,6 @@
299408 return this;
300409 }
301410
302- /**
303- * Returns the maximum number of requests per host.
304- * <p>
305- * This option is only used with {@code ProtocolVersion#V3} or above.
306- * <p>
307- * The default value for this option is 1024 for {@code LOCAL} and 256 for
308- * {@code REMOTE} hosts.
309- *
310- * @param distance the {@code HostDistance} for which to return this threshold.
311- * @return the maximum number of requests per host at distance {@code distance}.
312- */
313- public int getMaxSimultaneousRequestsPerHostThreshold(HostDistance distance) {
314- switch (distance) {
315- case LOCAL:
316- return maxSimultaneousRequestsPerHostLocal;
317- case REMOTE:
318- return maxSimultaneousRequestsPerHostRemote;
319- default:
320- return 0;
321- }
322- }
323-
324- /**
325- * Sets the maximum number of requests per host.
326- * <p>
327- * This option is only used with {@code ProtocolVersion#V3} or above.
328- *
329- * @param distance the {@code HostDistance} for which to set this threshold.
330- * @param newMaxRequests the value to set (between 1 and 32768).
331- * @return this {@code PoolingOptions}.
332- *
333- * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
334- * or if {@code newMaxConnections} is not within the allowed range.
335- */
336- public PoolingOptions setMaxSimultaneousRequestsPerHostThreshold(HostDistance distance, int newMaxRequests) {
337- if (newMaxRequests <= 0 || newMaxRequests > StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3)
338- throw new IllegalArgumentException(String.format("Max requests must be in the range (1, %d)",
339- StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3));
340-
341- switch (distance) {
342- case LOCAL:
343- maxSimultaneousRequestsPerHostLocal = newMaxRequests;
344- break;
345- case REMOTE:
346- maxSimultaneousRequestsPerHostRemote = newMaxRequests;
347- break;
348- default:
349- throw new IllegalArgumentException("Cannot set max requests per host for " + distance + " hosts");
350- }
351- return this;
352- }
353-
354411 /**
355412 * Returns the executor to use for connection initialization.
356413 *
@@ -387,6 +444,43 @@
387444 return this;
388445 }
389446
447+ synchronized void setProtocolVersion(ProtocolVersion protocolVersion) {
448+ this.protocolVersion = protocolVersion;
449+
450+ ProtocolVersion referenceVersion = (protocolVersion.compareTo(ProtocolVersion.V2) <= 0)
451+ ? ProtocolVersion.V2
452+ : ProtocolVersion.V3;
453+ Map<String, Integer> defaults = DEFAULTS.get(referenceVersion);
454+
455+ if (coreConnections[LOCAL.ordinal()] == UNSET)
456+ coreConnections[LOCAL.ordinal()] = defaults.get("corePoolLocal");
457+ if (maxConnections[LOCAL.ordinal()] == UNSET)
458+ maxConnections[LOCAL.ordinal()] = defaults.get("maxPoolLocal");
459+ checkConnectionsPerHostOrder(coreConnections[LOCAL.ordinal()], maxConnections[LOCAL.ordinal()], LOCAL);
460+
461+ if (coreConnections[REMOTE.ordinal()] == UNSET)
462+ coreConnections[REMOTE.ordinal()] = defaults.get("corePoolRemote");
463+ if (maxConnections[REMOTE.ordinal()] == UNSET)
464+ maxConnections[REMOTE.ordinal()] = defaults.get("maxPoolRemote");
465+ checkConnectionsPerHostOrder(coreConnections[REMOTE.ordinal()], maxConnections[REMOTE.ordinal()], REMOTE);
466+
467+ if (newConnectionThreshold[LOCAL.ordinal()] == UNSET)
468+ newConnectionThreshold[LOCAL.ordinal()] = defaults.get("newConnectionThresholdLocal");
469+ checkRequestsPerConnectionRange(newConnectionThreshold[LOCAL.ordinal()], "New connection threshold", LOCAL);
470+
471+ if (newConnectionThreshold[REMOTE.ordinal()] == UNSET)
472+ newConnectionThreshold[REMOTE.ordinal()] = defaults.get("newConnectionThresholdRemote");
473+ checkRequestsPerConnectionRange(newConnectionThreshold[REMOTE.ordinal()], "New connection threshold", REMOTE);
474+
475+ if (maxRequestsPerConnectionLocal == UNSET)
476+ maxRequestsPerConnectionLocal = defaults.get("maxRequestsPerConnectionLocal");
477+ checkRequestsPerConnectionRange(maxRequestsPerConnectionLocal, "Max requests per connection", LOCAL);
478+
479+ if (maxRequestsPerConnectionRemote == UNSET)
480+ maxRequestsPerConnectionRemote = defaults.get("maxRequestsPerConnectionRemote");
481+ checkRequestsPerConnectionRange(maxRequestsPerConnectionRemote, "Max requests per connection", REMOTE);
482+ }
483+
390484 /**
391485 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
392486 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
@@ -407,16 +501,72 @@
407501 manager.refreshConnectedHost(host);
408502 }
409503
410- private static void checkRequestsPerConnectionRange(int value, String description, HostDistance distance) {
411- if (value < 0 || value > StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2)
504+ private void checkRequestsPerConnectionRange(int value, String description, HostDistance distance) {
505+ // If we don't know the protocol version yet, use the highest possible upper bound, this will get checked again when possible
506+ int max = (protocolVersion == null || protocolVersion.compareTo(ProtocolVersion.V3) >= 0)
507+ ? StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3
508+ : StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2;
509+
510+ if (value < 0 || value > max)
412511 throw new IllegalArgumentException(String.format("%s for %s hosts must be in the range (0, %d)",
413- description, distance,
414- StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2));
512+ description, distance, max));
415513 }
416514
417515 private static void checkConnectionsPerHostOrder(int core, int max, HostDistance distance) {
418516 if (core > max)
419517 throw new IllegalArgumentException(String.format("Core connections for %s hosts must be less than max (%d > %d)",
420- distance, core, max));
518+ distance, core, max));
519+ }
520+
521+ /**
522+ * @deprecated this option isn't used anymore with the current pool resizing algorithm.
523+ */
524+ @Deprecated
525+ public int getMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
526+ return 0;
527+ }
528+
529+ /**
530+ * @deprecated this option isn't used anymore with the current pool resizing algorithm.
531+ */
532+ @Deprecated
533+ public synchronized PoolingOptions setMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMinSimultaneousRequests) {
534+ return this;
535+ }
536+
537+ /**
538+ * @deprecated this method has been renamed to {@link #getNewConnectionThreshold(HostDistance)}. This method calls the new one internally,
539+ * but you should use the new one in your code.
540+ */
541+ @Deprecated
542+ public int getMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
543+ return getNewConnectionThreshold(distance);
544+ }
545+
546+ /**
547+ * @deprecated this method has been renamed to {@link #setNewConnectionThreshold(HostDistance, int)}. This method calls the new one
548+ * internally, but you should use the new one in your code.
549+ */
550+ @Deprecated
551+ public PoolingOptions setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMaxSimultaneousRequests) {
552+ return this.setNewConnectionThreshold(distance, newMaxSimultaneousRequests);
553+ }
554+
555+ /**
556+ * @deprecated this method has been renamed to {@link #getMaxRequestsPerConnection(HostDistance)}. This method calls the new one internally,
557+ * but you should use the new one in your code.
558+ */
559+ @Deprecated
560+ public int getMaxSimultaneousRequestsPerHostThreshold(HostDistance distance) {
561+ return this.getMaxRequestsPerConnection(distance);
562+ }
563+
564+ /**
565+ * @deprecated this method has been renamed to {@link #setMaxRequestsPerConnection(HostDistance, int)}. This method calls the new one internally,
566+ * but you should use the new one in your code.
567+ */
568+ @Deprecated
569+ public PoolingOptions setMaxSimultaneousRequestsPerHostThreshold(HostDistance distance, int newMaxRequests) {
570+ return this.setMaxRequestsPerConnection(distance, newMaxRequests);
421571 }
422572 }
modified driver-core/src/main/java/com/datastax/driver/core/QueryTrace.java +1 −1
@@ -232,7 +232,7 @@
232232 }
233233
234234 if (tries > MAX_TRIES)
235- throw new TraceRetrievalException(String.format("Unable to retrieve complete query trace after %d tries", MAX_TRIES));
235+ throw new TraceRetrievalException(String.format("Unable to retrieve complete query trace for id %s after %d tries", traceId, MAX_TRIES));
236236 }
237237
238238 /**
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +26 −0
@@ -18,6 +18,9 @@
1818 import java.util.*;
1919
2020 import com.google.common.collect.ImmutableSet;
21+import com.google.common.collect.Sets;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
2124
2225 /*
2326 * Computes the token->list<replica> association, given the token ring and token->primary token map.
@@ -87,6 +90,7 @@
8790 }
8891
8992 static class NetworkTopologyStrategy extends ReplicationStrategy {
93+ private static final Logger logger = LoggerFactory.getLogger(NetworkTopologyStrategy.class);
9094
9195 private final Map<String, Integer> replicationFactors;
9296
@@ -99,6 +103,9 @@
99103 // This is essentially a copy of org.apache.cassandra.locator.NetworkTopologyStrategy
100104 Map<String, Set<String>> racks = getRacksInDcs(tokenToPrimary.values());
101105 Map<Token, Set<Host>> replicaMap = new HashMap<Token, Set<Host>>(tokenToPrimary.size());
106+
107+ Set<String> warnedDcs = Sets.newHashSetWithExpectedSize(replicationFactors.size());
108+
102109 for (int i = 0; i < ring.size(); i++) {
103110 Map<String, Set<Host>> allDcReplicas = new HashMap<String, Set<Host>>();
104111 Map<String, Set<String>> seenRacks = new HashMap<String, Set<String>>();
@@ -147,6 +154,25 @@
147154 }
148155 }
149156 }
157+
158+ // If we haven't found enough replicas after a whole trip around the ring, this probably
159+ // means that the replication factors are broken.
160+ // Warn the user because that leads to quadratic performance of this method (JAVA-702).
161+ for (Map.Entry<String, Set<Host>> entry : allDcReplicas.entrySet()) {
162+ String dcName = entry.getKey();
163+ int expectedFactor = replicationFactors.get(dcName);
164+ int achievedFactor = entry.getValue().size();
165+ if (achievedFactor < expectedFactor && !warnedDcs.contains(dcName)) {
166+ logger.warn("Error while computing token map for datacenter {}: "
167+ + "could not achieve replication factor {} (found {} replicas only), "
168+ + "check your keyspace replication settings. "
169+ + "Note that this can affect the performance of the driver.",
170+ dcName, expectedFactor, achievedFactor);
171+ // only warn once per DC
172+ warnedDcs.add(dcName);
173+ }
174+ }
175+
150176 replicaMap.put(ring.get(i), ImmutableSet.copyOf(replicas));
151177 }
152178 return replicaMap;
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +5 −3
@@ -111,7 +111,7 @@
111111 // Clone the request after the first execution, since we set the streamId on it later and we
112112 // don't want to share that across executions.
113113 if (position > 1)
114- request = manager.makeRequestMessage(statement, request.pagingState()) ;
114+ request = request.copy();
115115
116116 SpeculativeExecution execution = new SpeculativeExecution(request, position);
117117 runningExecutions.add(execution);
@@ -408,7 +408,7 @@
408408 @Override
409409 public Message.Request request() {
410410 if (retryConsistencyLevel != null && retryConsistencyLevel != request.consistency())
411- return manager.makeRequestMessage(statement, retryConsistencyLevel, request.serialConsistency(), request.pagingState(), request.defaultTimestamp());
411+ return request.copy(retryConsistencyLevel);
412412 else
413413 return request;
414414 }
@@ -582,7 +582,9 @@
582582 logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel());
583583 if (metricsEnabled())
584584 metrics().getErrorMetrics().getRetries().inc();
585- retry(true, retry.getRetryConsistencyLevel());
585+ if (!retry.isRetryCurrent())
586+ logError(connection.address, exceptionToReport);
587+ retry(retry.isRetryCurrent(), retry.getRetryConsistencyLevel());
586588 break;
587589 case RETHROW:
588590 setFinalResult(connection, response);
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +44 −7
@@ -125,15 +125,25 @@
125125 public final QueryProtocolOptions options;
126126
127127 public Query(String query) {
128- this(query, QueryProtocolOptions.DEFAULT);
128+ this(query, QueryProtocolOptions.DEFAULT, false);
129129 }
130130
131- public Query(String query, QueryProtocolOptions options) {
132- super(Type.QUERY);
131+ public Query(String query, QueryProtocolOptions options, boolean tracingRequested) {
132+ super(Type.QUERY, tracingRequested);
133133 this.query = query;
134134 this.options = options;
135135 }
136136
137+ @Override
138+ Request copy() {
139+ return new Query(this.query, options, isTracingRequested());
140+ }
141+
142+ @Override
143+ Request copy(ConsistencyLevel newConsistencyLevel) {
144+ return new Query(this.query, options.copy(newConsistencyLevel), isTracingRequested());
145+ }
146+
137147 @Override
138148 public String toString() {
139149 return "QUERY " + query + '(' + options + ')';
@@ -157,12 +167,22 @@
157167 public final MD5Digest statementId;
158168 public final QueryProtocolOptions options;
159169
160- public Execute(MD5Digest statementId, QueryProtocolOptions options) {
161- super(Message.Request.Type.EXECUTE);
170+ public Execute(MD5Digest statementId, QueryProtocolOptions options, boolean tracingRequested) {
171+ super(Message.Request.Type.EXECUTE, tracingRequested);
162172 this.statementId = statementId;
163173 this.options = options;
164174 }
165175
176+ @Override
177+ Request copy() {
178+ return new Execute(statementId, options, isTracingRequested());
179+ }
180+
181+ @Override
182+ Request copy(ConsistencyLevel newConsistencyLevel) {
183+ return new Execute(statementId, options.copy(newConsistencyLevel), isTracingRequested());
184+ }
185+
166186 @Override
167187 public String toString() {
168188 return "EXECUTE " + statementId + " (" + options + ')';
@@ -248,6 +268,10 @@
248268 flags.add(QueryFlag.DEFAULT_TIMESTAMP);
249269 }
250270
271+ public QueryProtocolOptions copy(ConsistencyLevel newConsistencyLevel) {
272+ return new QueryProtocolOptions(newConsistencyLevel, values, skipMetadata, pageSize, pagingState, serialConsistency, defaultTimestamp);
273+ }
274+
251275 public void encode(ByteBuf dest, ProtocolVersion version) {
252276 switch (version) {
253277 case V1:
@@ -362,14 +386,23 @@
362386 public final List<List<ByteBuffer>> values;
363387 public final BatchProtocolOptions options;
364388
365- public Batch(BatchStatement.Type type, List<Object> queryOrIdList, List<List<ByteBuffer>> values, BatchProtocolOptions options) {
366- super(Message.Request.Type.BATCH);
389+ public Batch(BatchStatement.Type type, List<Object> queryOrIdList, List<List<ByteBuffer>> values, BatchProtocolOptions options, boolean tracingRequested) {
390+ super(Message.Request.Type.BATCH, tracingRequested);
367391 this.type = type;
368392 this.queryOrIdList = queryOrIdList;
369393 this.values = values;
370394 this.options = options;
371395 }
372396
397+ @Override
398+ Request copy() {
399+ return new Batch(type, queryOrIdList, values, options, isTracingRequested());
400+ }
401+
402+ @Override
403+ Request copy(ConsistencyLevel newConsistencyLevel) {
404+ return new Batch(type, queryOrIdList, values, options.copy(newConsistencyLevel), isTracingRequested());
405+ }
373406 @Override
374407 public String toString() {
375408 StringBuilder sb = new StringBuilder();
@@ -400,6 +433,10 @@
400433 flags.add(QueryFlag.DEFAULT_TIMESTAMP);
401434 }
402435
436+ BatchProtocolOptions copy(ConsistencyLevel newConsistencyLevel) {
437+ return new BatchProtocolOptions(newConsistencyLevel, serialConsistency, defaultTimestamp);
438+ }
439+
403440 public void encode(ByteBuf dest, ProtocolVersion version) {
404441 switch (version) {
405442 case V2:
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +5 −10
@@ -429,17 +429,19 @@
429429 data.add(row);
430430 }
431431
432- return new Rows(metadata, data);
432+ return new Rows(metadata, data, version);
433433 }
434434 };
435435
436436 public final Metadata metadata;
437437 public final Queue<List<ByteBuffer>> data;
438+ private final ProtocolVersion version;
438439
439- private Rows(Metadata metadata, Queue<List<ByteBuffer>> data) {
440+ private Rows(Metadata metadata, Queue<List<ByteBuffer>> data, ProtocolVersion version) {
440441 super(Kind.ROWS);
441442 this.metadata = metadata;
442443 this.data = data;
444+ this.version = version;
443445 }
444446
445447 @Override
@@ -456,14 +458,7 @@
456458 if (metadata.columns == null) {
457459 sb.append(Bytes.toHexString(v));
458460 } else {
459- // We don't have the protocol version available and it's a pain to change
460- // everything to get it when this method is only ever call for debugging.
461- // So trying v3 and falling back to v2, which is ugly but good enough for now.
462- try {
463- sb.append(metadata.columns.getType(i).deserialize(v, ProtocolVersion.V3));
464- } catch (IllegalArgumentException e) {
465- sb.append(metadata.columns.getType(i).deserialize(v, ProtocolVersion.V2));
466- }
461+ sb.append(metadata.columns.getType(i).deserialize(v, version));
467462 }
468463 }
469464 }
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +23 −32
@@ -209,8 +209,7 @@
209209 if (isClosing)
210210 return Futures.immediateFuture(false);
211211
212- final HostConnectionPool newPool = HostConnectionPool.newInstance(host, distance, SessionManager.this,
213- cluster.getConfiguration().getProtocolOptions().getProtocolVersion());
212+ final HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
214213 ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection);
215214
216215 final SettableFuture<Boolean> future = SettableFuture.create();
@@ -252,8 +251,7 @@
252251 if (isClosing)
253252 return MoreFutures.VOID_SUCCESS;
254253
255- final HostConnectionPool newPool = HostConnectionPool.newInstance(host, distance, this,
256- cluster.getConfiguration().getProtocolOptions().getProtocolVersion());
254+ final HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
257255 if (previous == null) {
258256 if (pools.putIfAbsent(host, newPool) != null) {
259257 return null;
@@ -475,22 +473,17 @@
475473 defaultTimestamp = cluster.getConfiguration().getPolicies().getTimestampGenerator().next();
476474 }
477475
478- return makeRequestMessage(statement, consistency, serialConsistency, pagingState, defaultTimestamp);
479- }
480-
481- Message.Request makeRequestMessage(Statement statement, ConsistencyLevel cl, ConsistencyLevel scl, ByteBuffer pagingState, long defaultTimestamp) {
482- ProtocolVersion protoVersion = cluster.manager.protocolVersion();
483476 int fetchSize = statement.getFetchSize();
484477 ByteBuffer usedPagingState = pagingState;
485478
486- if (protoVersion == ProtocolVersion.V1) {
479+ if (version == ProtocolVersion.V1) {
487480 assert pagingState == null;
488481 // We don't let the user change the fetchSize globally if the proto v1 is used, so we just need to
489482 // check for the case of a per-statement override
490483 if (fetchSize <= 0)
491484 fetchSize = -1;
492485 else if (fetchSize != Integer.MAX_VALUE)
493- throw new UnsupportedFeatureException(protoVersion, "Paging is not supported");
486+ throw new UnsupportedFeatureException(version, "Paging is not supported");
494487 } else if (fetchSize <= 0) {
495488 fetchSize = configuration().getQueryOptions().getFetchSize();
496489 }
@@ -512,44 +505,44 @@
512505 // It saddens me that we special case for the query builder here, but for now this is simpler.
513506 // We could provide a general API in RegularStatement instead at some point but it's unclear what's
514507 // the cleanest way to do that is right now (and it's probably not really that useful anyway).
515- if (protoVersion == ProtocolVersion.V1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement)
508+ if (version == ProtocolVersion.V1 && rs instanceof com.datastax.driver.core.querybuilder.BuiltStatement)
516509 ((com.datastax.driver.core.querybuilder.BuiltStatement)rs).setForceNoValues(true);
517510
518- ByteBuffer[] rawValues = rs.getValues(protoVersion);
511+ ByteBuffer[] rawValues = rs.getValues(version);
519512
520- if (protoVersion == ProtocolVersion.V1 && rawValues != null)
521- throw new UnsupportedFeatureException(protoVersion, "Binary values are not supported");
513+ if (version == ProtocolVersion.V1 && rawValues != null)
514+ throw new UnsupportedFeatureException(version, "Binary values are not supported");
522515
523516 List<ByteBuffer> values = rawValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawValues);
524517 String qString = rs.getQueryString();
525- Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(cl, values, false,
526- fetchSize, usedPagingState, scl, defaultTimestamp);
527- request = new Requests.Query(qString, options);
518+ Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, values, false,
519+ fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
520+ request = new Requests.Query(qString, options, statement.isTracing());
528521 } else if (statement instanceof BoundStatement) {
529522 BoundStatement bs = (BoundStatement)statement;
530523 if (!cluster.manager.preparedQueries.containsKey(bs.statement.getPreparedId().id)) {
531524 throw new InvalidQueryException(String.format("Tried to execute unknown prepared query : %s. "
532525 + "You may have used a PreparedStatement that was created with another Cluster instance.", bs.statement.getPreparedId().id));
533526 }
534- if(protoVersion.compareTo(ProtocolVersion.V4) < 0)
527+ if (version.compareTo(ProtocolVersion.V4) < 0)
535528 bs.ensureAllSet();
536- boolean skipMetadata = protoVersion != ProtocolVersion.V1 && bs.statement.getPreparedId().resultSetMetadata != null;
537- Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(cl, Arrays.asList(bs.wrapper.values), skipMetadata,
538- fetchSize, usedPagingState, scl, defaultTimestamp);
539- request = new Requests.Execute(bs.statement.getPreparedId().id, options);
529+ boolean skipMetadata = version != ProtocolVersion.V1 && bs.statement.getPreparedId().resultSetMetadata != null;
530+ Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, Arrays.asList(bs.wrapper.values), skipMetadata,
531+ fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
532+ request = new Requests.Execute(bs.statement.getPreparedId().id, options, statement.isTracing());
540533 } else {
541534 assert statement instanceof BatchStatement : statement;
542535 assert pagingState == null;
543536
544- if (protoVersion == ProtocolVersion.V1)
545- throw new UnsupportedFeatureException(protoVersion, "Protocol level batching is not supported");
537+ if (version == ProtocolVersion.V1)
538+ throw new UnsupportedFeatureException(version, "Protocol level batching is not supported");
546539
547540 BatchStatement bs = (BatchStatement)statement;
548- if(protoVersion.compareTo(ProtocolVersion.V4) < 0)
541+ if (version.compareTo(ProtocolVersion.V4) < 0)
549542 bs.ensureAllSet();
550- BatchStatement.IdAndValues idAndVals = bs.getIdAndValues(protoVersion);
551- Requests.BatchProtocolOptions options = new Requests.BatchProtocolOptions(cl, scl, defaultTimestamp);
552- request = new Requests.Batch(bs.batchType, idAndVals.ids, idAndVals.values, options);
543+ BatchStatement.IdAndValues idAndVals = bs.getIdAndValues(version);
544+ Requests.BatchProtocolOptions options = new Requests.BatchProtocolOptions(consistency, serialConsistency, defaultTimestamp);
545+ request = new Requests.Batch(bs.batchType, idAndVals.ids, idAndVals.values, options, statement.isTracing());
553546 }
554547
555548 request.setCustomPayload(statement.getOutgoingPayload());
@@ -601,8 +594,6 @@
601594 }
602595
603596 ResultSetFuture executeQuery(Message.Request msg, Statement statement) {
604- if (statement.isTracing())
605- msg.setTracingRequested();
606597
607598 DefaultResultSetFuture future = new DefaultResultSetFuture(this, configuration().getProtocolOptions().getProtocolVersion(), msg);
608599 execute(future, statement);
@@ -645,7 +636,7 @@
645636 }
646637
647638 openConnections[i] = p.opened();
648- inFlightQueries[i] = p.inFlightQueriesCount();
639+ inFlightQueries[i] = p.totalInFlight.get();
649640 trashedConnections[i] = p.trashed();
650641 i++;
651642 }
deleted driver-core/src/main/java/com/datastax/driver/core/SingleConnectionPool.java +0 −407
@@ -1,407 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-
19-import java.util.ArrayList;
20-import java.util.List;
21-import java.util.Set;
22-import java.util.concurrent.CopyOnWriteArraySet;
23-import java.util.concurrent.Executor;
24-import java.util.concurrent.TimeUnit;
25-import java.util.concurrent.TimeoutException;
26-import java.util.concurrent.atomic.AtomicBoolean;
27-import java.util.concurrent.atomic.AtomicReference;
28-import java.util.concurrent.locks.Condition;
29-import java.util.concurrent.locks.Lock;
30-import java.util.concurrent.locks.ReentrantLock;
31-
32-import com.google.common.util.concurrent.*;
33-import org.slf4j.Logger;
34-import org.slf4j.LoggerFactory;
35-
36-import com.datastax.driver.core.exceptions.AuthenticationException;
37-import com.datastax.driver.core.utils.MoreFutures;
38-
39-import static com.datastax.driver.core.Connection.State.GONE;
40-import static com.datastax.driver.core.Connection.State.OPEN;
41-import static com.datastax.driver.core.Connection.State.TRASHED;
42-
43-/**
44- * A connection pool with a a single connection.
45- *
46- * This is used with {@link ProtocolVersion#V3} and higher.
47- */
48-class SingleConnectionPool extends HostConnectionPool {
49-
50- private static final Logger logger = LoggerFactory.getLogger(SingleConnectionPool.class);
51-
52- // When a request timeout, we may never release its stream ID. So over time, a given connection
53- // may get less an less available streams. When the number of available ones go below the
54- // following threshold, we just replace the connection by a new one.
55- private static final int MIN_AVAILABLE_STREAMS = 32768 * 3 / 4;
56-
57- volatile AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
58- private final AtomicBoolean open = new AtomicBoolean();
59- private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
60-
61- private volatile int waiter = 0;
62- private final Lock waitLock = new ReentrantLock(true);
63- private final Condition hasAvailableConnection = waitLock.newCondition();
64-
65- private final Runnable newConnectionTask;
66-
67- private final AtomicBoolean scheduledForCreation = new AtomicBoolean();
68-
69- public SingleConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
70- super(host, hostDistance, manager);
71-
72- this.newConnectionTask = new Runnable() {
73- @Override
74- public void run() {
75- addConnectionIfNeeded();
76- scheduledForCreation.set(false);
77- }
78- };
79- }
80-
81- @Override
82- ListenableFuture<Void> initAsync(Connection reusedConnection) {
83- final Connection connection;
84- ListenableFuture<Void> connectionFuture;
85- if (reusedConnection != null && reusedConnection.setPool(this)) {
86- connection = reusedConnection;
87- connectionFuture = MoreFutures.VOID_SUCCESS;
88- } else {
89- connection = manager.connectionFactory().newConnection(this);
90- connectionFuture = connection.initAsync();
91- }
92-
93- Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
94-
95- final SettableFuture<Void> initFuture = SettableFuture.create();
96- Futures.addCallback(connectionFuture, new FutureCallback<Void>() {
97- @Override
98- public void onSuccess(Void result) {
99- connectionRef.set(connection);
100- open.set(true);
101- if (isClosed()) {
102- initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
103- // we're not sure if closeAsync() saw the connection, so ensure it gets closed
104- connection.closeAsync().force();
105- } else {
106- logger.trace("Created connection pool to host {}", host);
107- phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
108- initFuture.set(null);
109- }
110- }
111-
112- @Override
113- public void onFailure(Throwable t) {
114- phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED);
115- initFuture.setException(t);
116- }
117- }, initExecutor);
118-
119- return initFuture;
120- }
121-
122- private PoolingOptions options() {
123- return manager.configuration().getPoolingOptions();
124- }
125-
126- @Override
127- public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
128- Phase phase = this.phase.get();
129- if (phase != Phase.READY)
130- // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
131- // That being said, maybe having a specific exception could be cleaner.
132- throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
133-
134- Connection connection = connectionRef.get();
135- if (connection == null) {
136- if (scheduledForCreation.compareAndSet(false, true))
137- manager.blockingExecutor().submit(newConnectionTask);
138- connection = waitForConnection(timeout, unit);
139- } else {
140- while (true) {
141- int inFlight = connection.inFlight.get();
142-
143- if (inFlight >= Math.min(connection.maxAvailableStreams(),
144- options().getMaxSimultaneousRequestsPerHostThreshold(hostDistance))) {
145- connection = waitForConnection(timeout, unit);
146- break;
147- }
148-
149- if (connection.inFlight.compareAndSet(inFlight, inFlight + 1))
150- break;
151- }
152- }
153- connection.setKeyspace(manager.poolsState.keyspace);
154- return connection;
155- }
156-
157- private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException {
158- waitLock.lock();
159- waiter++;
160- try {
161- hasAvailableConnection.await(timeout, unit);
162- } finally {
163- waiter--;
164- waitLock.unlock();
165- }
166- }
167-
168- private void signalAvailableConnection() {
169- // Quick check if it's worth signaling to avoid locking
170- if (waiter == 0)
171- return;
172-
173- waitLock.lock();
174- try {
175- hasAvailableConnection.signal();
176- } finally {
177- waitLock.unlock();
178- }
179- }
180-
181- private void signalAllAvailableConnection() {
182- // Quick check if it's worth signaling to avoid locking
183- if (waiter == 0)
184- return;
185-
186- waitLock.lock();
187- try {
188- hasAvailableConnection.signalAll();
189- } finally {
190- waitLock.unlock();
191- }
192- }
193-
194- private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
195- if (timeout == 0)
196- throw new TimeoutException();
197-
198- long start = System.nanoTime();
199- long remaining = timeout;
200- do {
201- try {
202- awaitAvailableConnection(remaining, unit);
203- } catch (InterruptedException e) {
204- Thread.currentThread().interrupt();
205- // If we're interrupted fine, check if there is a connection available but stop waiting otherwise
206- timeout = 0; // this will make us stop the loop if we don't get a connection right away
207- }
208-
209- if (isClosed())
210- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
211-
212- Connection connection = connectionRef.get();
213- // If we race with shutdown, connection could be null. In that case we just loop and we'll throw on the next
214- // iteration anyway
215- if (connection != null) {
216- while (true) {
217- int inFlight = connection.inFlight.get();
218-
219- if (inFlight >= Math.min(connection.maxAvailableStreams(),
220- options().getMaxSimultaneousRequestsPerHostThreshold(hostDistance)))
221- break;
222-
223- if (connection.inFlight.compareAndSet(inFlight, inFlight + 1))
224- return connection;
225- }
226- }
227-
228- remaining = timeout - Cluster.timeSince(start, unit);
229- } while (remaining > 0);
230-
231- throw new TimeoutException();
232- }
233-
234- @Override
235- public void returnConnection(Connection connection) {
236- int inFlight = connection.inFlight.decrementAndGet();
237-
238- if (isClosed()) {
239- close(connection);
240- return;
241- }
242-
243- if (connection.isDefunct()) {
244- // As part of making it defunct, we have already replaced it or
245- // closed the pool.
246- return;
247- }
248-
249- if (trash.contains(connection)) {
250- if (inFlight == 0 && trash.remove(connection))
251- close(connection);
252- } else {
253- if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
254- replaceConnection(connection);
255- } else {
256- signalAvailableConnection();
257- }
258- }
259- }
260-
261- // Trash the connection and create a new one, but we don't call trashConnection
262- // directly because we want to make sure the connection is always trashed.
263- private void replaceConnection(Connection connection) {
264- if (!connection.state.compareAndSet(OPEN, TRASHED))
265- return;
266- open.set(false);
267- maybeSpawnNewConnection();
268- doTrashConnection(connection);
269- }
270-
271- private void doTrashConnection(Connection connection) {
272- connectionRef.compareAndSet(connection, null);
273- trash.add(connection);
274-
275- if (connection.inFlight.get() == 0 && trash.remove(connection))
276- close(connection);
277- }
278-
279- private boolean addConnectionIfNeeded() {
280- if (!open.compareAndSet(false, true))
281- return false;
282-
283- if (phase.get() != Phase.READY) {
284- open.set(false);
285- return false;
286- }
287-
288- // Now really open the connection
289- try {
290- logger.debug("Creating new connection on busy pool to {}", host);
291- Connection newConnection = manager.connectionFactory().open(this);
292- connectionRef.set(newConnection);
293-
294- // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
295- if (isClosed() && !newConnection.isClosed()) {
296- close(newConnection);
297- this.open.set(false);
298- return false;
299- }
300-
301- signalAvailableConnection();
302- return true;
303- } catch (InterruptedException e) {
304- Thread.currentThread().interrupt();
305- // Skip the open but ignore otherwise
306- open.set(false);
307- return false;
308- } catch (ConnectionException e) {
309- open.set(false);
310- logger.debug("Connection error to {} while creating additional connection", host);
311- return false;
312- } catch (AuthenticationException e) {
313- // This shouldn't really happen in theory
314- open.set(false);
315- logger.error("Authentication error while creating additional connection (error is: {})", e.getMessage());
316- return false;
317- } catch (UnsupportedProtocolVersionException e) {
318- // This shouldn't happen since we shouldn't have been able to connect in the first place
319- open.set(false);
320- logger.error("UnsupportedProtocolVersionException error while creating additional connection (error is: {})", e.getMessage());
321- return false;
322- } catch (ClusterNameMismatchException e) {
323- open.set(false);
324- logger.error("ClusterNameMismatchException error while creating additional connection (error is: {})", e.getMessage());
325- return false;
326- }
327- }
328-
329- private void maybeSpawnNewConnection() {
330- if (!scheduledForCreation.compareAndSet(false, true))
331- return;
332-
333- manager.blockingExecutor().submit(newConnectionTask);
334- }
335-
336- @Override
337- public void replaceDefunctConnection(final Connection connection) {
338- if (connection.state.compareAndSet(OPEN, GONE))
339- open.set(false);
340- if (connectionRef.compareAndSet(connection, null))
341- manager.blockingExecutor().submit(new Runnable() {
342- @Override
343- public void run() {
344- addConnectionIfNeeded();
345- }
346- });
347- }
348-
349- @Override
350- void cleanupIdleConnections(long now) {
351- }
352-
353- private void close(final Connection connection) {
354- connection.closeAsync();
355- }
356-
357- protected CloseFuture makeCloseFuture() {
358- // Wake up all threads that wait
359- signalAllAvailableConnection();
360-
361- return new CloseFuture.Forwarding(discardConnection());
362- }
363-
364- private List<CloseFuture> discardConnection() {
365-
366- List<CloseFuture> futures = new ArrayList<CloseFuture>();
367-
368- final Connection connection = connectionRef.get();
369- if (connection != null) {
370- CloseFuture future = connection.closeAsync();
371- future.addListener(new Runnable() {
372- public void run() {
373- if (connection.state.compareAndSet(OPEN, GONE))
374- open.set(false);
375- }
376- }, MoreExecutors.sameThreadExecutor());
377- futures.add(future);
378- }
379- return futures;
380- }
381-
382- @Override
383- public void ensureCoreConnections() {
384- if (isClosed())
385- return;
386-
387- if (!open.get() && scheduledForCreation.compareAndSet(false, true)) {
388- manager.blockingExecutor().submit(newConnectionTask);
389- }
390- }
391-
392- @Override
393- public int opened() {
394- return open.get() ? 1 : 0;
395- }
396-
397- @Override
398- int trashed() {
399- return trash.size();
400- }
401-
402- @Override
403- public int inFlightQueriesCount() {
404- Connection connection = connectionRef.get();
405- return connection == null ? 0 : connection.inFlight.get();
406- }
407-}
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +4 −3
@@ -437,9 +437,10 @@
437437 * <p>
438438 * By default, this method returns {@code null} for all statements, except for
439439 * {@link BuiltStatement}s, where the value will be inferred from the query: if it updates
440- * counters or prepends/appends to a list, the result will be {@code false}, otherwise it
441- * will be {@code true}. In all cases, calling {@link #setIdempotent(boolean)} forces a
442- * value that overrides every other mechanism.
440+ * counters, prepends/appends to a list, or uses a function call or
441+ * {@link com.datastax.driver.core.querybuilder.QueryBuilder#raw(String)} anywhere in an inserted value,
442+ * the result will be {@code false}; otherwise it will be {@code true}.
443+ * In all cases, calling {@link #setIdempotent(boolean)} forces a value that overrides every other mechanism.
443444 *
444445 * @return whether this statement is idempotent, or {@code null} to use
445446 * {@link QueryOptions#getDefaultIdempotence()}.
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +17 −9
@@ -25,7 +25,7 @@
2525 * <p>
2626 * This policy retries queries in only two cases:
2727 * <ul>
28- * <li>On a read timeout, if enough replica replied but data was not retrieved.</li>
28+ * <li>On a read timeout, if enough replicas replied but data was not retrieved.</li>
2929 * <li>On a write timeout, if we timeout while writing the distributed log used by batch statements.</li>
3030 * </ul>
3131 * <p>
@@ -45,13 +45,13 @@
4545 * Defines whether to retry and at which consistency level on a read timeout.
4646 * <p>
4747 * This method triggers a maximum of one retry, and only if enough
48- * replica had responded to the read request but data was not retrieved
48+ * replicas had responded to the read request but data was not retrieved
4949 * amongst those. Indeed, that case usually means that enough replica
5050 * are alive to satisfy the consistency but the coordinator picked a
5151 * dead one for data retrieval, not having detected that replica as dead
5252 * yet. The reasoning for retrying then is that by the time we get the
5353 * timeout the dead replica will likely have been detected as dead and
54- * the retry has a high change of success.
54+ * the retry has a high chance of success.
5555 *
5656 * @param statement the original query that timed out.
5757 * @param cl the original consistency level of the read that timed out.
@@ -61,7 +61,7 @@
6161 * by the time the timeout exception was raised.
6262 * @param dataRetrieved whether actual data (by opposition to data checksum)
6363 * was present in the received responses.
64- * @param nbRetry the number of retry already performed for this operation.
64+ * @param nbRetry the number of retries already performed for this operation.
6565 * @return {@code RetryDecision.retry(cl)} if no retry attempt has yet been tried and
6666 * {@code receivedResponses >= requiredResponses && !dataRetrieved}, {@code RetryDecision.rethrow()} otherwise.
6767 */
@@ -79,12 +79,12 @@
7979 * This method triggers a maximum of one retry, and only in the case of
8080 * a {@code WriteType.BATCH_LOG} write. The reasoning for the retry in
8181 * that case is that write to the distributed batch log is tried by the
82- * coordinator of the write against a small subset of all the node alive
82+ * coordinator of the write against a small subset of all the nodes alive
8383 * in the local datacenter. Hence, a timeout usually means that none of
8484 * the nodes in that subset were alive but the coordinator hasn't
8585 * detected them as dead. By the time we get the timeout the dead
8686 * nodes will likely have been detected as dead and the retry has thus a
87- * high change of success.
87+ * high chance of success.
8888 *
8989 * @param statement the original query that timed out.
9090 * @param cl the original consistency level of the write that timed out.
@@ -110,8 +110,14 @@
110110 * Defines whether to retry and at which consistency level on an
111111 * unavailable exception.
112112 * <p>
113- * This method never retries as a retry on an unavailable exception
114- * using the same consistency level has almost no change of success.
113+ * This method triggers a retry iff no retry has been executed before
114+ * (nbRetry == 0), with {@link RetryDecision#tryNextHost}, otherwise it
115+ * throws an exception. The retry will be processed on the next host
116+ * in the query plan according to the current Load Balancing Policy.
117+ * Where retrying on the same host in the event of an Unavailable exception
118+ * has almost no chance of success, if the first replica tried happens to
119+ * be "network" isolated from all the other nodes but can still answer to
120+ * the client, it makes sense to retry the query on another node.
115121 *
116122 * @param statement the original query for which the consistency level cannot
117123 * be achieved.
@@ -125,7 +131,9 @@
125131 */
126132 @Override
127133 public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
128- return RetryDecision.rethrow();
134+ return (nbRetry == 0)
135+ ? RetryDecision.tryNextHost(cl)
136+ : RetryDecision.rethrow();
129137 }
130138
131139 @Override
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +6 −6
@@ -76,9 +76,9 @@
7676 private RetryDecision maxLikelyToWorkCL(int knownOk) {
7777 if (knownOk >= 3)
7878 return RetryDecision.retry(ConsistencyLevel.THREE);
79- else if (knownOk >= 2)
79+ else if (knownOk == 2)
8080 return RetryDecision.retry(ConsistencyLevel.TWO);
81- else if (knownOk >= 1)
81+ else if (knownOk == 1)
8282 return RetryDecision.retry(ConsistencyLevel.ONE);
8383 else
8484 return RetryDecision.rethrow();
@@ -134,9 +134,9 @@
134134 * and at least one replica acknowledged, the write is retried with a
135135 * lower consistency level (with unlogged batch, a write timeout can
136136 * <b>always</b> mean that part of the batch haven't been persisted at
137- * all, even if {@code receivedAcks > 0}). For other {@code writeType},
138- * if we know the write has been persisted on at least one replica, we
139- * ignore the exception. Otherwise, an exception is thrown.
137+ * all, even if {@code receivedAcks > 0}). For other write types ({@code WriteType.SIMPLE}
138+ * and {@code WriteType.BATCH}), if we know the write has been persisted on at
139+ * least one replica, we ignore the exception. Otherwise, an exception is thrown.
140140 *
141141 * @param statement the original query that timed out.
142142 * @param cl the original consistency level of the write that timed out.
@@ -157,7 +157,7 @@
157157 case SIMPLE:
158158 case BATCH:
159159 // Since we provide atomicity there is no point in retrying
160- return RetryDecision.ignore();
160+ return receivedAcks > 0 ? RetryDecision.ignore() : RetryDecision.rethrow();
161161 case UNLOGGED_BATCH:
162162 // Since only part of the batch could have been persisted,
163163 // retry with whatever consistency should allow to persist all
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +108 −54
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.google.common.base.Objects;
19+
1820 import com.datastax.driver.core.AtomicMonotonicTimestampGenerator;
1921 import com.datastax.driver.core.ServerSideTimestampGenerator;
2022 import com.datastax.driver.core.TimestampGenerator;
@@ -24,6 +26,15 @@
2426 */
2527 public class Policies {
2628
29+ /**
30+ * Returns a builder to create a new {@code Policies} object.
31+ *
32+ * @return the builder.
33+ */
34+ public static Builder builder() {
35+ return new Builder();
36+ }
37+
2738 private static final ReconnectionPolicy DEFAULT_RECONNECTION_POLICY = new ExponentialReconnectionPolicy(1000, 10 * 60 * 1000);
2839 private static final RetryPolicy DEFAULT_RETRY_POLICY = DefaultRetryPolicy.INSTANCE;
2940 private static final AddressTranslator DEFAULT_ADDRESS_TRANSLATOR = new IdentityTranslator();
@@ -36,59 +47,7 @@
3647 private final TimestampGenerator timestampGenerator;
3748 private final SpeculativeExecutionPolicy speculativeExecutionPolicy;
3849
39- public Policies() {
40- this(defaultLoadBalancingPolicy(), defaultReconnectionPolicy(), defaultRetryPolicy(), defaultAddressTranslator(), defaultTimestampGenerator(), defaultSpeculativeExecutionPolicy());
41- }
42-
43- /**
44- * Creates a new {@code Policies} object using the provided policies.
45- * <p>
46- * This constructor use the default {@link IdentityTranslator} and {@link TimestampGenerator}.
47- *
48- * @param loadBalancingPolicy the load balancing policy to use.
49- * @param reconnectionPolicy the reconnection policy to use.
50- * @param retryPolicy the retry policy to use.
51- */
52- public Policies(LoadBalancingPolicy loadBalancingPolicy,
53- ReconnectionPolicy reconnectionPolicy,
54- RetryPolicy retryPolicy,
55- SpeculativeExecutionPolicy speculativeExecutionPolicy) {
56- this(loadBalancingPolicy, reconnectionPolicy, retryPolicy, DEFAULT_ADDRESS_TRANSLATOR, speculativeExecutionPolicy);
57- }
58-
59- /**
60- * Creates a new {@code Policies} object using the provided policies.
61- *
62- * @param loadBalancingPolicy the load balancing policy to use.
63- * @param reconnectionPolicy the reconnection policy to use.
64- * @param retryPolicy the retry policy to use.
65- * @param addressTranslator the address translator to use.
66- */
67- public Policies(LoadBalancingPolicy loadBalancingPolicy,
68- ReconnectionPolicy reconnectionPolicy,
69- RetryPolicy retryPolicy,
70- AddressTranslator addressTranslator,
71- SpeculativeExecutionPolicy speculativeExecutionPolicy) {
72- // NB: this constructor is provided for backward compatibility with 2.1.0
73- this.loadBalancingPolicy = loadBalancingPolicy;
74- this.reconnectionPolicy = reconnectionPolicy;
75- this.retryPolicy = retryPolicy;
76- this.addressTranslator = addressTranslator;
77- this.speculativeExecutionPolicy = speculativeExecutionPolicy;
78- this.timestampGenerator = defaultTimestampGenerator();
79- }
80-
81- /**
82- * Creates a new {@code Policies} object using the provided policies.
83- *
84- * @param loadBalancingPolicy the load balancing policy to use.
85- * @param reconnectionPolicy the reconnection policy to use.
86- * @param retryPolicy the retry policy to use.
87- * @param addressTranslator the address translator to use.
88- * @param timestampGenerator the timestamp generator to use.
89- * @param speculativeExecutionPolicy the speculative execution policy to use.
90- */
91- public Policies(LoadBalancingPolicy loadBalancingPolicy,
50+ private Policies(LoadBalancingPolicy loadBalancingPolicy,
9251 ReconnectionPolicy reconnectionPolicy,
9352 RetryPolicy retryPolicy,
9453 AddressTranslator addressTranslator,
@@ -109,7 +68,7 @@
10968 * awareness (so {@code new TokenAwarePolicy(new DCAwareRoundRobinPolicy())}).
11069 * <p>
11170 * Note that this policy shuffles the replicas when token awareness is used, see
112- * {@link TokenAwarePolicy#TokenAwarePolicy(LoadBalancingPolicy,boolean)} for an
71+ * {@link TokenAwarePolicy#TokenAwarePolicy(LoadBalancingPolicy, boolean)} for an
11372 * explanation of the tradeoffs.
11473 *
11574 * @return the default load balancing policy.
@@ -236,4 +195,99 @@
236195 public SpeculativeExecutionPolicy getSpeculativeExecutionPolicy() {
237196 return speculativeExecutionPolicy;
238197 }
198+
199+ /**
200+ * A builder to create a new {@code Policies} object.
201+ */
202+ public static class Builder {
203+ private LoadBalancingPolicy loadBalancingPolicy;
204+ private ReconnectionPolicy reconnectionPolicy;
205+ private RetryPolicy retryPolicy;
206+ private AddressTranslator addressTranslator;
207+ private TimestampGenerator timestampGenerator;
208+ private SpeculativeExecutionPolicy speculativeExecutionPolicy;
209+
210+ /**
211+ * Sets the load balancing policy.
212+ *
213+ * @param loadBalancingPolicy see {@link #getLoadBalancingPolicy()}.
214+ * @return this builder.
215+ */
216+ public Builder withLoadBalancingPolicy(LoadBalancingPolicy loadBalancingPolicy) {
217+ this.loadBalancingPolicy = loadBalancingPolicy;
218+ return this;
219+ }
220+
221+ /**
222+ * Sets the reconnection policy.
223+ *
224+ * @param reconnectionPolicy see {@link #getReconnectionPolicy()}.
225+ * @return this builder.
226+ */
227+ public Builder withReconnectionPolicy(ReconnectionPolicy reconnectionPolicy) {
228+ this.reconnectionPolicy = reconnectionPolicy;
229+ return this;
230+ }
231+
232+ /**
233+ * Sets the retry policy.
234+ *
235+ * @param retryPolicy see {@link #getRetryPolicy()}.
236+ * @return this builder.
237+ */
238+ public Builder withRetryPolicy(RetryPolicy retryPolicy) {
239+ this.retryPolicy = retryPolicy;
240+ return this;
241+ }
242+
243+ /**
244+ * Sets the address translator.
245+ *
246+ * @param addressTranslator see {@link #getAddressTranslator()}.
247+ * @return this builder.
248+ */
249+ public Builder withAddressTranslator(AddressTranslator addressTranslator) {
250+ this.addressTranslator = addressTranslator;
251+ return this;
252+ }
253+
254+ /**
255+ * Sets the timestamp generator.
256+ *
257+ * @param timestampGenerator see {@link #getTimestampGenerator()}.
258+ * @return this builder.
259+ */
260+ public Builder withTimestampGenerator(TimestampGenerator timestampGenerator) {
261+ this.timestampGenerator = timestampGenerator;
262+ return this;
263+ }
264+
265+ /**
266+ * Sets the speculative execution policy.
267+ *
268+ * @param speculativeExecutionPolicy see {@link #getSpeculativeExecutionPolicy()}.
269+ * @return this builder.
270+ */
271+ public Builder withSpeculativeExecutionPolicy(SpeculativeExecutionPolicy speculativeExecutionPolicy) {
272+ this.speculativeExecutionPolicy = speculativeExecutionPolicy;
273+ return this;
274+ }
275+
276+ /**
277+ * Builds the final object from this builder.
278+ * <p>
279+ * Any field that hasn't been set explicitly will get its default value.
280+ *
281+ * @return the object.
282+ */
283+ public Policies build() {
284+ 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()));
291+ }
292+ }
239293 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +30 −9
@@ -43,18 +43,20 @@
4343 * exception will return an empty result set.</li>
4444 * </ul>
4545 */
46- public static class RetryDecision {
46+ class RetryDecision {
4747 /**
4848 * The type of retry decisions.
4949 */
50- public static enum Type { RETRY, RETHROW, IGNORE };
50+ public enum Type { RETRY, RETHROW, IGNORE };
5151
5252 private final Type type;
5353 private final ConsistencyLevel retryCL;
54+ private final boolean retryCurrent;
5455
55- private RetryDecision(Type type, ConsistencyLevel retryCL) {
56+ private RetryDecision(Type type, ConsistencyLevel retryCL, boolean retryCurrent){
5657 this.type = type;
5758 this.retryCL = retryCL;
59+ this.retryCurrent = retryCurrent;
5860 }
5961
6062 /**
@@ -76,13 +78,22 @@
7678 return retryCL;
7779 }
7880
81+ /**
82+ * Whether the retry policy uses the same host for retry decision.
83+ *
84+ * @return the retry on next host boolean. Default is false.
85+ */
86+ public boolean isRetryCurrent() {
87+ return retryCurrent;
88+ }
89+
7990 /**
8091 * Creates a RETHROW retry decision.
8192 *
8293 * @return a RETHROW retry decision.
8394 */
8495 public static RetryDecision rethrow() {
85- return new RetryDecision(Type.RETHROW, null);
96+ return new RetryDecision(Type.RETHROW, null, true);
8697 }
8798
8899 /**
@@ -92,7 +103,7 @@
92103 * @return a RETRY with consistency level {@code consistency} retry decision.
93104 */
94105 public static RetryDecision retry(ConsistencyLevel consistency) {
95- return new RetryDecision(Type.RETRY, consistency);
106+ return new RetryDecision(Type.RETRY, consistency, true);
96107 }
97108
98109 /**
@@ -101,15 +112,25 @@
101112 * @return an IGNORE retry decision.
102113 */
103114 public static RetryDecision ignore() {
104- return new RetryDecision(Type.IGNORE, null);
115+ return new RetryDecision(Type.IGNORE, null, true);
116+ }
117+
118+ /**
119+ * Creates a RETRY retry decision and indicates to retry on another host
120+ * using the provided consistency level.
121+ *
122+ * @return a RETRY retry decision.
123+ */
124+ public static RetryDecision tryNextHost(ConsistencyLevel retryCL) {
125+ return new RetryDecision(Type.RETRY, retryCL, false);
105126 }
106127
107128 @Override
108129 public String toString() {
109130 switch (type) {
110- case RETRY: return "Retry at " + retryCL;
111- case RETHROW: return "Rethrow";
112- case IGNORE: return "Ignore";
131+ case RETRY: return "Retry at " + retryCL + " on " + (retryCurrent ? "same " : "next ") + "host.";
132+ case RETHROW: return "Rethrow";
133+ case IGNORE: return "Ignore";
113134 }
114135 throw new AssertionError();
115136 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java +1 −1
@@ -63,7 +63,7 @@
6363
6464 @Override
6565 boolean isIdempotent() {
66- return true;
66+ return Utils.isIdempotent(value);
6767 }
6868 }
6969
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +60 −1
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.List;
2019
2120 public abstract class Clause extends Utils.Appendeable {
@@ -111,6 +110,66 @@
111110 }
112111 }
113112
113+ static class ContainsClause extends AbstractClause {
114+
115+ private final Object value;
116+
117+ ContainsClause(String name, Object value) {
118+ super(name);
119+ this.value = value;
120+
121+ if (value == null)
122+ throw new IllegalArgumentException("Missing value for CONTAINS clause");
123+ }
124+
125+ @Override
126+ void appendTo(StringBuilder sb, List<Object> variables) {
127+ Utils.appendName(name, sb).append(" CONTAINS ");
128+ Utils.appendValue(value, sb, variables);
129+ }
130+
131+ @Override
132+ Object firstValue() {
133+ return value;
134+ }
135+
136+ @Override
137+ boolean containsBindMarker() {
138+ return Utils.containsBindMarker(value);
139+ }
140+ }
141+
142+
143+ static class ContainsKeyClause extends AbstractClause {
144+
145+ private final Object value;
146+
147+ ContainsKeyClause(String name, Object value) {
148+ super(name);
149+ this.value = value;
150+
151+ if (value == null)
152+ throw new IllegalArgumentException("Missing value for CONTAINS KEY clause");
153+ }
154+
155+ @Override
156+ void appendTo(StringBuilder sb, List<Object> variables) {
157+ Utils.appendName(name, sb).append(" CONTAINS KEY ");
158+ Utils.appendValue(value, sb, variables);
159+ }
160+
161+ @Override
162+ Object firstValue() {
163+ return value;
164+ }
165+
166+ @Override
167+ boolean containsBindMarker() {
168+ return Utils.containsBindMarker(value);
169+ }
170+ }
171+
172+
114173 static class CompoundClause extends Clause {
115174 private String op;
116175 private final List<String> names;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +130 −27
@@ -26,25 +26,25 @@
2626 public class Delete extends BuiltStatement {
2727
2828 private final String table;
29- private final List<?> columnNames;
29+ private final List<Selector> columns;
3030 private final Where where;
3131 private final Options usings;
3232 private final Conditions conditions;
3333 private boolean ifExists;
3434
35- Delete(String keyspace, String table, List<?> columnNames) {
35+ Delete(String keyspace, String table, List<Selector> columns) {
3636 super(keyspace);
3737 this.table = table;
38- this.columnNames = columnNames;
38+ this.columns = columns;
3939 this.where = new Where(this);
4040 this.usings = new Options(this);
4141 this.conditions = new Conditions(this);
4242 }
4343
44- Delete(TableMetadata table, List<Object> columnNames) {
44+ Delete(TableMetadata table, List<Selector> columns) {
4545 super(table);
4646 this.table = escapeId(table.getName());
47- this.columnNames = columnNames;
47+ this.columns = columns;
4848 this.where = new Where(this);
4949 this.usings = new Options(this);
5050 this.conditions = new Conditions(this);
@@ -55,8 +55,8 @@
5555 StringBuilder builder = new StringBuilder();
5656
5757 builder.append("DELETE");
58- if (columnNames != null)
59- Utils.joinAndAppendNames(builder.append(" "), ",", columnNames);
58+ if (!columns.isEmpty())
59+ Utils.joinAndAppend(builder.append(" "), ",", columns, variables);
6060
6161 builder.append(" FROM ");
6262 if (keyspace != null)
@@ -136,6 +136,17 @@
136136 return usings.and(using);
137137 }
138138
139+ /**
140+ * Returns the options for this DELETE statement.
141+ * <p/>
142+ * Chain this with {@link Options#and(Using)} to add options.
143+ *
144+ * @return the options of this DELETE statement.
145+ */
146+ public Options using() {
147+ return usings;
148+ }
149+
139150 /**
140151 * Sets the 'IF EXISTS' option for this DELETE statement.
141152 *
@@ -263,12 +274,15 @@
263274 */
264275 public static class Builder {
265276
266- List<Object> columnNames;
277+ List<Selector> columns = new ArrayList<Selector>();
267278
268- Builder() {}
279+ Builder() {
280+ }
269281
270- Builder(List<Object> columnNames) {
271- this.columnNames = columnNames;
282+ Builder(String... columnNames) {
283+ for (String columnName : columnNames) {
284+ this.columns.add(new Selector(columnName));
285+ }
272286 }
273287
274288 /**
@@ -289,7 +303,7 @@
289303 * @return a newly built DELETE statement that deletes from {@code keyspace.table}.
290304 */
291305 public Delete from(String keyspace, String table) {
292- return new Delete(keyspace, table, columnNames);
306+ return new Delete(keyspace, table, columns);
293307 }
294308
295309 /**
@@ -299,7 +313,7 @@
299313 * @return a newly built DELETE statement that deletes from {@code table}.
300314 */
301315 public Delete from(TableMetadata table) {
302- return new Delete(table, columnNames);
316+ return new Delete(table, columns);
303317 }
304318 }
305319
@@ -316,23 +330,20 @@
316330 * @throws IllegalStateException if some columns had already been selected for this builder.
317331 */
318332 public Builder all() {
319- if (columnNames != null)
320- throw new IllegalStateException(String.format("Some columns (%s) have already been selected.", columnNames));
333+ if (!columns.isEmpty())
334+ throw new IllegalStateException(String.format("Some columns (%s) have already been selected.", columns));
321335
322- return (Builder)this;
336+ return this;
323337 }
324338
325339 /**
326340 * Deletes the provided column.
327341 *
328- * @param name the column name to select for deletion.
342+ * @param columnName the column to select for deletion.
329343 * @return this in-build DELETE Selection
330344 */
331- public Selection column(String name) {
332- if (columnNames == null)
333- columnNames = new ArrayList<Object>();
334-
335- columnNames.add(name);
345+ public Selection column(String columnName) {
346+ columns.add(new Selector(columnName));
336347 return this;
337348 }
338349
@@ -344,9 +355,46 @@
344355 * @return this in-build DELETE Selection
345356 */
346357 public Selection listElt(String columnName, int idx) {
347- StringBuilder sb = new StringBuilder();
348- Utils.appendName(columnName, sb);
349- return column(sb.append('[').append(idx).append(']').toString());
358+ columns.add(new CollectionElementSelector(columnName, idx));
359+ return this;
360+ }
361+
362+ /**
363+ * Deletes the provided list element,
364+ * specified as a bind marker.
365+ *
366+ * @param columnName the name of the list column.
367+ * @param idx the index of the element to delete.
368+ * @return this in-build DELETE Selection
369+ */
370+ public Selection listElt(String columnName, BindMarker idx) {
371+ columns.add(new CollectionElementSelector(columnName, idx));
372+ return this;
373+ }
374+
375+ /**
376+ * Deletes the provided set element.
377+ *
378+ * @param columnName the name of the set column.
379+ * @param element the element to delete.
380+ * @return this in-build DELETE Selection
381+ */
382+ public Selection setElt(String columnName, Object element) {
383+ columns.add(new CollectionElementSelector(columnName, element));
384+ return this;
385+ }
386+
387+ /**
388+ * Deletes the provided set element,
389+ * specified as a bind marker.
390+ *
391+ * @param columnName the name of the set column.
392+ * @param element the element to delete.
393+ * @return this in-build DELETE Selection
394+ */
395+ public Selection setElt(String columnName, BindMarker element) {
396+ columns.add(new CollectionElementSelector(columnName, element));
397+ return this;
350398 }
351399
352400 /**
@@ -357,12 +405,67 @@
357405 * @return this in-build DELETE Selection
358406 */
359407 public Selection mapElt(String columnName, Object key) {
360- StringBuilder sb = new StringBuilder();
408+ columns.add(new CollectionElementSelector(columnName, key));
409+ return this;
410+ }
411+ }
412+
413+ /**
414+ * A selector in a DELETE selection clause.
415+ * A selector can be either a column name,
416+ * a list element, a set element or a map entry.
417+ */
418+ static class Selector extends Utils.Appendeable {
419+
420+ private final String columnName;
421+
422+ Selector(String columnName) {
423+ this.columnName = columnName;
424+ }
425+
426+ @Override
427+ void appendTo(StringBuilder sb, List<Object> values) {
361428 Utils.appendName(columnName, sb);
429+ }
430+
431+ @Override
432+ boolean containsBindMarker() {
433+ return false;
434+ }
435+
436+ @Override
437+ public String toString() {
438+ StringBuilder sb = new StringBuilder();
439+ appendTo(sb, new ArrayList<Object>());
440+ return sb.toString();
441+ }
442+ }
443+
444+ /**
445+ * A selector representing a list index, a set element or a map key in a DELETE selection clause.
446+ */
447+ static class CollectionElementSelector extends Selector {
448+
449+ private final Object key;
450+
451+ CollectionElementSelector(String columnName, Object key) {
452+ super(columnName);
453+ this.key = key;
454+ }
455+
456+ @Override
457+ void appendTo(StringBuilder sb, List<Object> values) {
458+ super.appendTo(sb, values);
362459 sb.append('[');
363460 Utils.appendValue(key, sb);
364- return column(sb.append(']').toString());
461+ sb.append(']');
462+ }
463+
464+ @Override
465+ boolean containsBindMarker() {
466+ return Utils.containsBindMarker(key);
365467 }
468+
366469 }
367470
368471 /**
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +36 −10
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.ArrayList;
2019 import java.util.Arrays;
2120 import java.util.List;
@@ -80,6 +79,8 @@
8079 names.add(name);
8180 values.add(value);
8281 checkForBindMarkers(value);
82+ if (!hasNonIdempotentOps() && !Utils.isIdempotent(value))
83+ this.setNonIdempotentOps();
8384 maybeAddRoutingKey(name, value);
8485 return this;
8586 }
@@ -92,18 +93,33 @@
9293 * value in {@code values} will be inserted for the {@code i}th column
9394 * in {@code names}.
9495 * @return this INSERT statement.
95- *
9696 * @throws IllegalArgumentException if {@code names.length != values.length}.
9797 */
9898 public Insert values(String[] names, Object[] values) {
99- if (names.length != values.length)
100- throw new IllegalArgumentException(String.format("Got %d names but %d values", names.length, values.length));
101- this.names.addAll(Arrays.asList(names));
102- this.values.addAll(Arrays.asList(values));
103-
104- for (int i = 0; i < names.length; i++) {
105- checkForBindMarkers(values[i]);
106- maybeAddRoutingKey(names[i], values[i]);
99+ return values(Arrays.asList(names), Arrays.asList(values));
100+ }
101+
102+ /**
103+ * Adds multiple column/value pairs to the values inserted by this INSERT statement.
104+ *
105+ * @param names a list of column names to insert/update.
106+ * @param values a list of values to insert/update. The {@code i}th
107+ * value in {@code values} will be inserted for the {@code i}th column
108+ * in {@code names}.
109+ * @return this INSERT statement.
110+ * @throws IllegalArgumentException if {@code names.size() != values.size()}.
111+ */
112+ public Insert values(List<String> names, List<Object> values) {
113+ if (names.size() != values.size())
114+ throw new IllegalArgumentException(String.format("Got %d names but %d values", names.size(), values.size()));
115+ this.names.addAll(names);
116+ this.values.addAll(values);
117+ for (int i = 0; i < names.size(); i++) {
118+ Object value = values.get(i);
119+ checkForBindMarkers(value);
120+ maybeAddRoutingKey(names.get(i), value);
121+ if (!hasNonIdempotentOps() && !Utils.isIdempotent(value))
122+ this.setNonIdempotentOps();
107123 }
108124 return this;
109125 }
@@ -118,6 +134,16 @@
118134 return usings.and(using);
119135 }
120136
137+ /**
138+ * Returns the options for this INSERT statement.
139+ * <p/>
140+ * Chain this with {@link Options#and(Using)} to add options.
141+ *
142+ * @return the options of this INSERT statement.
143+ */
144+ public Options using() {
145+ return usings;
146+ }
121147 /**
122148 * Sets the 'IF NOT EXISTS' option for this INSERT statement.
123149 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java +0 −1
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.List;
2019
2120 public class Ordering extends Utils.Appendeable {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +78 −21
@@ -19,6 +19,7 @@
1919
2020 import com.datastax.driver.core.RegularStatement;
2121 import com.datastax.driver.core.TableMetadata;
22+import com.datastax.driver.core.exceptions.InvalidQueryException;
2223
2324 /**
2425 * Static methods to build a CQL3 query.
@@ -136,7 +137,7 @@
136137 * clause needs to be provided to complete the query).
137138 */
138139 public static Delete.Builder delete(String... columns) {
139- return new Delete.Builder(Arrays.asList((Object[])columns));
140+ return new Delete.Builder(columns);
140141 }
141142
142143 /**
@@ -226,11 +227,7 @@
226227 * @return the quoted column name.
227228 */
228229 public static String quote(String columnName) {
229- StringBuilder sb = new StringBuilder();
230- sb.append('"');
231- Utils.appendName(columnName, sb);
232- sb.append('"');
233- return sb.toString();
230+ return '"' + columnName + '"';
234231 }
235232
236233 /**
@@ -299,6 +296,30 @@
299296 return new Clause.InClause(name, values);
300297 }
301298
299+ /**
300+ * Creates a "contains" where clause stating the provided column must contain
301+ * the value provided.
302+ *
303+ * @param name the column name
304+ * @param value the value
305+ * @return the corresponding where clause.
306+ */
307+ public static Clause contains(String name, Object value) {
308+ return new Clause.ContainsClause(name, value);
309+ }
310+
311+ /**
312+ * Creates a "contains key" where clause stating the provided column must contain
313+ * the key provided.
314+ *
315+ * @param name the column name
316+ * @param key the key
317+ * @return the corresponding where clause.
318+ */
319+ public static Clause containsKey(String name, Object key) {
320+ return new Clause.ContainsKeyClause(name, key);
321+ }
322+
302323 /**
303324 * Creates a "lesser than" where clause stating the provided column must be less than
304325 * the provided value.
@@ -596,12 +617,16 @@
596617 * This will generate: {@code name = [ value ] + name}.
597618 *
598619 * @param name the column name (must be of type list).
599- * @param value the value to prepend
620+ * @param value the value to prepend. Using a BindMarker here is not supported.
621+ * To use a BindMarker use {@code QueryBuilder#prependAll} with a
622+ * singleton list.
600623 * @return the correspond assignment (to use in an update query)
601624 */
602625 public static Assignment prepend(String name, Object value) {
603- Object v = value instanceof BindMarker ? value : Collections.singletonList(value);
604- return new Assignment.ListPrependAssignment(name, v);
626+ if (value instanceof BindMarker) {
627+ throw new InvalidQueryException("binding a value in prepend() is not supported, use prependAll() and bind a singleton list");
628+ }
629+ return prependAll(name, Collections.singletonList(value));
605630 }
606631
607632 /**
@@ -636,12 +661,16 @@
636661 * This will generate: {@code name = name + [value]}.
637662 *
638663 * @param name the column name (must be of type list).
639- * @param value the value to append
664+ * @param value the value to append. Using a BindMarker here is not supported.
665+ * To use a BindMarker use {@code QueryBuilder#appendAll} with a
666+ * singleton list.
640667 * @return the correspond assignment (to use in an update query)
641668 */
642669 public static Assignment append(String name, Object value) {
643- Object v = value instanceof BindMarker ? value : Collections.singletonList(value);
644- return new Assignment.CollectionAssignment(name, v, true, false);
670+ if (value instanceof BindMarker) {
671+ throw new InvalidQueryException("Binding a value in append() is not supported, use appendAll() and bind a singleton list");
672+ }
673+ return appendAll(name, Collections.singletonList(value));
645674 }
646675
647676 /**
@@ -676,12 +705,15 @@
676705 * This will generate: {@code name = name - [value]}.
677706 *
678707 * @param name the column name (must be of type list).
679- * @param value the value to discard
708+ * @param value the value to discard. Using a BindMarker here is not supported.
709+ * To use a BindMarker use {@code QueryBuilder#discardAll} with a singleton list.
680710 * @return the correspond assignment (to use in an update query)
681711 */
682712 public static Assignment discard(String name, Object value) {
683- Object v = value instanceof BindMarker ? value : Collections.singletonList(value);
684- return new Assignment.CollectionAssignment(name, v, false);
713+ if (value instanceof BindMarker) {
714+ throw new InvalidQueryException("Binding a value in discard() is not supported, use discardAll() and bind a singleton list");
715+ }
716+ return discardAll(name, Collections.singletonList(value));
685717 }
686718
687719 /**
@@ -730,12 +762,16 @@
730762 * This will generate: {@code name = name + {value}}.
731763 *
732764 * @param name the column name (must be of type set).
733- * @param value the value to add
765+ * @param value the value to add. Using a BindMarker here is not supported.
766+ * To use a BindMarker use {@code QueryBuilder#addAll} with a
767+ * singleton set.
734768 * @return the correspond assignment (to use in an update query)
735769 */
736770 public static Assignment add(String name, Object value) {
737- Object v = value instanceof BindMarker ? value : Collections.singleton(value);
738- return new Assignment.CollectionAssignment(name, v, true);
771+ if (value instanceof BindMarker){
772+ throw new InvalidQueryException("Binding a value in add() is not supported, use addAll() and bind a singleton list");
773+ }
774+ return addAll(name, Collections.singleton(value));
739775 }
740776
741777 /**
@@ -770,12 +806,15 @@
770806 * This will generate: {@code name = name - {value}}.
771807 *
772808 * @param name the column name (must be of type set).
773- * @param value the value to remove
809+ * @param value the value to remove. Using a BindMarker here is not supported.
810+ * To use a BindMarker use {@code QueryBuilder#removeAll} with a singleton set.
774811 * @return the correspond assignment (to use in an update query)
775812 */
776813 public static Assignment remove(String name, Object value) {
777- Object v = value instanceof BindMarker ? value : Collections.singleton(value);
778- return new Assignment.CollectionAssignment(name, v, false);
814+ if (value instanceof BindMarker) {
815+ throw new InvalidQueryException("Binding a value in remove() is not supported, use removeAll() and bind a singleton set");
816+ }
817+ return removeAll(name, Collections.singleton(value));
779818 }
780819
781820 /**
@@ -920,6 +959,24 @@
920959 return new Utils.FCall(name, parameters);
921960 }
922961
962+ /**
963+ * Creates a {@code now()} function call.
964+ *
965+ * @return the function call.
966+ */
967+ public static Object now() {
968+ return new Utils.FCall("now");
969+ }
970+
971+ /**
972+ * Creates a {@code uuid()} function call.
973+ *
974+ * @return the function call.
975+ */
976+ public static Object uuid() {
977+ return new Utils.FCall("uuid");
978+ }
979+
923980 /**
924981 * Declares that the name in argument should be treated as a column name.
925982 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +25 −0
@@ -264,6 +264,16 @@
264264 this.columnNames = columnNames;
265265 }
266266
267+ /**
268+ * Uses DISTINCT selection.
269+ *
270+ * @return this in-build SELECT statement.
271+ */
272+ public Builder distinct() {
273+ this.isDistinct = true;
274+ return this;
275+ }
276+
267277 /**
268278 * Adds the table to select from.
269279 *
@@ -460,6 +470,21 @@
460470 return queueName(name);
461471 }
462472
473+ /**
474+ * Selects the provided raw expression.
475+ *
476+ * This method is used internally by the mapper module. It is not exposed on the parent class {@link Selection} to
477+ * avoid breaking binary compatibility. This means that it is not accessible directly via the fluent API (you need
478+ * a cast). This shouldn't be a problem for regular clients because they will use other methods of the DSL
479+ * ({@code fcall}, etc.) rather than provide a raw string.
480+ *
481+ * @param rawString the raw expression to add.
482+ * @return this in-build SELECT statement
483+ */
484+ public SelectionOrAlias raw(String rawString) {
485+ return queueName(QueryBuilder.raw(rawString));
486+ }
487+
463488 /**
464489 * Selects the write time of provided column.
465490 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +1 −1
@@ -175,7 +175,7 @@
175175 */
176176 public Assignments and(Assignment assignment) {
177177 statement.setCounterOp(assignment instanceof CounterAssignment);
178- if (!assignment.isIdempotent())
178+ if (!hasNonIdempotentOps() && !Utils.isIdempotent(assignment))
179179 statement.setNonIdempotentOps();
180180 assignments.add(assignment);
181181 checkForBindMarkers(assignment);
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java +0 −1
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import java.nio.ByteBuffer;
1918 import java.util.List;
2019
2120 public abstract class Using extends Utils.Appendeable {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +36 −1
@@ -22,6 +22,8 @@
2222 import java.util.*;
2323 import java.util.regex.Pattern;
2424
25+import static com.google.common.base.Preconditions.checkNotNull;
26+
2527 import com.datastax.driver.core.DataType;
2628 import com.datastax.driver.core.ProtocolVersion;
2729 import com.datastax.driver.core.TupleValue;
@@ -59,11 +61,14 @@
5961 return sb;
6062 }
6163
62- // Returns null if it's not really serializable (function call, bind markers, ...)
64+ // Returns false if it's not really serializable (function call, bind markers, ...)
6365 static boolean isSerializable(Object value) {
6466 if (value instanceof BindMarker || value instanceof FCall || value instanceof CName)
6567 return false;
6668
69+ if (value instanceof RawString)
70+ return false;
71+
6772 // We also don't serialize fixed size number types. The reason is that if we do it, we will
6873 // force a particular size (4 bytes for ints, ...) and for the query builder, we don't want
6974 // users to have to bother with that.
@@ -261,6 +266,31 @@
261266 return false;
262267 }
263268
269+ static boolean isIdempotent(Object value) {
270+ if(value == null) {
271+ return true;
272+ } else if (value instanceof Assignment) {
273+ Assignment assignment = (Assignment)value;
274+ return assignment.isIdempotent();
275+ } else if (value instanceof FCall) {
276+ return false;
277+ } else if (value instanceof RawString) {
278+ return false;
279+ } else if(value instanceof Collection) {
280+ for (Object elt : ((Collection)value)) {
281+ if(!isIdempotent(elt))
282+ return false;
283+ }
284+ return true;
285+ } else if (value instanceof Map) {
286+ for (Map.Entry<?, ?> entry : ((Map<?, ?>)value).entrySet()) {
287+ if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue()))
288+ return false;
289+ }
290+ }
291+ return true;
292+ }
293+
264294 private static StringBuilder appendValueString(String value, StringBuilder sb) {
265295 return sb.append(DataType.text().format(value));
266296 }
@@ -304,6 +334,8 @@
304334 Alias alias = (Alias)name;
305335 appendName(alias.column, sb);
306336 sb.append(" AS ").append(alias.alias);
337+ } else if (name instanceof RawString) {
338+ sb.append(((RawString)name).str);
307339 } else {
308340 throw new IllegalArgumentException(String.format("Invalid column %s of type unknown of the query builder", name));
309341 }
@@ -329,10 +361,12 @@
329361 }
330362
331363 static class FCall {
364+
332365 private final String name;
333366 private final Object[] parameters;
334367
335368 FCall(String name, Object... parameters) {
369+ checkNotNull(name);
336370 this.name = name;
337371 this.parameters = parameters;
338372 }
@@ -349,6 +383,7 @@
349383 sb.append(')');
350384 return sb.toString();
351385 }
386+
352387 }
353388
354389 static class CName {
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AbstractCreateStatement.java +1 −1
@@ -68,7 +68,7 @@
6868 validateNotEmpty(columnName, "Column name");
6969 validateNotNull(dataType, "Column type");
7070 validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
71- simpleColumns.put(columnName, new ColumnType.NativeColumnType(dataType));
71+ simpleColumns.put(columnName, new NativeColumnType(dataType));
7272 return self;
7373 }
7474
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/ColumnType.java +0 −12
@@ -26,16 +26,4 @@
2626 */
2727 interface ColumnType {
2828 String asCQLString();
29-
30- class NativeColumnType implements ColumnType {
31- private final String asCQLString;
32-
33- NativeColumnType(DataType nativeType) {
34- asCQLString = nativeType.toString();
35- }
36-
37- @Override public String asCQLString() {
38- return asCQLString;
39- }
40- }
4129 }
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Create.java +3 −3
@@ -66,7 +66,7 @@
6666 validateNotEmpty(columnName, "Partition key name");
6767 validateNotNull(dataType, "Partition key type");
6868 validateNotKeyWord(columnName, String.format("The partition key name '%s' is not allowed because it is a reserved keyword", columnName));
69- partitionColumns.put(columnName, new ColumnType.NativeColumnType(dataType));
69+ partitionColumns.put(columnName, new NativeColumnType(dataType));
7070 return this;
7171 }
7272
@@ -104,7 +104,7 @@
104104 validateNotEmpty(columnName, "Clustering column name");
105105 validateNotNull(dataType, "Clustering column type");
106106 validateNotKeyWord(columnName, String.format("The clustering column name '%s' is not allowed because it is a reserved keyword", columnName));
107- clusteringColumns.put(columnName, new ColumnType.NativeColumnType(dataType));
107+ clusteringColumns.put(columnName, new NativeColumnType(dataType));
108108 return this;
109109 }
110110
@@ -138,7 +138,7 @@
138138 validateNotEmpty(columnName, "Column name");
139139 validateNotNull(dataType, "Column type");
140140 validateNotKeyWord(columnName, String.format("The static column name '%s' is not allowed because it is a reserved keyword", columnName));
141- staticColumns.put(columnName, new ColumnType.NativeColumnType(dataType));
141+ staticColumns.put(columnName, new NativeColumnType(dataType));
142142 return this;
143143 }
144144
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/NativeColumnType.java +33 −0
@@ -0,0 +1,33 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import com.datastax.driver.core.DataType;
19+
20+/**
21+ * Represents a native CQL type in a SchemaBuilder statement.
22+ */
23+class NativeColumnType implements ColumnType {
24+ private final String asCQLString;
25+
26+ NativeColumnType(DataType nativeType) {
27+ asCQLString = nativeType.toString();
28+ }
29+
30+ @Override public String asCQLString() {
31+ return asCQLString;
32+ }
33+}
modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +1 −1
@@ -51,7 +51,7 @@
5151 }
5252
5353 public static void createMultiDCSchema(Session session, int dc1RF, int dc2RF) {
54- session.execute(String.format(CREATE_KEYSPACE_GENERIC_FORMAT, SIMPLE_KEYSPACE, "NetworkTopologyStrategy", String.format("'dc1' : %d, 'dc2' : %d", dc1RF, dc2RF)));
54+ session.execute(String.format(CREATE_KEYSPACE_GENERIC_FORMAT, SIMPLE_KEYSPACE, "NetworkTopologyStrategy", String.format("'datacenter1' : %d, 'datacenter2' : %d", dc1RF, dc2RF)));
5555 session.execute("USE " + SIMPLE_KEYSPACE);
5656 session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, i int)", SIMPLE_TABLE));
5757 }
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +6 −0
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
19+
1820 /**
1921 * Augment AssertJ with custom assertions for the Java driver.
2022 */
@@ -34,6 +36,10 @@
3436 public static DataTypeAssert assertThat(DataType type) {
3537 return new DataTypeAssert(type);
3638 }
39+
40+ public static IndexMetadataAssert assertThat(IndexMetadata indexMetadata) {
41+ return new IndexMetadataAssert(indexMetadata);
42+ }
3743
3844 public static LocalDateAssert assertThat(LocalDate localDate) {
3945 return new LocalDateAssert(localDate);
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +4 −9
@@ -21,7 +21,8 @@
2121 import com.google.common.collect.Lists;
2222 import org.testng.annotations.Test;
2323
24-import static org.testng.Assert.*;
24+import static org.testng.Assert.assertEquals;
25+import static org.testng.Assert.assertTrue;
2526
2627 public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster {
2728
@@ -42,14 +43,8 @@
4243 TimeUnit.MILLISECONDS.sleep(100);
4344
4445 HostConnectionPool pool = getPool(session);
45- if (pool instanceof DynamicConnectionPool) {
46- DynamicConnectionPool p = (DynamicConnectionPool)pool;
47- for (Connection connection : p.connections) {
48- assertEquals(connection.inFlight.get(), 0);
49- }
50- } else if (pool instanceof SingleConnectionPool){
51- SingleConnectionPool p = (SingleConnectionPool)pool;
52- assertEquals(p.connectionRef.get().inFlight.get(), 0);
46+ for (Connection connection : pool.connections) {
47+ assertEquals(connection.inFlight.get(), 0);
5348 }
5449 }
5550
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +14 −25
@@ -15,9 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
19-import java.net.InetSocketAddress;
20-import java.util.Map;
2118 import java.util.concurrent.TimeUnit;
2219
2320 import org.slf4j.Logger;
@@ -36,17 +33,18 @@
3633
3734 private static final Logger logger = LoggerFactory.getLogger(AuthenticationTest.class);
3835
39- private CCMBridge cassandraCluster;
36+ private CCMBridge ccm;
4037
4138 /**
4239 * creates a cluster and turns on password authentication before starting it.
4340 */
4441 @BeforeClass (groups = "short")
4542 public void setupClusterWithAuthentication() throws InterruptedException {
46- cassandraCluster = CCMBridge.create("test");
47- cassandraCluster.populate(1);
48- cassandraCluster.updateConfig("authenticator", "PasswordAuthenticator");
49- cassandraCluster.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
43+ ccm = CCMBridge.builder("test")
44+ .withCassandraConfiguration("authenticator", "PasswordAuthenticator")
45+ .notStarted()
46+ .build();
47+ ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
5048
5149 // Even though we've override the default user setup delay, still wait
5250 // one second to make sure we don't race
@@ -55,51 +53,42 @@
5553
5654 @AfterClass (groups = "short")
5755 public void shutdownCluster() {
58- if (null != cassandraCluster)
59- cassandraCluster.stop();
56+ if (ccm != null)
57+ ccm.stop();
6058 }
6159
6260 @Test(groups = "short")
63- public void testAuthenticatedConnection() throws InterruptedException {
61+ public void should_connect_with_credentials() throws InterruptedException {
6462 try {
6563 Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
6664 .withCredentials("cassandra", "cassandra")
6765 .build()
6866 .connect();
6967 } catch (NoHostAvailableException e) {
70-
71- for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
72- logger.error("Error connecting to " + entry.getKey(), entry.getValue());
73- throw new RuntimeException(e);
68+ logger.error(e.getCustomMessage(1, true, true));
7469 }
7570 }
7671
7772 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
78- public void testConnectionAttemptWithIncorrectCredentialsIsRefused() throws InterruptedException {
73+ public void should_fail_to_connect_with_wrong_credentials() throws InterruptedException {
7974 try {
8075 Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
8176 .withCredentials("bogus", "bogus")
8277 .build()
8378 .connect();
8479 } catch (NoHostAvailableException e) {
85-
86- for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
87- logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue());
88- throw new RuntimeException(e);
80+ logger.error(e.getCustomMessage(1, true, true));
8981 }
9082 }
9183
9284 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
93- public void testConnectionAttemptWithoutCredentialsIsRefused() throws InterruptedException {
85+ public void should_fail_to_connect_without_credentials() throws InterruptedException {
9486 try {
9587 Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
9688 .build()
9789 .connect();
9890 } catch (NoHostAvailableException e) {
99-
100- for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
101- logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue());
102- throw new RuntimeException(e);
91+ logger.error(e.getCustomMessage(1, true, true));
10392 }
10493 }
10594 }
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +184 −138
@@ -38,10 +38,8 @@
3838 import org.testng.annotations.AfterClass;
3939 import org.testng.annotations.BeforeClass;
4040
41-import static com.google.common.base.Preconditions.checkArgument;
4241 import static org.testng.Assert.fail;
4342
44-import com.datastax.driver.core.Cluster.Builder;
4543 import com.datastax.driver.core.exceptions.AlreadyExistsException;
4644 import com.datastax.driver.core.exceptions.DriverException;
4745 import com.datastax.driver.core.exceptions.NoHostAvailableException;
@@ -56,6 +54,8 @@
5654 public static final String IP_PREFIX;
5755
5856 private static final String CASSANDRA_VERSION_REGEXP = "\\d\\.\\d\\.\\d+(-\\w+)?";
57+ static final File CASSANDRA_DIR;
58+ static final String CASSANDRA_VERSION;
5959
6060 public static final String DEFAULT_CLIENT_TRUSTSTORE_PASSWORD = "cassandra1sfun";
6161 public static final String DEFAULT_CLIENT_TRUSTSTORE_PATH = "/client.truststore";
@@ -83,7 +83,27 @@
8383 */
8484 private static final Map<String,String> ENVIRONMENT_MAP;
8585
86+ /**
87+ * The command to use to launch CCM
88+ */
89+ private static final String CCM_COMMAND;
90+
8691 static {
92+ String version = System.getProperty("cassandra.version");
93+ if (version.matches(CASSANDRA_VERSION_REGEXP)) {
94+ CASSANDRA_DIR = null;
95+ CASSANDRA_VERSION = "-v " + version;
96+ } else {
97+ CASSANDRA_DIR = new File(version);
98+ CASSANDRA_VERSION = "";
99+ }
100+
101+ String ip_prefix = System.getProperty("ipprefix");
102+ if (ip_prefix == null || ip_prefix.isEmpty()) {
103+ ip_prefix = "127.0.1.";
104+ }
105+ IP_PREFIX = ip_prefix;
106+
87107 // Inherit the current environment.
88108 Map<String,String> envMap = Maps.newHashMap(new ProcessBuilder().environment());
89109 // If ccm.path is set, override the PATH variable with it.
@@ -93,8 +113,15 @@
93113 if(existingPath == null) {
94114 existingPath = "";
95115 }
96- envMap.put("PATH", ccmPath + ":" + existingPath);
116+ envMap.put("PATH", ccmPath + File.pathSeparator + existingPath);
117+ }
118+
119+ if (isWindows()) {
120+ CCM_COMMAND = "cmd /c ccm.py";
121+ } else {
122+ CCM_COMMAND = "ccm";
97123 }
124+
98125 // If ccm.java.home is set, override the JAVA_HOME variable with it.
99126 String ccmJavaHome = System.getProperty("ccm.java.home");
100127 if(ccmJavaHome != null) {
@@ -103,27 +130,16 @@
103130 ENVIRONMENT_MAP = ImmutableMap.copyOf(envMap);
104131 }
105132
106- static final File CASSANDRA_DIR;
107- static final String CASSANDRA_VERSION;
108-
109- static {
110- String version = System.getProperty("cassandra.version");
111- if (version.matches(CASSANDRA_VERSION_REGEXP)) {
112- CASSANDRA_DIR = null;
113- CASSANDRA_VERSION = "-v " + version;
114- } else {
115- CASSANDRA_DIR = new File(version);
116- CASSANDRA_VERSION = "";
117- }
133+ /**
134+ * Checks if the operating system is a Windows one
135+ * @return <code>true</code> if the operating system is a Windows one, <code>false</code> otherwise.
136+ */
137+ private static boolean isWindows() {
118138
119- String ip_prefix = System.getProperty("ipprefix");
120- if (ip_prefix == null || ip_prefix.isEmpty()) {
121- ip_prefix = "127.0.1.";
122- }
123- IP_PREFIX = ip_prefix;
139+ String osName = System.getProperty("os.name");
140+ return osName != null && osName.startsWith("Windows");
124141 }
125142
126- private final Runtime runtime = Runtime.getRuntime();
127143 private final File ccmDir;
128144
129145 private CCMBridge() {
@@ -165,38 +181,8 @@
165181 return f;
166182 }
167183
168- /** Note that this method does not start CCM */
169- public static CCMBridge create(String name, String... options) {
170- // This leads to a confusing CCM error message so check explicitly:
171- checkArgument(!"current".equals(name.toLowerCase()),
172- "cluster can't be called \"current\"");
173- CCMBridge bridge = new CCMBridge();
174- bridge.execute("ccm create %s -b -i %s %s " + Joiner.on(" ").join(options), name, IP_PREFIX, CASSANDRA_VERSION);
175- return bridge;
176- }
177-
178- public static CCMBridge create(String name, int nbNodes, String... options) {
179- checkArgument(!"current".equals(name.toLowerCase()),
180- "cluster can't be called \"current\"");
181- CCMBridge bridge = new CCMBridge();
182- bridge.execute("ccm create %s -n %d -s -i %s -b %s " + Joiner.on(" ").join(options), name, nbNodes, IP_PREFIX, CASSANDRA_VERSION);
183- return bridge;
184- }
185-
186- public static CCMBridge createWithCustomVersion(String name, int nbNodes, String cassandraVersion) {
187- checkArgument(!"current".equals(name.toLowerCase()),
188- "cluster can't be called \"current\"");
189- CCMBridge bridge = new CCMBridge();
190- bridge.execute("ccm create %s -n %d -s -i %s -b -v %s ", name, nbNodes, IP_PREFIX, cassandraVersion);
191- return bridge;
192- }
193-
194- public static CCMBridge create(String name, int nbNodesDC1, int nbNodesDC2) {
195- checkArgument(!"current".equals(name.toLowerCase()),
196- "cluster can't be called \"current\"");
197- CCMBridge bridge = new CCMBridge();
198- bridge.execute("ccm create %s -n %d:%d -s -i %s -b %s", name, nbNodesDC1, nbNodesDC2, IP_PREFIX, CASSANDRA_VERSION);
199- return bridge;
184+ public static Builder builder(String clusterName) {
185+ return new Builder(clusterName);
200186 }
201187
202188 public static CCMBridge.CCMCluster buildCluster(int nbNodes, Cluster.Builder builder) {
@@ -208,55 +194,55 @@
208194 }
209195
210196 public void start() {
211- execute("ccm start --wait-other-notice --wait-for-binary-proto");
197+ execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto");
212198 }
213199
214200 public void stop() {
215- execute("ccm stop");
201+ execute(CCM_COMMAND + " stop");
216202 }
217203
218204 public void forceStop() {
219- execute("ccm stop --not-gently");
205+ execute(CCM_COMMAND + " stop --not-gently");
220206 }
221207
222208 public void start(int n) {
223209 logger.info("Starting: " + IP_PREFIX + n);
224- execute("ccm node%d start --wait-other-notice --wait-for-binary-proto", n);
210+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
225211 }
226212
227- public void start(int n, String option) {
228- logger.info("Starting: " + IP_PREFIX + n + " with " + option);
229- execute("ccm node%d start --wait-other-notice --wait-for-binary-proto --jvm_arg=%s", n, option);
213+ public void start(int n, String jvmArg) {
214+ logger.info("Starting: " + IP_PREFIX + n + " with " + jvmArg);
215+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto --jvm_arg=%s", n, jvmArg);
230216 }
231217
232218 public void stop(int n) {
233219 logger.info("Stopping: " + IP_PREFIX + n);
234- execute("ccm node%d stop", n);
220+ execute(CCM_COMMAND + " node%d stop", n);
235221 }
236222
237223 public void stop(String clusterName) {
238- logger.info("Stopping Cluster : "+clusterName);
239- execute("ccm stop "+clusterName);
224+ logger.info("Stopping Cluster : " + clusterName);
225+ execute(CCM_COMMAND + " stop "+clusterName);
240226 }
241227
242228 public void forceStop(int n) {
243229 logger.info("Force stopping: " + IP_PREFIX + n);
244- execute("ccm node%d stop --not-gently", n);
230+ execute(CCM_COMMAND + " node%d stop --not-gently", n);
245231 }
246232
247233 public void remove() {
248234 stop();
249- execute("ccm remove");
235+ execute(CCM_COMMAND + " remove");
250236 }
251237
252238 public void remove(String clusterName) {
253239 stop(clusterName);
254- execute("ccm remove " + clusterName);
240+ execute(CCM_COMMAND + " remove " + clusterName);
255241 }
256242
257243 public void remove(int n) {
258244 logger.info("Removing: " + IP_PREFIX + n);
259- execute("ccm node%d remove", n);
245+ execute(CCM_COMMAND + " node%d remove", n);
260246 }
261247
262248 public void bootstrapNode(int n) {
@@ -265,14 +251,10 @@
265251
266252 public void bootstrapNode(int n, String dc) {
267253 if (dc == null)
268- execute("ccm add node%d -i %s%d -j %d -r %d -b -s", n, IP_PREFIX, n, 7000 + 100 * n, 8000 + 100 * n);
254+ execute(CCM_COMMAND + " add node%d -i %s%d -j %d -r %d -b -s", n, IP_PREFIX, n, 7000 + 100 * n, 8000 + 100 * n);
269255 else
270- execute("ccm add node%d -i %s%d -j %d -b -d %s -s", n, IP_PREFIX, n, 7000 + 100 * n, dc);
271- execute("ccm node%d start --wait-other-notice --wait-for-binary-proto", n);
272- }
273-
274- public void bootstrapNodeWithPorts(int n, int thriftPort, int storagePort, int binaryPort, int jmxPort, int remoteDebugPort) {
275- bootstrapNodeWithPorts(n, thriftPort, storagePort, binaryPort, jmxPort, remoteDebugPort, null);
256+ execute(CCM_COMMAND + " add node%d -i %s%d -j %d -b -d %s -s", n, IP_PREFIX, n, 7000 + 100 * n, dc);
257+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
276258 }
277259
278260 public void bootstrapNodeWithPorts(int n, int thriftPort, int storagePort, int binaryPort, int jmxPort, int remoteDebugPort, String option) {
@@ -280,18 +262,14 @@
280262 String storageItf = IP_PREFIX + n + ":" + storagePort;
281263 String binaryItf = IP_PREFIX + n + ":" + binaryPort;
282264 String remoteLogItf = IP_PREFIX + n + ":" + remoteDebugPort;
283- execute("ccm add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s",
265+ execute(CCM_COMMAND + " add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s",
284266 n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf);
285267 if(option == null) start(n);
286268 else start(n, option);
287269 }
288270
289271 public void decommissionNode(int n) {
290- execute("ccm node%d decommission", n);
291- }
292-
293- public void updateConfig(String name, String value) {
294- updateConfig(ImmutableMap.of(name, value));
272+ execute(CCM_COMMAND + " node%d decommission", n);
295273 }
296274
297275 public void updateConfig(Map<String, String> configs) {
@@ -299,19 +277,17 @@
299277 for (Map.Entry<String, String> entry : configs.entrySet()) {
300278 confStr.append(entry.getKey() + ":" + entry.getValue() + " ");
301279 }
302- execute("ccm updateconf " + confStr);
303- }
304-
305- public void populate(int n) {
306- execute("ccm populate -n %d -i %s", n, IP_PREFIX);
280+ execute(CCM_COMMAND + " updateconf " + confStr);
307281 }
308282
309283 private void execute(String command, Object... args) {
284+
285+ String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
310286 try {
311- String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
312287 logger.debug("Executing: " + fullCommand);
313288 CommandLine cli = CommandLine.parse(fullCommand);
314289 Executor executor = new DefaultExecutor();
290+ executor.setWorkingDirectory(CASSANDRA_DIR);
315291
316292 LogOutputStream outStream = new LogOutputStream() {
317293 @Override protected void processLine(String line, int logLevel) {
@@ -333,7 +309,7 @@
333309 throw new RuntimeException();
334310 }
335311 } catch (IOException e) {
336- throw new RuntimeException(e);
312+ throw new RuntimeException(String.format("The command %s failed to execute", fullCommand), e);
337313 }
338314 }
339315
@@ -361,33 +337,6 @@
361337 }
362338 }
363339
364- /**
365- * Enables SSL without client authentication. Does not apply to already started nodes.
366- */
367- public void enableSSL() {
368- enableSSL(false);
369- }
370-
371- /**
372- * Enables SSL. Does not apply to already started nodes.
373- * @param requireClientAuth Whether or not to require Clients used authentication.
374- */
375- public void enableSSL(boolean requireClientAuth) {
376- ImmutableMap.Builder<String, String> configs = ImmutableMap.builder();
377-
378- configs.put("client_encryption_options.enabled", "true");
379- configs.put("client_encryption_options.keystore", DEFAULT_SERVER_KEYSTORE_FILE.getAbsolutePath());
380- configs.put("client_encryption_options.keystore_password", DEFAULT_SERVER_KEYSTORE_PASSWORD);
381-
382- if (requireClientAuth) {
383- configs.put("client_encryption_options.require_client_auth", "true");
384- configs.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath());
385- configs.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD);
386- }
387-
388- updateConfig(configs.build());
389- }
390-
391340 private static void busyWaitForPort(InetAddress address, int port, boolean expectedConnectionState) {
392341 long maxAcceptableWaitTime = TimeUnit.SECONDS.toMillis(10);
393342 long waitQuantum = TimeUnit.MILLISECONDS.toMillis(500);
@@ -453,16 +402,6 @@
453402 // One cluster for the whole test class
454403 public static abstract class PerClassSingleNodeCluster {
455404
456- /**
457- * The JVM args to use when starting nodes.
458- * Unfortunately, this must be set for all tests because
459- * CCM cluster instances are reused between tests,
460- * so a specific test cannot ask for specific JVM options.
461- */
462- private static final String JVM_ARGS =
463- // custom query handler to test protocol v4 custom payloads
464- "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler";
465-
466405 protected static CCMBridge ccmBridge;
467406 private static boolean erroredOut;
468407 private static boolean clusterInitialized=false;
@@ -474,6 +413,8 @@
474413
475414 protected static Cluster cluster;
476415 protected static Session session;
416+
417+ protected final VersionNumber cassandraVersion = VersionNumber.parse(System.getProperty("cassandra.version"));
477418
478419 protected abstract Collection<String> getTableDefinitions();
479420
@@ -494,24 +435,35 @@
494435
495436 @AfterClass(groups = { "short", "long" })
496437 public void afterClass() {
497- clearSimpleKeyspace();
438+ try {
439+ clearSimpleKeyspace();
440+ } finally {
441+ if(cluster != null) {
442+ cluster.close();
443+ }
444+ }
498445 }
499446
500447 private void maybeInitCluster(){
501448 if (!clusterInitialized){
502449 try {
503- //launch ccm cluster
504- ccmBridge = CCMBridge.create("test-class");
505- // Only enable user defined functions if protocol version is >= 4.
506- if(TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V4) >= 0)
507- ccmBridge.updateConfig("enable_user_defined_functions", "true");
450+ ProtocolVersion protocolVersion = TestUtils.getDesiredProtocolVersion();
451+
452+ ccmBridge = CCMBridge.builder("test-class")
453+ .withoutNodes()
454+ .notStarted()
455+ .withCassandraConfiguration("enable_user_defined_functions",
456+ // Only enable user defined functions if protocol version is >= 4.
457+ Boolean.toString(protocolVersion.compareTo(ProtocolVersion.V4) >= 0))
458+ .build();
508459
509460 ports = new int[5];
510461 for (int i = 0; i < 5; i++) {
511462 ports[i] = TestUtils.findAvailablePort(11000 + i);
512463 }
513464
514- ccmBridge.bootstrapNodeWithPorts(1, ports[0], ports[1], ports[2], ports[3], ports[4], JVM_ARGS);
465+ ccmBridge.bootstrapNodeWithPorts(1, ports[0], ports[1], ports[2], ports[3], ports[4],
466+ "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler");
515467 ksNumber = new AtomicLong(0);
516468 erroredOut = false;
517469 hostAddress = new InetSocketAddress(InetAddress.getByName(IP_PREFIX + 1), ports[2]);
@@ -530,7 +482,7 @@
530482
531483 private void initKeyspace() {
532484 try {
533- Builder builder = Cluster.builder();
485+ Cluster.Builder builder = Cluster.builder();
534486
535487 builder = configure(builder);
536488
@@ -561,9 +513,17 @@
561513 }
562514
563515 private void clearSimpleKeyspace() {
564- session.execute("DROP KEYSPACE " + keyspace);
565- if (cluster != null) {
566- cluster.close();
516+ if(keyspace != null) {
517+ // Temporarily extend read timeout to 1 minute to accommodate keyspaces with many tables.
518+ // This should be more than enough although some tests create many tables, so dropping a keyspace
519+ // could take as long as 12 seconds on restricted hardware.
520+ int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis();
521+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000);
522+ try {
523+ session.execute("DROP KEYSPACE " + keyspace);
524+ } finally {
525+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout);
526+ }
567527 }
568528 }
569529
@@ -582,14 +542,16 @@
582542 if (nbNodes == 0)
583543 throw new IllegalArgumentException();
584544
585- return new CCMCluster(CCMBridge.create("test", nbNodes), builder, nbNodes);
545+ CCMBridge ccm = CCMBridge.builder("test").withNodes(nbNodes).build();
546+ return new CCMCluster(ccm, builder, nbNodes);
586547 }
587548
588549 public static CCMCluster create(int nbNodesDC1, int nbNodesDC2, Cluster.Builder builder) {
589550 if (nbNodesDC1 == 0)
590551 throw new IllegalArgumentException();
591552
592- return new CCMCluster(CCMBridge.create("test", nbNodesDC1, nbNodesDC2), builder, nbNodesDC1 + nbNodesDC2);
553+ CCMBridge ccm = CCMBridge.builder("test").withNodes(nbNodesDC1, nbNodesDC2).build();
554+ return new CCMCluster(ccm, builder, nbNodesDC1 + nbNodesDC2);
593555 }
594556
595557 public static CCMCluster create(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) {
@@ -605,7 +567,8 @@
605567
606568 try {
607569 Thread.sleep(1000);
608- } catch (Exception e) {
570+ } catch (InterruptedException e) {
571+ fail("Unexpected interruption");
609572 }
610573 this.cluster = builder.addContactPoints(contactPoints).build();
611574 this.session = cluster.connect();
@@ -636,4 +599,87 @@
636599 }
637600 }
638601 }
602+
603+ /** use {@link #builder(String)} to get an instance */
604+ public static class Builder {
605+ private final String clusterName;
606+ private Integer[] nodes = { 1 };
607+ private boolean start = true;
608+ private String cassandraVersion = CASSANDRA_VERSION;
609+ private String[] startOptions = new String[0];
610+ private Map<String, String> cassandraConfiguration = Maps.newHashMap();
611+
612+
613+ Builder(String clusterName) {
614+ this.clusterName = clusterName;
615+ }
616+
617+ /** Number of nodes for each DC. Defaults to [1] (1 DC with 1 node) */
618+ public Builder withNodes(Integer... nodes) {
619+ this.nodes = nodes;
620+ return this;
621+ }
622+
623+ public Builder withoutNodes() {
624+ return withNodes();
625+ }
626+
627+ public Builder withSSL(boolean requireClientAuth) {
628+ cassandraConfiguration.put("client_encryption_options.enabled", "true");
629+ cassandraConfiguration.put("client_encryption_options.keystore", DEFAULT_SERVER_KEYSTORE_FILE.getAbsolutePath());
630+ cassandraConfiguration.put("client_encryption_options.keystore_password", DEFAULT_SERVER_KEYSTORE_PASSWORD);
631+
632+ if (requireClientAuth) {
633+ cassandraConfiguration.put("client_encryption_options.require_client_auth", "true");
634+ cassandraConfiguration.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath());
635+ cassandraConfiguration.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD);
636+ }
637+ return this;
638+ }
639+
640+ /** Whether to start the cluster immediately (defaults to true if this is never called) */
641+ public Builder notStarted() {
642+ this.start = false;
643+ return this;
644+ }
645+
646+ /** Defaults to system property cassandra.version */
647+ public Builder withCassandraVersion(String cassandraVersion) {
648+ this.cassandraVersion = "-v " + cassandraVersion;
649+ return this;
650+ }
651+
652+ /** Free-form options that will be added at the end of the start command */
653+ public Builder withStartOptions(String... options) {
654+ this.startOptions = options;
655+ return this;
656+ }
657+
658+ /** Customizes entries in cassandra.yaml (can be called multiple times) */
659+ public Builder withCassandraConfiguration(String key, String value) {
660+ this.cassandraConfiguration.put(key, value);
661+ return this;
662+ }
663+
664+ public CCMBridge build() {
665+ CCMBridge ccm = new CCMBridge();
666+ ccm.execute(buildCreateCommand());
667+ ccm.updateConfig(cassandraConfiguration);
668+ if (start)
669+ ccm.start();
670+ return ccm;
671+ }
672+
673+ private String buildCreateCommand() {
674+ StringBuilder result = new StringBuilder(CCM_COMMAND + " create");
675+ result.append(" " + clusterName);
676+ result.append(" -i" + IP_PREFIX);
677+ result.append(" " + cassandraVersion);
678+ if (nodes.length > 0)
679+ result.append(" -n " + Joiner.on(":").join(nodes));
680+ if (startOptions.length > 0)
681+ result.append(" " + Joiner.on(" ").join(startOptions));
682+ return result.toString();
683+ }
684+ }
639685 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +16 −13
@@ -15,15 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.datastax.driver.core.exceptions.NoHostAvailableException;
19-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
20-import com.datastax.driver.core.querybuilder.Insert;
21-import com.datastax.driver.core.utils.UUIDs;
22-import com.google.common.collect.Lists;
23-import org.slf4j.Logger;
24-import org.slf4j.LoggerFactory;
25-import org.testng.annotations.Test;
26-
2718 import java.net.InetAddress;
2819 import java.net.InetSocketAddress;
2920 import java.util.Collections;
@@ -31,10 +22,23 @@
3122 import java.util.concurrent.TimeUnit;
3223 import java.util.concurrent.TimeoutException;
3324
25+import com.google.common.collect.Lists;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+import org.testng.annotations.Test;
29+
30+import static org.assertj.core.api.Assertions.fail;
31+import static org.mockito.Mockito.spy;
32+import static org.mockito.Mockito.times;
33+import static org.mockito.Mockito.verify;
34+
35+import com.datastax.driver.core.exceptions.NoHostAvailableException;
36+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
37+import com.datastax.driver.core.querybuilder.Insert;
38+import com.datastax.driver.core.utils.UUIDs;
39+
3440 import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS;
3541 import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
36-import static org.assertj.core.api.Assertions.fail;
37-import static org.mockito.Mockito.*;
3842
3943 public class ClusterInitTest {
4044 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -52,8 +56,7 @@
5256 try {
5357 // Obtaining connect timeouts is not trivial: we create a 6-host cluster but only start one of them,
5458 // then simulate the other 5.
55- ccm = CCMBridge.create("test");
56- ccm.populate(6);
59+ ccm = CCMBridge.builder("test").withNodes(6).notStarted().build();
5760 ccm.start(1);
5861
5962 for (int i = 0; i < 5; i++) {
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +3 −3
@@ -43,7 +43,7 @@
4343 ReconnectionPolicy reconnectionPolicy = new ConstantReconnectionPolicy(60 * 1000);
4444
4545 try {
46- ccm = CCMBridge.create("test", 2);
46+ ccm = CCMBridge.builder("test").withNodes(2).build();
4747 // We pass only the first host as contact point, so we know the control connection will be on this host
4848 cluster = Cluster.builder()
4949 .addContactPoint(CCMBridge.ipOfNode(1))
@@ -82,7 +82,7 @@
8282 Cluster cluster = null;
8383
8484 try {
85- ccm = CCMBridge.create("test", 1);
85+ ccm = CCMBridge.builder("test").build();
8686
8787 // First driver instance: create UDT
8888 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
@@ -119,7 +119,7 @@
119119 Cluster cluster = null;
120120
121121 try {
122- ccm = CCMBridge.create("test", 3);
122+ ccm = CCMBridge.builder("test").withNodes(3).build();
123123
124124 cluster = Cluster.builder()
125125 .addContactPoint(CCMBridge.ipOfNode(1))
deleted driver-core/src/test/java/com/datastax/driver/core/DynamicConnectionPoolTest.java +0 −431
@@ -1,431 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.util.Collection;
19-import java.util.List;
20-import java.util.concurrent.*;
21-import java.util.concurrent.atomic.AtomicBoolean;
22-
23-import static java.util.concurrent.TimeUnit.MILLISECONDS;
24-import static java.util.concurrent.TimeUnit.SECONDS;
25-
26-import com.codahale.metrics.Gauge;
27-import com.google.common.collect.Lists;
28-import org.testng.annotations.Test;
29-
30-import static org.assertj.core.api.Assertions.assertThat;
31-import static org.mockito.Mockito.doReturn;
32-import static org.mockito.Mockito.spy;
33-import static org.testng.Assert.fail;
34-
35-public class DynamicConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
36- @Override
37- protected Collection<String> getTableDefinitions() {
38- StringBuilder sb = new StringBuilder("CREATE TABLE Java349 (mykey INT primary key");
39- for (int i = 0; i < 1000; i++) {
40- sb.append(", column").append(i).append(" INT");
41- }
42- sb.append(")");
43- return Lists.newArrayList(sb.toString());
44- }
45-
46- @Override
47- protected Cluster.Builder configure(Cluster.Builder builder) {
48- // Use version 2 at highest.
49- ProtocolVersion versionToUse = TestUtils.getDesiredProtocolVersion(ProtocolVersion.V2);
50- return builder.withProtocolVersion(versionToUse);
51- }
52-
53- /**
54- * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
55- * of creating a new connection.
56- *
57- * @since 2.0.10, 2.1.6
58- * @jira_ticket JAVA-419
59- * @test_category connection:connection_pool
60- */
61- @Test(groups = "short")
62- public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException {
63- DynamicConnectionPool pool = createPool(2, 2);
64-
65- assertThat(pool.connections.size()).isEqualTo(2);
66- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
67-
68- for (int i = 0; i < 256; i++) {
69- Connection connection = pool.borrowConnection(100, MILLISECONDS);
70- assertThat(coreConnections).contains(connection);
71- }
72-
73- boolean timedOut = false;
74- try {
75- pool.borrowConnection(100, MILLISECONDS);
76- } catch (TimeoutException e) {
77- timedOut = true;
78- }
79- assertThat(timedOut).isTrue();
80- }
81-
82- /**
83- * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
84- * timeout instead of creating a new connection.
85- *
86- * @since 2.0.10, 2.1.6
87- * @jira_ticket JAVA-419
88- * @test_category connection:connection_pool
89- */
90- @Test(groups = "short")
91- public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws ConnectionException, TimeoutException {
92- DynamicConnectionPool pool = createPool(1, 2);
93-
94- assertThat(pool.connections.size()).isEqualTo(1);
95- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
96-
97- //
98- for (int i = 0; i < 128; i++) {
99- Connection connection = pool.borrowConnection(100, MILLISECONDS);
100- assertThat(coreConnections).contains(connection);
101- }
102-
103- // Borrow more and ensure the connection returned is a non-core connection.
104- for (int i = 0; i < 128; i++) {
105- Connection connection = pool.borrowConnection(100, MILLISECONDS);
106- assertThat(coreConnections).doesNotContain(connection);
107- }
108-
109- boolean timedOut = false;
110- try {
111- pool.borrowConnection(100, MILLISECONDS);
112- } catch (TimeoutException e) {
113- timedOut = true;
114- }
115- assertThat(timedOut).isTrue();
116- }
117-
118- /**
119- * Ensures that if the core connection pool is full that borrowConnection will create and use a new connection.
120- *
121- * @since 2.0.10, 2.1.6
122- * @jira_ticket JAVA-419
123- * @test_category connection:connection_pool
124- */
125- @Test(groups = "short")
126- public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException {
127- cluster.getConfiguration().getPoolingOptions()
128- .setIdleTimeoutSeconds(20);
129-
130- DynamicConnectionPool pool = createPool(1, 2);
131- Connection core = pool.connections.get(0);
132-
133- // Fill core connection
134- for (int i = 0; i < 128; i++)
135- assertThat(
136- pool.borrowConnection(100, MILLISECONDS)
137- ).isEqualTo(core);
138-
139- // Reaching 128 on the core connection should have triggered the creation of an extra one
140- TimeUnit.MILLISECONDS.sleep(100);
141- assertThat(pool.connections).hasSize(2);
142- }
143-
144- /**
145- * Ensures that a trashed connection that has not been timed out should be resurrected into the connection pool if
146- * borrowConnection is called and a new connection is needed.
147- *
148- * @since 2.0.10, 2.1.6
149- * @jira_ticket JAVA-419
150- * @test_category connection:connection_pool
151- */
152- @Test(groups = "long")
153- public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
154- cluster.getConfiguration().getPoolingOptions()
155- .setIdleTimeoutSeconds(20);
156-
157- DynamicConnectionPool pool = createPool(1, 2);
158- Connection connection1 = pool.connections.get(0);
159-
160- for (int i = 0; i < 101; i++)
161- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
162-
163- TimeUnit.MILLISECONDS.sleep(100);
164- assertThat(pool.connections).hasSize(2);
165- Connection connection2 = pool.connections.get(1);
166-
167- assertThat(connection1.inFlight.get()).isEqualTo(101);
168- assertThat(connection2.inFlight.get()).isEqualTo(0);
169-
170- // Go back under the capacity of 1 connection
171- for (int i = 0; i < 51; i++)
172- pool.returnConnection(connection1);
173-
174- assertThat(connection1.inFlight.get()).isEqualTo(50);
175- assertThat(connection2.inFlight.get()).isEqualTo(0);
176-
177- // Given enough time, one connection gets trashed (and the implementation picks the first one)
178- TimeUnit.SECONDS.sleep(20);
179- assertThat(pool.connections).containsExactly(connection2);
180- assertThat(pool.trash).containsExactly(connection1);
181-
182- // Now borrow enough to go just under the 1 connection threshold
183- for (int i = 0; i < 50; i++)
184- pool.borrowConnection(100, MILLISECONDS);
185-
186- assertThat(pool.connections).containsExactly(connection2);
187- assertThat(pool.trash).containsExactly(connection1);
188- assertThat(connection1.inFlight.get()).isEqualTo(50);
189- assertThat(connection2.inFlight.get()).isEqualTo(50);
190-
191- // Borrowing one more time should resurrect the trashed connection
192- pool.borrowConnection(100, MILLISECONDS);
193- TimeUnit.MILLISECONDS.sleep(100);
194-
195- assertThat(pool.connections).containsExactly(connection2, connection1);
196- assertThat(pool.trash).isEmpty();
197- assertThat(connection1.inFlight.get()).isEqualTo(50);
198- assertThat(connection2.inFlight.get()).isEqualTo(51);
199- }
200-
201- /**
202- * Ensures that a trashed connection that has been timed out should not be resurrected into the connection pool if
203- * borrowConnection is called and a new connection is needed.
204- *
205- * @since 2.0.10, 2.1.6
206- * @jira_ticket JAVA-419
207- * @test_category connection:connection_pool
208- */
209- @Test(groups = "long")
210- public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
211- cluster.getConfiguration().getPoolingOptions()
212- .setIdleTimeoutSeconds(20);
213-
214- DynamicConnectionPool pool = createPool(1, 2);
215- Connection connection1 = pool.connections.get(0);
216-
217- for (int i = 0; i < 101; i++)
218- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
219-
220- TimeUnit.MILLISECONDS.sleep(100);
221- assertThat(pool.connections).hasSize(2);
222- Connection connection2 = pool.connections.get(1);
223-
224- assertThat(connection1.inFlight.get()).isEqualTo(101);
225- assertThat(connection2.inFlight.get()).isEqualTo(0);
226-
227- // Go back under the capacity of 1 connection
228- for (int i = 0; i < 51; i++)
229- pool.returnConnection(connection1);
230-
231- assertThat(connection1.inFlight.get()).isEqualTo(50);
232- assertThat(connection2.inFlight.get()).isEqualTo(0);
233-
234- // Given enough time, one connection gets trashed (and the implementation picks the first one)
235- TimeUnit.SECONDS.sleep(20);
236- assertThat(pool.connections).containsExactly(connection2);
237- assertThat(pool.trash).containsExactly(connection1);
238-
239- // Return trashed connection down to 0 inFlight
240- for (int i = 0; i < 50; i++)
241- pool.returnConnection(connection1);
242- assertThat(connection1.inFlight.get()).isEqualTo(0);
243-
244- // Give enough time for trashed connection to be cleaned up from the trash:
245- TimeUnit.SECONDS.sleep(30);
246- assertThat(pool.connections).containsExactly(connection2);
247- assertThat(pool.trash).isEmpty();
248- assertThat(connection1.isClosed()).isTrue();
249-
250- // Fill the live connection to go over the threshold where a second one is needed
251- for (int i = 0; i < 101; i++)
252- assertThat(pool.borrowConnection(100, TimeUnit.MILLISECONDS)).isEqualTo(connection2);
253- assertThat(connection2.inFlight.get()).isEqualTo(101);
254- TimeUnit.MILLISECONDS.sleep(100);
255-
256- // Borrow again to get the new connection
257- Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
258- assertThat(connection3)
259- .isNotEqualTo(connection2) // should not be the full connection
260- .isNotEqualTo(connection1); // should not be the previously trashed one
261- }
262-
263- /**
264- * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
265- *
266- * @since 2.0.10, 2.1.6
267- * @jira_ticket JAVA-419
268- * @test_category connection:connection_pool
269- */
270- @Test(groups = "long")
271- public void should_not_close_trashed_connection_until_no_in_flight()
272- throws ConnectionException, TimeoutException, InterruptedException {
273- cluster.getConfiguration().getPoolingOptions()
274- .setIdleTimeoutSeconds(20);
275-
276- DynamicConnectionPool pool = createPool(1, 2);
277- Connection connection1 = pool.connections.get(0);
278-
279- // Fill core connection enough to trigger creation of another one
280- for (int i = 0; i < 110; i++)
281- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
282-
283- TimeUnit.MILLISECONDS.sleep(100);
284- assertThat(pool.connections).hasSize(2);
285-
286- // Return enough times to get back under the threshold where one connection is enough
287- for (int i = 0; i < 50; i++)
288- pool.returnConnection(connection1);
289-
290- // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
291- // It still has in-flight requests so should not get closed.
292- TimeUnit.SECONDS.sleep(30);
293- assertThat(pool.trash).containsExactly(connection1);
294- assertThat(connection1.inFlight.get()).isEqualTo(60);
295- assertThat(connection1.isClosed()).isFalse();
296-
297- // Consume all inFlight requests on the trashed connection.
298- while (connection1.inFlight.get() > 0) {
299- pool.returnConnection(connection1);
300- }
301-
302- // Sleep enough time for the connection to be consider idled and closed.
303- TimeUnit.SECONDS.sleep(30);
304-
305- // The connection should be now closed.
306- // The trashed connection should be closed and not in the pool or trash.
307- assertThat(connection1.isClosed()).isTrue();
308- assertThat(pool.connections).doesNotContain(connection1);
309- assertThat(pool.trash).doesNotContain(connection1);
310- }
311-
312- /**
313- * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
314- * the connection is put in the trash.
315- *
316- * @since 2.0.10, 2.1.6
317- * @jira_ticket JAVA-419
318- * @test_category connection:connection_pool
319- */
320- @Test(groups = "short")
321- public void should_trash_on_returning_connection_with_insufficient_streams()
322- throws ConnectionException, TimeoutException, InterruptedException {
323- DynamicConnectionPool pool = createPool(1, 2);
324- Connection core = pool.connections.get(0);
325-
326- for (int i = 0; i < 128; i++)
327- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
328-
329- TimeUnit.MILLISECONDS.sleep(100);
330- assertThat(pool.connections).hasSize(2);
331-
332- // Grab the new non-core connection and replace it with a spy.
333- Connection extra1 = spy(pool.connections.get(1));
334- pool.connections.set(1, extra1);
335-
336- // Borrow 10 times to ensure pool is utilized.
337- for (int i = 0; i < 10; i++) {
338- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1);
339- }
340-
341- // Return connection, it should not be trashed since it still has 9 inflight requests.
342- pool.returnConnection(extra1);
343- assertThat(pool.connections).hasSize(2);
344-
345- // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
346- // this should cause the connection to be replaced and trashed on returnConnection.
347- doReturn(0).when(extra1).maxAvailableStreams();
348-
349- // On returning of the connection, should detect that there are no available streams and trash it.
350- pool.returnConnection(extra1);
351- assertThat(pool.connections).hasSize(1);
352- }
353-
354- private DynamicConnectionPool createPool(int coreConnections, int maxConnections) {
355- cluster.getConfiguration().getPoolingOptions()
356- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
357- .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
358- Session session = cluster.connect();
359- Host host = TestUtils.findHost(cluster, 1);
360- return (DynamicConnectionPool)((SessionManager)session).pools.get(host);
361- }
362-
363- /**
364- * <p>
365- * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
366- * insertions are being executed, the number of opened connection is monitored.
367- * <p/>
368- * If at anytime, the number of opened connections is negative, this test will fail.
369- *
370- * @since 2.0.6, 2.1.1
371- * @jira_ticket JAVA-349
372- * @test_category connection:connection_pool
373- */
374- @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */)
375- public void open_connections_metric_should_always_be_positive() throws InterruptedException {
376- // Track progress in a dedicated thread
377- int numberOfInserts = 100 * 1000;
378- final CountDownLatch pendingInserts = new CountDownLatch(numberOfInserts);
379- ExecutorService progressReportExecutor = Executors.newSingleThreadExecutor();
380- final Runnable progressReporter = new Runnable() {
381- @Override
382- public void run() {
383- pendingInserts.countDown();
384- }
385- };
386-
387- // Track opened connections in a dedicated thread every one second
388- final AtomicBoolean negativeOpenConnectionCountSpotted = new AtomicBoolean(false);
389- final Gauge<Integer> openConnections = cluster.getMetrics().getOpenConnections();
390- ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1);
391- final Runnable openConnectionsWatcher = new Runnable() {
392- @Override
393- public void run() {
394- Integer value = openConnections.getValue();
395- if (value < 0) {
396- System.err.println("Negative value spotted for openConnection metric: " + value);
397- negativeOpenConnectionCountSpotted.set(true);
398- }
399- }
400- };
401- openConnectionsWatcherExecutor.scheduleAtFixedRate(openConnectionsWatcher, 1, 1, SECONDS);
402-
403- // Insert 100k lines in a newly created 1k columns table
404- PreparedStatement insertStatement = session.prepare(generateJava349InsertStatement());
405- for (int key = 0; key < numberOfInserts; key++) {
406- session.executeAsync(insertStatement.bind(key)).addListener(progressReporter, progressReportExecutor);
407- }
408-
409- // Wait for all inserts to happen and stop connections and progress tracking
410- pendingInserts.await();
411- openConnectionsWatcherExecutor.shutdownNow();
412- progressReportExecutor.shutdownNow();
413-
414- if (negativeOpenConnectionCountSpotted.get()) {
415- fail("Negative value spotted for open connection count");
416- }
417- }
418-
419- private String generateJava349InsertStatement() {
420- StringBuilder sb = new StringBuilder("INSERT INTO Java349 (mykey");
421- for (int i = 0; i < 1000; i++) {
422- sb.append(", column").append(i);
423- }
424- sb.append(") VALUES (?");
425- for (int i = 0; i < 1000; i++) {
426- sb.append(", ").append(i);
427- }
428- sb.append(");");
429- return sb.toString();
430- }
431-}
modified driver-core/src/test/java/com/datastax/driver/core/ExceptionsTest.java +22 −27
@@ -15,16 +15,17 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.Locale;
19+
1820 import com.datastax.driver.core.exceptions.*;
1921 import com.datastax.driver.core.policies.Policies;
2022 import com.datastax.driver.core.policies.WhiteListPolicy;
2123 import com.datastax.driver.core.utils.CassandraVersion;
22-import com.google.common.collect.ImmutableMap;
24+
2325 import com.google.common.collect.Lists;
2426 import org.testng.annotations.Test;
2527
2628 import java.net.InetSocketAddress;
27-import java.util.List;
2829
2930 import static com.datastax.driver.core.TestUtils.waitForDownWithWait;
3031 import static org.assertj.core.api.Assertions.assertThat;
@@ -52,7 +53,7 @@
5253 String[] cqlCommands = new String[]{
5354 String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1),
5455 "USE " + keyspace,
55- String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table)
56+ String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)
5657 };
5758
5859 // Create the schema once
@@ -199,9 +200,9 @@
199200
200201 c.session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, replicationFactor));
201202 c.session.execute("USE " + keyspace);
202- c.session.execute(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table));
203+ c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table));
203204
204- c.session.execute(new SimpleStatement(String.format(TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
205+ c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
205206 c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
206207
207208 c.cassandraCluster.forceStop(2);
@@ -315,9 +316,9 @@
315316
316317 c.session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, replicationFactor));
317318 c.session.execute("USE " + keyspace);
318- c.session.execute(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table));
319+ c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table));
319320
320- c.session.execute(new SimpleStatement(String.format(TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
321+ c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
321322 c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
322323
323324 c.cassandraCluster.stop(2);
@@ -335,7 +336,7 @@
335336 }
336337
337338 try{
338- c.session.execute(new SimpleStatement(String.format(TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
339+ c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
339340 } catch (UnavailableException e) {
340341 String expectedError = String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", "ALL", 3, 2);
341342 assertEquals(e.getMessage(), expectedError);
@@ -368,14 +369,14 @@
368369
369370 c.session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, replicationFactor));
370371 c.session.execute("USE " + keyspace);
371- c.session.execute(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table));
372+ c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table));
372373
373- c.session.execute(new SimpleStatement(String.format(TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
374+ c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
374375 c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
375376
376377 c.cassandraCluster.forceStop(2);
377378 try{
378- c.session.execute(new SimpleStatement(String.format(TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
379+ c.session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
379380 } catch (WriteTimeoutException e) {
380381 assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL);
381382 assertEquals(e.getReceivedAcknowledgements(), 2);
@@ -404,14 +405,12 @@
404405 @Test(groups = "long", expectedExceptions = WriteFailureException.class)
405406 public void should_rethrow_write_failure_when_encountered_on_replica() throws InterruptedException {
406407 String keyspace = "writefailureks";
407- String table = "testtable";
408408
409409 CCMBridge ccm = null;
410410 Cluster cluster = null;
411411
412412 try {
413- ccm = CCMBridge.create("test");
414- ccm.populate(2);
413+ ccm = CCMBridge.builder("test").withNodes(2).notStarted().build();
415414 // Configure 1 of the nodes to fail writes to the keyspace.
416415 ccm.start(1, "-Dcassandra.test.fail_writes_ks=" +keyspace);
417416 ccm.start(2);
@@ -426,11 +425,11 @@
426425
427426 session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 2));
428427 session.execute("USE " + keyspace);
429- session.execute(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table));
428+ session.execute("CREATE TABLE testtable (k text PRIMARY KEY, t text, i int, f float)");
430429
431430 try {
432431 // Query with a CL of ALL to hit all replicas.
433- session.execute(new SimpleStatement(String.format(TestUtils.INSERT_FORMAT, table, "1", "2", 3, 4.0f))
432+ session.execute(new SimpleStatement(String.format(Locale.US, "INSERT INTO testtable (k, t, i, f) VALUES ('%s', '%s', %d, %f)", "1", "2", 3, 4.0f))
434433 .setConsistencyLevel(ConsistencyLevel.ALL));
435434 } catch(WriteFailureException e) {
436435 // Expect a failure for node configured to fail writes.
@@ -470,21 +469,17 @@
470469 CCMBridge ccm = null;
471470 Cluster cluster = null;
472471 try {
473- ccm = CCMBridge.create("test");
474-
475- // This relies on the fact that the previous line did not start the cluster, which is true
476- // but a bit weird considering that other versions of create do
477- // (JAVA-789 will fix this)
478- ccm.updateConfig("tombstone_failure_threshold", "1000");
479- ccm.populate(2);
480- ccm.start();
472+ ccm = CCMBridge.builder("test")
473+ .withNodes(2)
474+ .withCassandraConfiguration("tombstone_failure_threshold", "1000")
475+ .build();
481476
482477 // The rest of the test relies on the fact that the PK '1' will be placed on node1
483478 // (hard-coding it is reasonable considering that C* shouldn't change its default partitioner too often)
484479 cluster = Cluster.builder()
485- .addContactPoint(CCMBridge.ipOfNode(2))
486- .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
487- Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(2), 9042))))
480+ .addContactPoint(CCMBridge.ipOfNode(2))
481+ .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
482+ Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(2), 9042))))
488483 .build();
489484
490485 Session session = cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +2 −2
@@ -57,7 +57,7 @@
5757 CCMBridge ccm = null;
5858 Cluster cluster = null;
5959 try {
60- ccm = CCMBridge.create("test", 1);
60+ ccm = CCMBridge.builder("test").withNodes(1).build();
6161 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1))
6262 .withPoolingOptions(new PoolingOptions()
6363 .setHeartbeatIntervalSeconds(3))
@@ -121,7 +121,7 @@
121121 CCMBridge ccm = null;
122122 Cluster cluster = null;
123123 try {
124- ccm = CCMBridge.create("test", 1);
124+ ccm = CCMBridge.builder("test").withNodes(1).build();
125125 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1))
126126 .withPoolingOptions(new PoolingOptions()
127127 .setHeartbeatIntervalSeconds(0))
added driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +431 −0
@@ -0,0 +1,431 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.Collection;
19+import java.util.List;
20+import java.util.concurrent.*;
21+import java.util.concurrent.atomic.AtomicBoolean;
22+
23+import static java.util.concurrent.TimeUnit.MILLISECONDS;
24+import static java.util.concurrent.TimeUnit.SECONDS;
25+
26+import com.codahale.metrics.Gauge;
27+import com.google.common.collect.Lists;
28+import org.testng.annotations.Test;
29+
30+import static org.assertj.core.api.Assertions.assertThat;
31+import static org.mockito.Mockito.doReturn;
32+import static org.mockito.Mockito.spy;
33+import static org.testng.Assert.fail;
34+
35+public class HostConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
36+ @Override
37+ protected Collection<String> getTableDefinitions() {
38+ StringBuilder sb = new StringBuilder("CREATE TABLE Java349 (mykey INT primary key");
39+ for (int i = 0; i < 1000; i++) {
40+ sb.append(", column").append(i).append(" INT");
41+ }
42+ sb.append(")");
43+ return Lists.newArrayList(sb.toString());
44+ }
45+
46+ @Override
47+ protected Cluster.Builder configure(Cluster.Builder builder) {
48+ // Use version 2 at highest.
49+ ProtocolVersion versionToUse = TestUtils.getDesiredProtocolVersion(ProtocolVersion.V2);
50+ return builder.withProtocolVersion(versionToUse);
51+ }
52+
53+ /**
54+ * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
55+ * of creating a new connection.
56+ *
57+ * @since 2.0.10, 2.1.6
58+ * @jira_ticket JAVA-419
59+ * @test_category connection:connection_pool
60+ */
61+ @Test(groups = "short")
62+ public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException {
63+ HostConnectionPool pool = createPool(2, 2);
64+
65+ assertThat(pool.connections.size()).isEqualTo(2);
66+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
67+
68+ for (int i = 0; i < 256; i++) {
69+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
70+ assertThat(coreConnections).contains(connection);
71+ }
72+
73+ boolean timedOut = false;
74+ try {
75+ pool.borrowConnection(100, MILLISECONDS);
76+ } catch (TimeoutException e) {
77+ timedOut = true;
78+ }
79+ assertThat(timedOut).isTrue();
80+ }
81+
82+ /**
83+ * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
84+ * timeout instead of creating a new connection.
85+ *
86+ * @since 2.0.10, 2.1.6
87+ * @jira_ticket JAVA-419
88+ * @test_category connection:connection_pool
89+ */
90+ @Test(groups = "short")
91+ public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws ConnectionException, TimeoutException {
92+ HostConnectionPool pool = createPool(1, 2);
93+
94+ assertThat(pool.connections.size()).isEqualTo(1);
95+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
96+
97+ //
98+ for (int i = 0; i < 128; i++) {
99+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
100+ assertThat(coreConnections).contains(connection);
101+ }
102+
103+ // Borrow more and ensure the connection returned is a non-core connection.
104+ for (int i = 0; i < 128; i++) {
105+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
106+ assertThat(coreConnections).doesNotContain(connection);
107+ }
108+
109+ boolean timedOut = false;
110+ try {
111+ pool.borrowConnection(100, MILLISECONDS);
112+ } catch (TimeoutException e) {
113+ timedOut = true;
114+ }
115+ assertThat(timedOut).isTrue();
116+ }
117+
118+ /**
119+ * Ensures that if the core connection pool is full that borrowConnection will create and use a new connection.
120+ *
121+ * @since 2.0.10, 2.1.6
122+ * @jira_ticket JAVA-419
123+ * @test_category connection:connection_pool
124+ */
125+ @Test(groups = "short")
126+ public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException {
127+ cluster.getConfiguration().getPoolingOptions()
128+ .setIdleTimeoutSeconds(20);
129+
130+ HostConnectionPool pool = createPool(1, 2);
131+ Connection core = pool.connections.get(0);
132+
133+ // Fill core connection
134+ for (int i = 0; i < 128; i++)
135+ assertThat(
136+ pool.borrowConnection(100, MILLISECONDS)
137+ ).isEqualTo(core);
138+
139+ // Reaching 128 on the core connection should have triggered the creation of an extra one
140+ TimeUnit.MILLISECONDS.sleep(100);
141+ assertThat(pool.connections).hasSize(2);
142+ }
143+
144+ /**
145+ * Ensures that a trashed connection that has not been timed out should be resurrected into the connection pool if
146+ * borrowConnection is called and a new connection is needed.
147+ *
148+ * @since 2.0.10, 2.1.6
149+ * @jira_ticket JAVA-419
150+ * @test_category connection:connection_pool
151+ */
152+ @Test(groups = "long")
153+ public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
154+ cluster.getConfiguration().getPoolingOptions()
155+ .setIdleTimeoutSeconds(20);
156+
157+ HostConnectionPool pool = createPool(1, 2);
158+ Connection connection1 = pool.connections.get(0);
159+
160+ for (int i = 0; i < 101; i++)
161+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
162+
163+ TimeUnit.MILLISECONDS.sleep(100);
164+ assertThat(pool.connections).hasSize(2);
165+ Connection connection2 = pool.connections.get(1);
166+
167+ assertThat(connection1.inFlight.get()).isEqualTo(101);
168+ assertThat(connection2.inFlight.get()).isEqualTo(0);
169+
170+ // Go back under the capacity of 1 connection
171+ for (int i = 0; i < 51; i++)
172+ pool.returnConnection(connection1);
173+
174+ assertThat(connection1.inFlight.get()).isEqualTo(50);
175+ assertThat(connection2.inFlight.get()).isEqualTo(0);
176+
177+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
178+ TimeUnit.SECONDS.sleep(20);
179+ assertThat(pool.connections).containsExactly(connection2);
180+ assertThat(pool.trash).containsExactly(connection1);
181+
182+ // Now borrow enough to go just under the 1 connection threshold
183+ for (int i = 0; i < 50; i++)
184+ pool.borrowConnection(100, MILLISECONDS);
185+
186+ assertThat(pool.connections).containsExactly(connection2);
187+ assertThat(pool.trash).containsExactly(connection1);
188+ assertThat(connection1.inFlight.get()).isEqualTo(50);
189+ assertThat(connection2.inFlight.get()).isEqualTo(50);
190+
191+ // Borrowing one more time should resurrect the trashed connection
192+ pool.borrowConnection(100, MILLISECONDS);
193+ TimeUnit.MILLISECONDS.sleep(100);
194+
195+ assertThat(pool.connections).containsExactly(connection2, connection1);
196+ assertThat(pool.trash).isEmpty();
197+ assertThat(connection1.inFlight.get()).isEqualTo(50);
198+ assertThat(connection2.inFlight.get()).isEqualTo(51);
199+ }
200+
201+ /**
202+ * Ensures that a trashed connection that has been timed out should not be resurrected into the connection pool if
203+ * borrowConnection is called and a new connection is needed.
204+ *
205+ * @since 2.0.10, 2.1.6
206+ * @jira_ticket JAVA-419
207+ * @test_category connection:connection_pool
208+ */
209+ @Test(groups = "long")
210+ public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
211+ cluster.getConfiguration().getPoolingOptions()
212+ .setIdleTimeoutSeconds(20);
213+
214+ HostConnectionPool pool = createPool(1, 2);
215+ Connection connection1 = pool.connections.get(0);
216+
217+ for (int i = 0; i < 101; i++)
218+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
219+
220+ TimeUnit.MILLISECONDS.sleep(100);
221+ assertThat(pool.connections).hasSize(2);
222+ Connection connection2 = pool.connections.get(1);
223+
224+ assertThat(connection1.inFlight.get()).isEqualTo(101);
225+ assertThat(connection2.inFlight.get()).isEqualTo(0);
226+
227+ // Go back under the capacity of 1 connection
228+ for (int i = 0; i < 51; i++)
229+ pool.returnConnection(connection1);
230+
231+ assertThat(connection1.inFlight.get()).isEqualTo(50);
232+ assertThat(connection2.inFlight.get()).isEqualTo(0);
233+
234+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
235+ TimeUnit.SECONDS.sleep(20);
236+ assertThat(pool.connections).containsExactly(connection2);
237+ assertThat(pool.trash).containsExactly(connection1);
238+
239+ // Return trashed connection down to 0 inFlight
240+ for (int i = 0; i < 50; i++)
241+ pool.returnConnection(connection1);
242+ assertThat(connection1.inFlight.get()).isEqualTo(0);
243+
244+ // Give enough time for trashed connection to be cleaned up from the trash:
245+ TimeUnit.SECONDS.sleep(30);
246+ assertThat(pool.connections).containsExactly(connection2);
247+ assertThat(pool.trash).isEmpty();
248+ assertThat(connection1.isClosed()).isTrue();
249+
250+ // Fill the live connection to go over the threshold where a second one is needed
251+ for (int i = 0; i < 101; i++)
252+ assertThat(pool.borrowConnection(100, TimeUnit.MILLISECONDS)).isEqualTo(connection2);
253+ assertThat(connection2.inFlight.get()).isEqualTo(101);
254+ TimeUnit.MILLISECONDS.sleep(100);
255+
256+ // Borrow again to get the new connection
257+ Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
258+ assertThat(connection3)
259+ .isNotEqualTo(connection2) // should not be the full connection
260+ .isNotEqualTo(connection1); // should not be the previously trashed one
261+ }
262+
263+ /**
264+ * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
265+ *
266+ * @since 2.0.10, 2.1.6
267+ * @jira_ticket JAVA-419
268+ * @test_category connection:connection_pool
269+ */
270+ @Test(groups = "long")
271+ public void should_not_close_trashed_connection_until_no_in_flight()
272+ throws ConnectionException, TimeoutException, InterruptedException {
273+ cluster.getConfiguration().getPoolingOptions()
274+ .setIdleTimeoutSeconds(20);
275+
276+ HostConnectionPool pool = createPool(1, 2);
277+ Connection connection1 = pool.connections.get(0);
278+
279+ // Fill core connection enough to trigger creation of another one
280+ for (int i = 0; i < 110; i++)
281+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
282+
283+ TimeUnit.MILLISECONDS.sleep(100);
284+ assertThat(pool.connections).hasSize(2);
285+
286+ // Return enough times to get back under the threshold where one connection is enough
287+ for (int i = 0; i < 50; i++)
288+ pool.returnConnection(connection1);
289+
290+ // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
291+ // It still has in-flight requests so should not get closed.
292+ TimeUnit.SECONDS.sleep(30);
293+ assertThat(pool.trash).containsExactly(connection1);
294+ assertThat(connection1.inFlight.get()).isEqualTo(60);
295+ assertThat(connection1.isClosed()).isFalse();
296+
297+ // Consume all inFlight requests on the trashed connection.
298+ while (connection1.inFlight.get() > 0) {
299+ pool.returnConnection(connection1);
300+ }
301+
302+ // Sleep enough time for the connection to be consider idled and closed.
303+ TimeUnit.SECONDS.sleep(30);
304+
305+ // The connection should be now closed.
306+ // The trashed connection should be closed and not in the pool or trash.
307+ assertThat(connection1.isClosed()).isTrue();
308+ assertThat(pool.connections).doesNotContain(connection1);
309+ assertThat(pool.trash).doesNotContain(connection1);
310+ }
311+
312+ /**
313+ * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
314+ * the connection is put in the trash.
315+ *
316+ * @since 2.0.10, 2.1.6
317+ * @jira_ticket JAVA-419
318+ * @test_category connection:connection_pool
319+ */
320+ @Test(groups = "short")
321+ public void should_trash_on_returning_connection_with_insufficient_streams()
322+ throws ConnectionException, TimeoutException, InterruptedException {
323+ HostConnectionPool pool = createPool(1, 2);
324+ Connection core = pool.connections.get(0);
325+
326+ for (int i = 0; i < 128; i++)
327+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
328+
329+ TimeUnit.MILLISECONDS.sleep(100);
330+ assertThat(pool.connections).hasSize(2);
331+
332+ // Grab the new non-core connection and replace it with a spy.
333+ Connection extra1 = spy(pool.connections.get(1));
334+ pool.connections.set(1, extra1);
335+
336+ // Borrow 10 times to ensure pool is utilized.
337+ for (int i = 0; i < 10; i++) {
338+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1);
339+ }
340+
341+ // Return connection, it should not be trashed since it still has 9 inflight requests.
342+ pool.returnConnection(extra1);
343+ assertThat(pool.connections).hasSize(2);
344+
345+ // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
346+ // this should cause the connection to be replaced and trashed on returnConnection.
347+ doReturn(0).when(extra1).maxAvailableStreams();
348+
349+ // On returning of the connection, should detect that there are no available streams and trash it.
350+ pool.returnConnection(extra1);
351+ assertThat(pool.connections).hasSize(1);
352+ }
353+
354+ private HostConnectionPool createPool(int coreConnections, int maxConnections) {
355+ cluster.getConfiguration().getPoolingOptions()
356+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
357+ .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
358+ Session session = cluster.connect();
359+ Host host = TestUtils.findHost(cluster, 1);
360+ return (HostConnectionPool)((SessionManager)session).pools.get(host);
361+ }
362+
363+ /**
364+ * <p>
365+ * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
366+ * insertions are being executed, the number of opened connection is monitored.
367+ * <p/>
368+ * If at anytime, the number of opened connections is negative, this test will fail.
369+ *
370+ * @since 2.0.6, 2.1.1
371+ * @jira_ticket JAVA-349
372+ * @test_category connection:connection_pool
373+ */
374+ @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */)
375+ public void open_connections_metric_should_always_be_positive() throws InterruptedException {
376+ // Track progress in a dedicated thread
377+ int numberOfInserts = 100 * 1000;
378+ final CountDownLatch pendingInserts = new CountDownLatch(numberOfInserts);
379+ ExecutorService progressReportExecutor = Executors.newSingleThreadExecutor();
380+ final Runnable progressReporter = new Runnable() {
381+ @Override
382+ public void run() {
383+ pendingInserts.countDown();
384+ }
385+ };
386+
387+ // Track opened connections in a dedicated thread every one second
388+ final AtomicBoolean negativeOpenConnectionCountSpotted = new AtomicBoolean(false);
389+ final Gauge<Integer> openConnections = cluster.getMetrics().getOpenConnections();
390+ ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1);
391+ final Runnable openConnectionsWatcher = new Runnable() {
392+ @Override
393+ public void run() {
394+ Integer value = openConnections.getValue();
395+ if (value < 0) {
396+ System.err.println("Negative value spotted for openConnection metric: " + value);
397+ negativeOpenConnectionCountSpotted.set(true);
398+ }
399+ }
400+ };
401+ openConnectionsWatcherExecutor.scheduleAtFixedRate(openConnectionsWatcher, 1, 1, SECONDS);
402+
403+ // Insert 100k lines in a newly created 1k columns table
404+ PreparedStatement insertStatement = session.prepare(generateJava349InsertStatement());
405+ for (int key = 0; key < numberOfInserts; key++) {
406+ session.executeAsync(insertStatement.bind(key)).addListener(progressReporter, progressReportExecutor);
407+ }
408+
409+ // Wait for all inserts to happen and stop connections and progress tracking
410+ pendingInserts.await();
411+ openConnectionsWatcherExecutor.shutdownNow();
412+ progressReportExecutor.shutdownNow();
413+
414+ if (negativeOpenConnectionCountSpotted.get()) {
415+ fail("Negative value spotted for open connection count");
416+ }
417+ }
418+
419+ private String generateJava349InsertStatement() {
420+ StringBuilder sb = new StringBuilder("INSERT INTO Java349 (mykey");
421+ for (int i = 0; i < 1000; i++) {
422+ sb.append(", column").append(i);
423+ }
424+ sb.append(") VALUES (?");
425+ for (int i = 0; i < 1000; i++) {
426+ sb.append(", ").append(i);
427+ }
428+ sb.append(");");
429+ return sb.toString();
430+ }
431+}
added driver-core/src/test/java/com/datastax/driver/core/IndexMetadataAssert.java +85 −0
@@ -0,0 +1,85 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import static org.assertj.core.api.Assertions.assertThat;
19+
20+import org.assertj.core.api.AbstractAssert;
21+
22+import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
23+
24+public class IndexMetadataAssert extends AbstractAssert<IndexMetadataAssert, IndexMetadata> {
25+
26+ public IndexMetadataAssert(IndexMetadata actual) {
27+ super(actual, IndexMetadataAssert.class);
28+ }
29+
30+ public IndexMetadataAssert hasName(String name) {
31+ assertThat(actual.getName()).isEqualTo(name);
32+ return this;
33+ }
34+
35+ public IndexMetadataAssert hasOption(String name, String value) {
36+ assertThat(actual.getOption(name)).isEqualTo(value);
37+ return this;
38+ }
39+
40+ public IndexMetadataAssert asCqlQuery(String cqlQuery) {
41+ assertThat(actual.asCQLQuery()).isEqualTo(cqlQuery);
42+ return this;
43+ }
44+
45+ public IndexMetadataAssert isKeys(){
46+ assertThat(actual.isKeys()).isTrue();
47+ return this;
48+ }
49+
50+ public IndexMetadataAssert isNotKeys(){
51+ assertThat(actual.isKeys()).isFalse();
52+ return this;
53+ }
54+
55+ public IndexMetadataAssert isFull() {
56+ assertThat(actual.isFull()).isTrue();
57+ return this;
58+ }
59+
60+ public IndexMetadataAssert isNotFull() {
61+ assertThat(actual.isFull()).isFalse();
62+ return this;
63+ }
64+
65+ public IndexMetadataAssert isEntries() {
66+ assertThat(actual.isEntries()).isTrue();
67+ return this;
68+ }
69+
70+ public IndexMetadataAssert isNotEntries() {
71+ assertThat(actual.isEntries()).isFalse();
72+ return this;
73+ }
74+
75+ public IndexMetadataAssert isCustomIndex() {
76+ assertThat(actual.isCustomIndex()).isTrue();
77+ return this;
78+ }
79+
80+ public IndexMetadataAssert isNotCustomIndex() {
81+ assertThat(actual.isCustomIndex()).isFalse();
82+ return this;
83+ }
84+
85+}
added driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +240 −0
@@ -0,0 +1,240 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import static com.datastax.driver.core.Assertions.assertThat;
19+import static com.datastax.driver.core.ColumnMetadata.COLUMN_NAME;
20+import static com.datastax.driver.core.ColumnMetadata.COMPONENT_INDEX;
21+import static com.datastax.driver.core.ColumnMetadata.INDEX_NAME;
22+import static com.datastax.driver.core.ColumnMetadata.INDEX_OPTIONS;
23+import static com.datastax.driver.core.ColumnMetadata.INDEX_TYPE;
24+import static com.datastax.driver.core.ColumnMetadata.KIND;
25+import static com.datastax.driver.core.ColumnMetadata.VALIDATOR;
26+import static com.datastax.driver.core.DataType.cint;
27+import static com.datastax.driver.core.DataType.text;
28+
29+import java.nio.ByteBuffer;
30+import java.util.Collection;
31+import java.util.List;
32+
33+import org.testng.annotations.Test;
34+
35+import com.datastax.driver.core.ColumnMetadata.IndexMetadata;
36+import com.datastax.driver.core.ColumnMetadata.Raw;
37+import com.datastax.driver.core.Token.M3PToken;
38+import com.datastax.driver.core.utils.CassandraVersion;
39+import com.google.common.collect.ImmutableList;
40+import com.google.common.primitives.Ints;
41+
42+@CassandraVersion(
43+ major = 1.2)
44+public class IndexMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
45+
46+ @Override
47+ protected Collection<String> getTableDefinitions() {
48+ String createTable = "CREATE TABLE indexing ("
49+ + "id int primary key,"
50+ + "map_values map<text, int>,"
51+ + "map_keys map<text, int>,"
52+ + "map_entries map<text, int>,"
53+ + "text_column text"
54+ +
55+ // Frozen collections was introduced only in C* 2.1.3
56+ (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0
57+ ?
58+ ", map_full frozen<map<text, int>>,"
59+ + "set_full frozen<set<text>>,"
60+ + "list_full frozen<list<text>>);"
61+ :
62+ ")");
63+ return ImmutableList.of(createTable);
64+ }
65+
66+ @Test(
67+ groups = "short")
68+ public void should_not_flag_text_column_index_type() {
69+ String createValuesIndex = String.format("CREATE INDEX text_column_index ON %s.indexing (text_column);", keyspace);
70+ session.execute(createValuesIndex);
71+ IndexMetadata index = getIndexForColumn("text_column");
72+ assertThat(index).hasName("text_column_index")
73+ .isNotKeys()
74+ .isNotFull()
75+ .isNotEntries()
76+ .isNotCustomIndex()
77+ .asCqlQuery(createValuesIndex);
78+ }
79+
80+ @Test(
81+ groups = "short")
82+ @CassandraVersion(
83+ major = 2.1)
84+ public void should_not_flag_map_index_type() {
85+ String createValuesIndex = String.format("CREATE INDEX map_values_index ON %s.indexing (map_values);", keyspace);
86+ session.execute(createValuesIndex);
87+ IndexMetadata index = getIndexForColumn("map_values");
88+ assertThat(index).hasName("map_values_index")
89+ .isNotKeys()
90+ .isNotFull()
91+ .isNotEntries()
92+ .isNotCustomIndex()
93+ .asCqlQuery(createValuesIndex);
94+ }
95+
96+ @Test(
97+ groups = "short")
98+ @CassandraVersion(
99+ major = 2.1)
100+ public void should_flag_map_index_type_as_keys() {
101+ String createKeysIndex = String.format("CREATE INDEX map_keys_index ON %s.indexing (KEYS(map_keys));", keyspace);
102+ session.execute(createKeysIndex);
103+ IndexMetadata index = getIndexForColumn("map_keys");
104+ assertThat(index).hasName("map_keys_index")
105+ .isKeys()
106+ .isNotFull()
107+ .isNotEntries()
108+ .isNotCustomIndex()
109+ .asCqlQuery(createKeysIndex);
110+ }
111+
112+ @Test(
113+ groups = "short")
114+ @CassandraVersion(
115+ major = 2.1,
116+ minor = 3)
117+ public void should_flag_map_index_type_as_full() {
118+ String createFullIndex = String.format("CREATE INDEX map_full_index ON %s.indexing (FULL(map_full));", keyspace);
119+ session.execute(createFullIndex);
120+ IndexMetadata index = getIndexForColumn("map_full");
121+ assertThat(index).hasName("map_full_index")
122+ .isNotKeys()
123+ .isFull()
124+ .isNotEntries()
125+ .isNotCustomIndex()
126+ .asCqlQuery(createFullIndex);
127+ }
128+
129+ @Test(
130+ groups = "short")
131+ @CassandraVersion(
132+ major = 2.1,
133+ minor = 3)
134+ public void should_flag_set_index_type_as_full() {
135+ String createFullIndex = String.format("CREATE INDEX set_full_index ON %s.indexing (FULL(set_full));", keyspace);
136+ session.execute(createFullIndex);
137+ IndexMetadata index = getIndexForColumn("set_full");
138+ assertThat(index).hasName("set_full_index")
139+ .isNotKeys()
140+ .isFull()
141+ .isNotEntries()
142+ .isNotCustomIndex()
143+ .asCqlQuery(createFullIndex);
144+ }
145+
146+ @Test(
147+ groups = "short")
148+ @CassandraVersion(
149+ major = 2.1,
150+ minor = 3)
151+ public void should_flag_list_index_type_as_full() {
152+ String createFullIndex = String.format("CREATE INDEX list_full_index ON %s.indexing (FULL(list_full));", keyspace);
153+ session.execute(createFullIndex);
154+ IndexMetadata index = getIndexForColumn("list_full");
155+ assertThat(index).hasName("list_full_index")
156+ .isNotKeys()
157+ .isFull()
158+ .isNotEntries()
159+ .isNotCustomIndex()
160+ .asCqlQuery(createFullIndex);
161+ }
162+
163+ @Test(
164+ groups = "short")
165+ @CassandraVersion(
166+ major = 3.0)
167+ public void should_flag_map_index_type_as_entries() {
168+ String createEntriesIndex = String.format("CREATE INDEX map_entries_index ON %s.indexing (ENTRIES(map_entries));", keyspace);
169+ session.execute(createEntriesIndex);
170+ IndexMetadata index = getIndexForColumn("map_entries");
171+ assertThat(index).hasName("map_entries_index")
172+ .isNotKeys()
173+ .isNotFull()
174+ .isEntries()
175+ .isNotCustomIndex()
176+ .asCqlQuery(createEntriesIndex);
177+ }
178+
179+ @Test(
180+ groups = "short",
181+ description = "This test case builds a ColumnMetadata object programatically to test custom indices,"
182+ + "otherwise, it would require deploying an actual custom index class into the C* test cluster")
183+ public void should_parse_custom_index_options() {
184+ TableMetadata table = getTable("indexing");
185+ ColumnDefinitions defs = new ColumnDefinitions(new ColumnDefinitions.Definition[] {
186+ definition(COLUMN_NAME, text()),
187+ definition(COMPONENT_INDEX, cint()),
188+ definition(KIND, text()),
189+ definition(INDEX_NAME, text()),
190+ definition(INDEX_TYPE, text()),
191+ definition(VALIDATOR, text()),
192+ definition(INDEX_OPTIONS, text())
193+ });
194+ List<ByteBuffer> data = ImmutableList.of(
195+ wrap("text_column"), // column name
196+ wrap(0), // component index
197+ wrap("regular"), // kind
198+ wrap("custom_index"), // index name
199+ wrap("CUSTOM"), // index type
200+ wrap("org.apache.cassandra.db.marshal.UTF8Type"), // validator
201+ wrap("{\"foo\" : \"bar\", \"class_name\" : \"dummy.DummyIndex\"}") // index options
202+ );
203+ Row row = ArrayBackedRow.fromData(defs, M3PToken.FACTORY, ProtocolVersion.V3, data);
204+ ColumnMetadata column = ColumnMetadata.fromRaw(table, Raw.fromRow(row, VersionNumber.parse("2.1")));
205+ IndexMetadata index = column.getIndex();
206+ assertThat(index).hasName("custom_index")
207+ .isNotKeys()
208+ .isNotFull()
209+ .isNotEntries()
210+ .isCustomIndex()
211+ .hasOption("foo", "bar")
212+ .asCqlQuery(String.format("CREATE CUSTOM INDEX custom_index ON %s.indexing (text_column) "
213+ + "USING 'dummy.DummyIndex' WITH OPTIONS = {'foo' : 'bar', 'class_name' : 'dummy.DummyIndex'};", keyspace));
214+ }
215+
216+ private ColumnDefinitions.Definition definition(String name, DataType type) {
217+ return new ColumnDefinitions.Definition("ks", "table", name, type);
218+ }
219+
220+ private ByteBuffer wrap(String value) {
221+ return ByteBuffer.wrap(value.getBytes());
222+ }
223+
224+ private ByteBuffer wrap(int number) {
225+ return ByteBuffer.wrap(Ints.toByteArray(number));
226+ }
227+
228+ private IndexMetadata getIndexForColumn(String columnName) {
229+ return getColumn(columnName).getIndex();
230+ }
231+
232+ private ColumnMetadata getColumn(String name) {
233+ return getTable("indexing").getColumn(name);
234+ }
235+
236+ private TableMetadata getTable(String name) {
237+ return cluster.getMetadata().getKeyspace(keyspace).getTable(name);
238+ }
239+
240+}
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +2 −2
@@ -51,7 +51,7 @@
5151 CCMBridge ccm = null;
5252 Cluster cluster = null;
5353 try {
54- ccm = CCMBridge.create("test", 2);
54+ ccm = CCMBridge.builder("test").withNodes(2).build();
5555 cluster = Cluster.builder()
5656 .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2))
5757 .withLoadBalancingPolicy(policy)
@@ -86,7 +86,7 @@
8686 CCMBridge ccm = null;
8787 Cluster cluster = null;
8888 try {
89- ccm = CCMBridge.create("test", 2);
89+ ccm = CCMBridge.builder("test").withNodes(2).build();
9090
9191 // In order to validate this behavior, we need to stop the first node that would be attempted to be
9292 // established as the control connection.
modified driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +1 −1
@@ -54,7 +54,7 @@
5454 Cluster cluster = null;
5555
5656 try {
57- ccm = CCMBridge.create("test", 3);
57+ ccm = CCMBridge.builder("test").withNodes(3).build();
5858
5959 cluster = Cluster.builder()
6060 .addContactPoint(CCMBridge.ipOfNode(1))
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +1 −1
@@ -36,7 +36,7 @@
3636
3737 @Test(groups = "short")
3838 public void testMissingRpcAddressAtStartup() throws Exception {
39- CCMBridge ccm = CCMBridge.create("ccm", 2);
39+ CCMBridge ccm = CCMBridge.builder("ccm").withNodes(2).build();
4040
4141 Cluster cluster = null;
4242 try {
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +2 −2
@@ -47,7 +47,7 @@
4747 @Test(groups = "short", dataProvider = "NettyOptionsTest")
4848 public void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception {
4949 //given
50- CCMBridge ccm = CCMBridge.create("test", hosts);
50+ CCMBridge ccm = CCMBridge.builder("test").withNodes(hosts).build();
5151 Cluster cluster = null;
5252 try {
5353 NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
@@ -65,7 +65,7 @@
6565 cluster = Cluster.builder()
6666 .addContactPoint(ipOfNode(1))
6767 .withPoolingOptions(new PoolingOptions()
68- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
68+ .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
6969 )
7070 .withNettyOptions(nettyOptions)
7171 .build();
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +41 −0
@@ -22,8 +22,12 @@
2222 import com.google.common.collect.ImmutableList;
2323 import com.google.common.collect.ImmutableMap;
2424 import com.google.common.collect.ImmutableMap.Builder;
25+import org.apache.log4j.Level;
26+import org.apache.log4j.Logger;
2527 import org.testng.annotations.Test;
2628
29+import static org.assertj.core.api.Assertions.assertThat;
30+
2731 public class NetworkTopologyStrategyTest extends AbstractReplicationStrategyTest {
2832
2933 private static class ReplicationFactorDefinition {
@@ -589,4 +593,41 @@
589593 assertReplicaPlacement(replicaMap, TOKEN17, IP2, IP6, IP1, IP5, IP3, IP4);
590594 assertReplicaPlacement(replicaMap, TOKEN18, IP6, IP1, IP5, IP3, IP2, IP4);
591595 }
596+
597+ @Test(groups = "unit")
598+ public void should_warn_if_replication_factor_cannot_be_met() {
599+ Logger logger = Logger.getLogger(ReplicationStrategy.NetworkTopologyStrategy.class);
600+ MemoryAppender logs = new MemoryAppender();
601+ logger.setLevel(Level.WARN);
602+ logger.addAppender(logs);
603+
604+ List<Token> ring = ImmutableList.<Token>builder()
605+ .add(TOKEN01)
606+ .add(TOKEN02)
607+ .add(TOKEN03)
608+ .add(TOKEN04)
609+ .build();
610+
611+ Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder()
612+ .put(TOKEN01, host(IP1, DC1, RACK11))
613+ .put(TOKEN02, host(IP2, DC1, RACK12))
614+ .put(TOKEN03, host(IP3, DC2, RACK21))
615+ .put(TOKEN04, host(IP4, DC2, RACK22))
616+ .build();
617+
618+ // Wrong configuration: impossible replication factor for DC2
619+ networkTopologyStrategy(rf(DC1, 2), rf(DC2, 3))
620+ .computeTokenToReplicaMap(tokenToPrimary, ring);
621+ assertThat(logs.getNext())
622+ .contains("Error while computing token map for datacenter DC2");
623+
624+ // Wrong configuration: non-existing datacenter
625+ networkTopologyStrategy(rf(DC1, 2), rf("does_not_exist", 2))
626+ .computeTokenToReplicaMap(tokenToPrimary, ring);
627+ assertThat(logs.getNext())
628+ .contains("Error while computing token map for datacenter does_not_exist");
629+
630+ logger.setLevel(null);
631+ logger.removeAppender(logs);
632+ }
592633 }
added driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java +92 −0
@@ -0,0 +1,92 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.Collection;
19+import java.util.Collections;
20+import java.util.concurrent.LinkedBlockingQueue;
21+import java.util.concurrent.ThreadPoolExecutor;
22+import java.util.concurrent.TimeUnit;
23+
24+import org.testng.annotations.Test;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+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;
32+
33+public class PoolingOptionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
34+ @Override
35+ protected Collection<String> getTableDefinitions() {
36+ return Collections.emptyList();
37+ }
38+
39+ /**
40+ * <p>
41+ * Validates that if a custom executor is provided via {@link PoolingOptions#setInitializationExecutor} that it
42+ * is used to create and tear down connections.
43+ * </p>
44+ *
45+ * @test_category connection:connection_pool
46+ * @expected_result executor is used and successfully able to connect and tear down connections.
47+ * @jira_ticket JAVA-692
48+ * @since 2.0.10, 2.1.6
49+ */
50+ @Test(groups = "short")
51+ public void should_be_able_to_use_custom_initialization_executor() {
52+ ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
53+ new LinkedBlockingQueue<Runnable>()));
54+
55+ PoolingOptions poolingOptions = new PoolingOptions();
56+ poolingOptions.setInitializationExecutor(executor);
57+
58+ Cluster cluster = Cluster.builder()
59+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
60+ .withPoolingOptions(poolingOptions).build();
61+ try {
62+ cluster.init();
63+ // Ensure executor used.
64+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
65+
66+ // Reset invocation count.
67+ reset();
68+
69+ Session session = cluster.connect();
70+
71+ // Ensure executor used again to establish core connections.
72+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
73+
74+ // Expect core connections + control connection.
75+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
76+ TestUtils.numberOfLocalCoreConnections(cluster) + 1);
77+
78+ reset();
79+
80+ session.close();
81+
82+ // Executor should have been used to close connections associated with the session.
83+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
84+
85+ // Only the control connection should remain.
86+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
87+ } finally {
88+ cluster.close();
89+ executor.shutdown();
90+ }
91+ }
92+}
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +70 −59
@@ -17,71 +17,82 @@
1717
1818 import org.testng.annotations.Test;
1919
20-import java.util.Collection;
21-import java.util.Collections;
22-import java.util.concurrent.*;
23-
2420 import static org.assertj.core.api.Assertions.assertThat;
25-import static org.mockito.Matchers.any;
26-import static org.mockito.Mockito.*;
27-
28-public class PoolingOptionsTest extends CCMBridge.PerClassSingleNodeCluster {
29- @Override
30- protected Collection<String> getTableDefinitions() {
31- return Collections.emptyList();
21+import static org.assertj.core.api.Assertions.fail;
22+
23+import static com.datastax.driver.core.HostDistance.LOCAL;
24+import static com.datastax.driver.core.HostDistance.REMOTE;
25+
26+public class PoolingOptionsTest {
27+
28+ @Test(groups = "unit")
29+ public void should_initialize_to_v2_defaults_if_v2_or_below() {
30+ PoolingOptions options = new PoolingOptions();
31+ options.setProtocolVersion(ProtocolVersion.V1);
32+
33+ assertThat(options.getCoreConnectionsPerHost(LOCAL)).isEqualTo(2);
34+ assertThat(options.getMaxConnectionsPerHost(LOCAL)).isEqualTo(8);
35+ assertThat(options.getCoreConnectionsPerHost(REMOTE)).isEqualTo(1);
36+ assertThat(options.getMaxConnectionsPerHost(REMOTE)).isEqualTo(2);
37+ assertThat(options.getNewConnectionThreshold(LOCAL)).isEqualTo(100);
38+ assertThat(options.getNewConnectionThreshold(REMOTE)).isEqualTo(100);
39+ assertThat(options.getMaxRequestsPerConnection(LOCAL)).isEqualTo(128);
40+ assertThat(options.getMaxRequestsPerConnection(REMOTE)).isEqualTo(128);
3241 }
3342
34- /**
35- * <p>
36- * Validates that if a custom executor is provided via {@link PoolingOptions#setInitializationExecutor} that it
37- * is used to create and tear down connections.
38- * </p>
39- *
40- * @test_category connection:connection_pool
41- * @expected_result executor is used and successfully able to connect and tear down connections.
42- * @jira_ticket JAVA-692
43- * @since 2.0.10, 2.1.6
44- */
45- @Test(groups = "short")
46- public void should_be_able_to_use_custom_initialization_executor() {
47- ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
48- new LinkedBlockingQueue<Runnable>()));
49-
50- PoolingOptions poolingOptions = new PoolingOptions();
51- poolingOptions.setInitializationExecutor(executor);
52-
53- Cluster cluster = Cluster.builder()
54- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
55- .withPoolingOptions(poolingOptions).build();
56- try {
57- cluster.init();
58- // Ensure executor used.
59- verify(executor, atLeastOnce()).execute(any(Runnable.class));
60-
61- // Reset invocation count.
62- reset();
63-
64- Session session = cluster.connect();
65-
66- // Ensure executor used again to establish core connections.
67- verify(executor, atLeastOnce()).execute(any(Runnable.class));
68-
69- // Expect core connections + control connection.
70- assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
71- TestUtils.numberOfLocalCoreConnections(cluster) + 1);
43+ @Test(groups = "unit")
44+ public void should_initialize_to_v3_defaults_if_v3_or_above() {
45+ PoolingOptions options = new PoolingOptions();
46+ options.setProtocolVersion(ProtocolVersion.V3);
47+
48+ assertThat(options.getCoreConnectionsPerHost(LOCAL)).isEqualTo(1);
49+ assertThat(options.getMaxConnectionsPerHost(LOCAL)).isEqualTo(1);
50+ assertThat(options.getCoreConnectionsPerHost(REMOTE)).isEqualTo(1);
51+ assertThat(options.getMaxConnectionsPerHost(REMOTE)).isEqualTo(1);
52+ assertThat(options.getNewConnectionThreshold(LOCAL)).isEqualTo(800);
53+ assertThat(options.getNewConnectionThreshold(REMOTE)).isEqualTo(200);
54+ assertThat(options.getMaxRequestsPerConnection(LOCAL)).isEqualTo(1024);
55+ assertThat(options.getMaxRequestsPerConnection(REMOTE)).isEqualTo(256);
56+ }
7257
73- reset();
58+ @Test(groups = "unit")
59+ public void should_enforce_invariants_once_protocol_version_known() {
60+ // OK for v2 (default max = 8)
61+ PoolingOptions options = new PoolingOptions().setCoreConnectionsPerHost(LOCAL, 3);
62+ options.setCoreConnectionsPerHost(LOCAL, 3);
63+ options.setProtocolVersion(ProtocolVersion.V2);
64+ assertThat(options.getCoreConnectionsPerHost(LOCAL)).isEqualTo(3);
65+ assertThat(options.getMaxConnectionsPerHost(LOCAL)).isEqualTo(8);
66+
67+ // KO for v3 (default max = 1)
68+ options = new PoolingOptions().setCoreConnectionsPerHost(LOCAL, 3);
69+ try {
70+ options.setProtocolVersion(ProtocolVersion.V3);
71+ fail("Expected an IllegalArgumentException");
72+ } catch (IllegalArgumentException e) {/*expected*/}
73+
74+ // OK for v3 (up to 32K stream ids)
75+ options = new PoolingOptions().setMaxRequestsPerConnection(LOCAL, 5000);
76+ options.setProtocolVersion(ProtocolVersion.V3);
77+ assertThat(options.getMaxRequestsPerConnection(LOCAL)).isEqualTo(5000);
78+
79+ // KO for v2 (up to 128)
80+ options = new PoolingOptions().setMaxRequestsPerConnection(LOCAL, 5000);
81+ try {
82+ options.setProtocolVersion(ProtocolVersion.V2);
83+ fail("Expected an IllegalArgumentException");
84+ } catch (IllegalArgumentException e) {/*expected*/}
85+ }
7486
75- session.close();
87+ @Test(groups = "unit")
88+ public void should_set_core_and_max_connections_simultaneously() {
89+ PoolingOptions options = new PoolingOptions();
90+ options.setProtocolVersion(ProtocolVersion.V2);
7691
77- // Executor should have been used to close connections associated with the session.
78- verify(executor, atLeastOnce()).execute(any(Runnable.class));
92+ options.setConnectionsPerHost(LOCAL, 10, 15);
7993
80- // Only the control connection should remain.
81- assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
82- } finally {
83- cluster.close();
84- executor.shutdown();
85- }
94+ assertThat(options.getCoreConnectionsPerHost(LOCAL)).isEqualTo(10);
95+ assertThat(options.getMaxConnectionsPerHost(LOCAL)).isEqualTo(15);
8696 }
8797 }
98+
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +6 −2
@@ -214,11 +214,15 @@
214214 .build()
215215 );
216216 // when
217+ // when
217218 try {
218219 session.execute(query);
219- fail("Should have thrown UnavailableException");
220- } catch (UnavailableException e) {
220+ fail("Should have thrown NoHostAvailableException");
221+ } catch(NoHostAvailableException e) {
221222 // ok
223+ Throwable error = e.getErrors().get(hostAddress);
224+ assertThat(error).isNotNull();
225+ assertThat(error).isInstanceOf(UnavailableException.class);
222226 }
223227 // then
224228 String line = errorAppender.waitAndGet(5000);
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +8 −8
@@ -44,7 +44,7 @@
4444
4545 @Test(groups = "long")
4646 public void should_ignore_recommissioned_node_on_reconnection_attempt() throws Exception {
47- mainCcm = CCMBridge.create("main", 3);
47+ mainCcm = CCMBridge.builder("main").withNodes(3).build();
4848 // node1 will be our "recommissioned" node, for now we just stop it so that it stays in the peers table.
4949 mainCcm.stop(1);
5050 mainCcm.waitForDown(1);
@@ -56,7 +56,7 @@
5656 // From that point, reconnections to node1 have been scheduled.
5757
5858 // Start another ccm that will reuse node1's address
59- otherCcm = CCMBridge.create("other", 1);
59+ otherCcm = CCMBridge.builder("other").withNodes(1).build();
6060 otherCcm.waitForUp(1);
6161
6262 // Give the driver the time to notice the node is back up and try to connect to it.
@@ -67,7 +67,7 @@
6767
6868 @Test(groups = "long")
6969 public void should_ignore_recommissioned_node_on_control_connection_reconnect() throws Exception {
70- mainCcm = CCMBridge.create("main", 2);
70+ mainCcm = CCMBridge.builder("main").withNodes(2).build();
7171 mainCcm.stop(1);
7272 mainCcm.waitForDown(1);
7373
@@ -77,7 +77,7 @@
7777 waitForCountUpHosts(mainCluster, 1);
7878
7979 // Start another ccm that will reuse node1's address
80- otherCcm = CCMBridge.create("other", 1);
80+ otherCcm = CCMBridge.builder("other").withNodes(1).build();
8181 otherCcm.waitForUp(1);
8282
8383 // Stop node2, the control connection gets defunct
@@ -91,11 +91,11 @@
9191 @Test(groups = "long")
9292 public void should_ignore_recommissioned_node_on_session_init() throws Exception {
9393 // Simulate the bug before starting the cluster
94- mainCcm = CCMBridge.create("main", 2);
94+ mainCcm = CCMBridge.builder("main").withNodes(2).build();
9595 mainCcm.stop(1);
9696 mainCcm.waitForDown(1);
9797
98- otherCcm = CCMBridge.create("other", 1);
98+ otherCcm = CCMBridge.builder("other").withNodes(1).build();
9999 otherCcm.waitForUp(1);
100100
101101 // Start the driver, it should only connect to node 2
@@ -119,11 +119,11 @@
119119 @CassandraVersion(major=2.0)
120120 public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception {
121121 // Simulate the bug before starting the cluster
122- mainCcm = CCMBridge.create("main", 2);
122+ mainCcm = CCMBridge.builder("main").withNodes(2).build();
123123 mainCcm.stop(1);
124124 mainCcm.waitForDown(1);
125125
126- otherCcm = CCMBridge.createWithCustomVersion("main", 1, "1.2.19");
126+ otherCcm = CCMBridge.builder("main").withNodes(1).withCassandraVersion("1.2.19").build();
127127 otherCcm.waitForUp(1);
128128
129129 // Start the driver, it should only connect to node 2
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +8 −8
@@ -53,7 +53,7 @@
5353 CCMBridge ccm = null;
5454 Cluster cluster = null;
5555 try {
56- ccm = CCMBridge.create("test", 2);
56+ ccm = CCMBridge.builder("test").withNodes(2).build();
5757 int reconnectionDelay = 1000;
5858 cluster = Cluster.builder()
5959 .addContactPoint(CCMBridge.ipOfNode(1))
@@ -90,10 +90,10 @@
9090 CCMBridge ccm = null;
9191 Cluster cluster = null;
9292 try {
93- ccm = CCMBridge.create("test");
94- ccm.populate(1);
95- // Configure password authentication on the server (default: cassandra / cassandra)
96- ccm.updateConfig("authenticator", "PasswordAuthenticator");
93+ ccm = CCMBridge.builder("test")
94+ .withCassandraConfiguration("authenticator", "PasswordAuthenticator") // default credentials: cassandra / cassandra
95+ .notStarted()
96+ .build();
9797 ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
9898
9999 DynamicPlainTextAuthProvider authProvider = new DynamicPlainTextAuthProvider("cassandra", "cassandra");
@@ -149,7 +149,7 @@
149149 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
150150
151151 try {
152- ccm = CCMBridge.create("test", 2);
152+ ccm = CCMBridge.builder("test").withNodes(2).build();
153153 cluster = Cluster.builder()
154154 .addContactPoint(CCMBridge.ipOfNode(1))
155155 .withReconnectionPolicy(reconnectionPolicy)
@@ -190,7 +190,7 @@
190190 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
191191
192192 try {
193- ccm = CCMBridge.create("test", 1);
193+ ccm = CCMBridge.builder("test").withNodes(1).build();
194194 cluster = Cluster.builder()
195195 .addContactPoint(CCMBridge.ipOfNode(1))
196196 .withLoadBalancingPolicy(loadBalancingPolicy)
@@ -256,7 +256,7 @@
256256 SocketOptions socketOptions = spy(new SocketOptions());
257257
258258 try {
259- ccm = CCMBridge.create("test", 1);
259+ ccm = CCMBridge.builder("test").withNodes(1).build();
260260 cluster = Cluster.builder()
261261 .addContactPoint(CCMBridge.ipOfNode(1))
262262 .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +1 −2
@@ -41,8 +41,7 @@
4141 LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
4242
4343 // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use
44- ccm = CCMBridge.create("test");
45- ccm.populate(3);
44+ ccm = CCMBridge.builder("test").withNodes(3).notStarted().build();
4645 ccm.start(1);
4746 ccm.start(2);
4847 ccm.waitForUp(1);
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +1 −4
@@ -83,9 +83,6 @@
8383
8484 private Connection getSingleConnection(Session session) {
8585 HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next();
86- if (pool instanceof DynamicConnectionPool)
87- return ((DynamicConnectionPool)pool).connections.get(0);
88- else
89- return ((SingleConnectionPool)pool).connectionRef.get();
86+ return pool.connections.get(0);
9087 }
9188 }
deleted driver-core/src/test/java/com/datastax/driver/core/RetryPolicyTest.java +0 −557
@@ -1,557 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import org.testng.annotations.Test;
19-
20-import com.datastax.driver.core.exceptions.*;
21-import com.datastax.driver.core.policies.*;
22-
23-import static com.datastax.driver.core.TestUtils.waitFor;
24-import static com.datastax.driver.core.TestUtils.waitForDownWithWait;
25-import static org.testng.Assert.*;
26-
27-public class RetryPolicyTest extends AbstractPoliciesTest {
28-
29- /**
30- * Test RetryPolicy to ensure the basic unit get tests for the RetryDecisions.
31- */
32- public static class TestRetryPolicy implements RetryPolicy {
33- public RetryDecision onReadTimeout(Statement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
34- return RetryDecision.rethrow();
35- }
36- public RetryDecision onWriteTimeout(Statement query, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
37- return RetryDecision.rethrow();
38- }
39- public RetryDecision onUnavailable(Statement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
40- return RetryDecision.rethrow();
41- }
42- public static void testRetryDecision() {
43- assertEquals(RetryDecision.retry(ConsistencyLevel.ONE).getType(), RetryDecision.Type.RETRY);
44- assertEquals(RetryDecision.retry(ConsistencyLevel.ONE).getRetryConsistencyLevel(), ConsistencyLevel.ONE);
45- assertEquals(RetryDecision.rethrow().getType(), RetryDecision.Type.RETHROW);
46- assertEquals(RetryDecision.ignore().getType(), RetryDecision.Type.IGNORE);
47-
48- assertEquals(RetryDecision.retry(ConsistencyLevel.ONE).toString(), "Retry at " + ConsistencyLevel.ONE);
49- assertEquals(RetryDecision.rethrow().toString(), "Rethrow");
50- assertEquals(RetryDecision.ignore().toString(), "Ignore");
51- }
52- @Override
53- public void init(Cluster cluster) {}
54- @Override
55- public void close() {}
56- }
57-
58- /**
59- * Test RetryDecision get variables and defaults are correct.
60- */
61- @Test(groups = "unit")
62- public void RetryDecisionTest() throws Throwable {
63- TestRetryPolicy.testRetryDecision();
64- }
65-
66- /*
67- * Test the DefaultRetryPolicy.
68- */
69- @Test(groups = "long")
70- public void defaultRetryPolicy() throws Throwable {
71- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy());
72- defaultPolicyTest(builder);
73- }
74-
75- /*
76- * Test the DefaultRetryPolicy with Logging enabled.
77- */
78- @Test(groups = "long")
79- public void defaultLoggingPolicy() throws Throwable {
80- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy())
81- .withRetryPolicy(new LoggingRetryPolicy(DefaultRetryPolicy.INSTANCE));
82- defaultPolicyTest(builder);
83- }
84-
85- /*
86- * Test the FallthroughRetryPolicy.
87- * Uses the same code that DefaultRetryPolicy uses.
88- */
89- @Test(groups = "long")
90- public void fallthroughRetryPolicy() throws Throwable {
91- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy())
92- .withRetryPolicy(FallthroughRetryPolicy.INSTANCE);
93- defaultPolicyTest(builder);
94- }
95-
96- /*
97- * Test the FallthroughRetryPolicy with Logging enabled.
98- * Uses the same code that DefaultRetryPolicy uses.
99- */
100- @Test(groups = "long")
101- public void fallthroughLoggingPolicy() throws Throwable {
102- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy())
103- .withRetryPolicy(new LoggingRetryPolicy(FallthroughRetryPolicy.INSTANCE));
104- defaultPolicyTest(builder);
105- }
106-
107- public void defaultPolicyTest(Cluster.Builder builder) throws Throwable {
108- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder);
109- try {
110- createSchema(c.session);
111- // FIXME: Race condition where the nodes are not fully up yet and assertQueried reports slightly different numbers with fallthrough*Policy
112- Thread.sleep(5000);
113-
114- init(c, 12);
115- query(c, 12);
116-
117- assertQueried(CCMBridge.IP_PREFIX + '1', 6);
118- assertQueried(CCMBridge.IP_PREFIX + '2', 6);
119-
120- resetCoordinators();
121-
122- // Test reads
123- boolean successfulQuery = false;
124- boolean readTimeoutOnce = false;
125- boolean unavailableOnce = false;
126- boolean restartOnce = false;
127- for (int i = 0; i < 10000; ++i) {
128- try {
129- // Force a ReadTimeoutException to be performed once
130- if (!readTimeoutOnce) {
131- c.cassandraCluster.forceStop(2);
132- }
133-
134- // Force an UnavailableException to be performed once
135- if (readTimeoutOnce && !unavailableOnce) {
136- waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 5);
137- }
138-
139- // Bring back node to ensure other errors are not thrown on restart
140- if (unavailableOnce && !restartOnce) {
141- c.cassandraCluster.start(2);
142- restartOnce = true;
143- }
144-
145- query(c, 12);
146-
147- if (restartOnce)
148- successfulQuery = true;
149- } catch (UnavailableException e) {
150- assertEquals("Not enough replica available for query at consistency ONE (1 required but only 0 alive)", e.getMessage());
151- unavailableOnce = true;
152- } catch (ReadTimeoutException e) {
153- assertEquals("Cassandra timeout during read query at consistency ONE (1 responses were required but only 0 replica responded)", e.getMessage());
154- readTimeoutOnce = true;
155- }
156- }
157-
158- // Ensure the full cycle was completed
159- assertTrue(successfulQuery, "Hit testing race condition. [Never completed successfully.] (Shouldn't be an issue.):\n");
160- assertTrue(readTimeoutOnce, "Hit testing race condition. [Never encountered a ReadTimeoutException.] (Shouldn't be an issue.):\n");
161- assertTrue(unavailableOnce, "Hit testing race condition. [Never encountered an UnavailableException.] (Shouldn't be an issue.):\n");
162-
163- // A weak test to ensure that the nodes were contacted
164- assertQueriedAtLeast(CCMBridge.IP_PREFIX + '1', 1);
165- assertQueriedAtLeast(CCMBridge.IP_PREFIX + '2', 1);
166-
167- resetCoordinators();
168-
169-
170- // Test writes
171- successfulQuery = false;
172- boolean writeTimeoutOnce = false;
173- unavailableOnce = false;
174- restartOnce = false;
175- for (int i = 0; i < 100; ++i) {
176- try {
177- // Force a WriteTimeoutException to be performed once
178- if (!writeTimeoutOnce) {
179- c.cassandraCluster.forceStop(2);
180- }
181-
182- // Force an UnavailableException to be performed once
183- if (writeTimeoutOnce && !unavailableOnce) {
184- waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 5);
185- }
186-
187- // Bring back node to ensure other errors are not thrown on restart
188- if (unavailableOnce && !restartOnce) {
189- c.cassandraCluster.start(2);
190- waitFor(CCMBridge.IP_PREFIX + "2", c.cluster);
191- restartOnce = true;
192- }
193-
194- write(c, 12);
195-
196- if (restartOnce)
197- successfulQuery = true;
198- } catch (UnavailableException e) {
199- assertEquals("Not enough replica available for query at consistency ONE (1 required but only 0 alive)", e.getMessage());
200- unavailableOnce = true;
201- } catch (WriteTimeoutException e) {
202- assertEquals("Cassandra timeout during write query at consistency ONE (1 replica were required but only 0 acknowledged the write)", e.getMessage());
203- writeTimeoutOnce = true;
204- }
205- }
206- // Ensure the full cycle was completed
207- assertTrue(successfulQuery, "Hit testing race condition. [Never completed successfully.] (Shouldn't be an issue.):\n");
208- assertTrue(writeTimeoutOnce, "Hit testing race condition. [Never encountered a ReadTimeoutException.] (Shouldn't be an issue.):\n");
209- assertTrue(unavailableOnce, "Hit testing race condition. [Never encountered an UnavailableException.] (Shouldn't be an issue.):\n");
210-
211- // TODO: Missing test to see if nodes were written to
212-
213-
214- // Test batch writes
215- successfulQuery = false;
216- writeTimeoutOnce = false;
217- unavailableOnce = false;
218- restartOnce = false;
219- for (int i = 0; i < 100; ++i) {
220- try {
221- // Force a WriteTimeoutException to be performed once
222- if (!writeTimeoutOnce) {
223- c.cassandraCluster.forceStop(2);
224- }
225-
226- // Force an UnavailableException to be performed once
227- if (writeTimeoutOnce && !unavailableOnce) {
228- waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 5);
229- }
230-
231- // Bring back node to ensure other errors are not thrown on restart
232- if (unavailableOnce && !restartOnce) {
233- c.cassandraCluster.start(2);
234- waitFor(CCMBridge.IP_PREFIX + "2", c.cluster);
235- restartOnce = true;
236- }
237-
238- write(c, 12, true);
239-
240- if (restartOnce)
241- successfulQuery = true;
242- } catch (UnavailableException e) {
243- assertEquals("Not enough replica available for query at consistency ONE (1 required but only 0 alive)", e.getMessage());
244- unavailableOnce = true;
245- } catch (WriteTimeoutException e) {
246- assertEquals("Cassandra timeout during write query at consistency ONE (1 replica were required but only 0 acknowledged the write)", e.getMessage());
247- writeTimeoutOnce = true;
248- }
249- }
250- // Ensure the full cycle was completed
251- assertTrue(successfulQuery, "Hit testing race condition. [Never completed successfully.] (Shouldn't be an issue.):\n");
252- assertTrue(writeTimeoutOnce, "Hit testing race condition. [Never encountered a ReadTimeoutException.] (Shouldn't be an issue.):\n");
253- assertTrue(unavailableOnce, "Hit testing race condition. [Never encountered an UnavailableException.] (Shouldn't be an issue.):\n");
254-
255- // TODO: Missing test to see if nodes were written to
256-
257- } catch (Throwable e) {
258- c.errorOut();
259- throw e;
260- } finally {
261- resetCoordinators();
262- c.discard();
263- }
264- }
265-
266- /**
267- * Tests DowngradingConsistencyRetryPolicy
268- */
269- @Test(groups = "long")
270- public void downgradingConsistencyRetryPolicy() throws Throwable {
271- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy())
272- .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
273- downgradingConsistencyRetryPolicy(builder);
274- }
275-
276- /**
277- * Tests DowngradingConsistencyRetryPolicy with LoggingRetryPolicy
278- */
279- @Test(groups = "long")
280- public void downgradingConsistencyLoggingPolicy() throws Throwable {
281- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy())
282- .withRetryPolicy(new LoggingRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE));
283- downgradingConsistencyRetryPolicy(builder);
284- }
285-
286- /**
287- * Tests DowngradingConsistencyRetryPolicy
288- */
289- public void downgradingConsistencyRetryPolicy(Cluster.Builder builder) throws Throwable {
290- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
291- try {
292- createSchema(c.session, 3);
293- // FIXME: Race condition where the nodes are not fully up yet and assertQueried reports slightly different numbers
294- Thread.sleep(5000);
295-
296- init(c, 12, ConsistencyLevel.ALL);
297- query(c, 12, ConsistencyLevel.ALL);
298-
299- assertQueried(CCMBridge.IP_PREFIX + '1', 4);
300- assertQueried(CCMBridge.IP_PREFIX + '2', 4);
301- assertQueried(CCMBridge.IP_PREFIX + '3', 4);
302-
303- resetCoordinators();
304- c.cassandraCluster.stop(2);
305- waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 10);
306-
307- query(c, 12, ConsistencyLevel.ALL);
308-
309- assertQueried(CCMBridge.IP_PREFIX + '1', 6);
310- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
311- assertQueried(CCMBridge.IP_PREFIX + '3', 6);
312-
313- resetCoordinators();
314- c.cassandraCluster.stop(1);
315- waitForDownWithWait(CCMBridge.IP_PREFIX + '1', c.cluster, 10);
316-
317- try {
318- query(c, 12, ConsistencyLevel.ALL);
319- } catch (ReadTimeoutException e) {
320- assertEquals("Cassandra timeout during read query at consistency TWO (2 responses were required but only 1 replica responded)", e.getMessage());
321- }
322-
323- Thread.sleep(15000);
324- resetCoordinators();
325-
326- try {
327- query(c, 12, ConsistencyLevel.TWO);
328- } catch (Exception e) {
329- fail("Only 1 node is up and CL.TWO should downgrade and pass.");
330- }
331-
332- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
333- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
334- assertQueried(CCMBridge.IP_PREFIX + '3', 12);
335-
336- resetCoordinators();
337-
338- try {
339- query(c, 12, ConsistencyLevel.ALL);
340- } catch (Exception e) {
341- fail("Only 1 node is up and CL.ALL should downgrade and pass.");
342- }
343-
344- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
345- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
346- assertQueried(CCMBridge.IP_PREFIX + '3', 12);
347-
348- resetCoordinators();
349-
350- query(c, 12, ConsistencyLevel.QUORUM);
351-
352- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
353- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
354- assertQueried(CCMBridge.IP_PREFIX + '3', 12);
355-
356- resetCoordinators();
357-
358- query(c, 12, ConsistencyLevel.TWO);
359-
360- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
361- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
362- assertQueried(CCMBridge.IP_PREFIX + '3', 12);
363-
364- resetCoordinators();
365-
366- query(c, 12, ConsistencyLevel.ONE);
367-
368- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
369- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
370- assertQueried(CCMBridge.IP_PREFIX + '3', 12);
371-
372- } catch (Throwable e) {
373- c.errorOut();
374- throw e;
375- } finally {
376- resetCoordinators();
377- c.discard();
378- }
379- }
380-
381- /*
382- * Test the AlwaysIgnoreRetryPolicy with Logging enabled.
383- */
384- @Test(groups = "long")
385- public void alwaysIgnoreRetryPolicyTest() throws Throwable {
386- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy())
387- .withRetryPolicy(new LoggingRetryPolicy(AlwaysIgnoreRetryPolicy.INSTANCE));
388- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder);
389-
390- try {
391- createSchema(c.session);
392- init(c, 12);
393- query(c, 12);
394-
395- assertQueried(CCMBridge.IP_PREFIX + '1', 6);
396- assertQueried(CCMBridge.IP_PREFIX + '2', 6);
397-
398- resetCoordinators();
399-
400- // Test failed reads
401- c.cassandraCluster.forceStop(2);
402- for (int i = 0; i < 10; ++i) {
403- query(c, 12);
404- }
405-
406- // A weak test to ensure that the nodes were contacted
407- assertQueried(CCMBridge.IP_PREFIX + '1', 120);
408- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
409- resetCoordinators();
410-
411-
412- c.cassandraCluster.start(2);
413- waitFor(CCMBridge.IP_PREFIX + '2', c.cluster);
414-
415- // Test successful reads
416- for (int i = 0; i < 10; ++i) {
417- query(c, 12);
418- }
419-
420- // A weak test to ensure that the nodes were contacted
421- assertQueriedAtLeast(CCMBridge.IP_PREFIX + '1', 1);
422- assertQueriedAtLeast(CCMBridge.IP_PREFIX + '2', 1);
423- resetCoordinators();
424-
425-
426- // Test writes
427- for (int i = 0; i < 100; ++i) {
428- init(c, 12);
429- }
430-
431- // TODO: Missing test to see if nodes were written to
432-
433-
434- // Test failed writes
435- c.cassandraCluster.forceStop(2);
436- for (int i = 0; i < 100; ++i) {
437- init(c, 12);
438- }
439-
440- // TODO: Missing test to see if nodes were written to
441-
442- } catch (Throwable e) {
443- c.errorOut();
444- throw e;
445- } finally {
446- resetCoordinators();
447- c.discard();
448- }
449- }
450-
451- private class QueryRunnable implements Runnable {
452- private CCMBridge.CCMCluster c;
453- private int i;
454-
455- public QueryRunnable(CCMBridge.CCMCluster c, int i) {
456- this.c = c;
457- this.i = i;
458- }
459-
460- public void run(){
461- query(c, i);
462- }
463- }
464-
465- private class InitRunnable implements Runnable {
466- private CCMBridge.CCMCluster c;
467- private int i;
468-
469- public InitRunnable(CCMBridge.CCMCluster c, int i) {
470- this.c = c;
471- this.i = i;
472- }
473-
474- public void run(){
475- try {
476- init(c, i);
477- fail();
478- } catch (DriverInternalError e) {
479- } catch (NoHostAvailableException e) { }
480- }
481- }
482-
483- /*
484- * Test the AlwaysIgnoreRetryPolicy with Logging enabled.
485- */
486- @Test(groups = "long")
487- public void alwaysRetryRetryPolicyTest() throws Throwable {
488- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy())
489- .withRetryPolicy(new LoggingRetryPolicy(AlwaysRetryRetryPolicy.INSTANCE));
490- CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder);
491-
492- try {
493- createSchema(c.session);
494- init(c, 12);
495- query(c, 12);
496-
497- assertQueried(CCMBridge.IP_PREFIX + '1', 6);
498- assertQueried(CCMBridge.IP_PREFIX + '2', 6);
499-
500- resetCoordinators();
501-
502- // Test failed reads
503- c.cassandraCluster.forceStop(2);
504-
505- Thread t1 = new Thread(new QueryRunnable(c, 12));
506- t1.start();
507- t1.join(10000);
508- if (t1.isAlive())
509- t1.interrupt();
510-
511- // A weak test to ensure that the nodes were contacted
512- assertQueried(CCMBridge.IP_PREFIX + '1', 0);
513- assertQueried(CCMBridge.IP_PREFIX + '2', 0);
514- resetCoordinators();
515-
516-
517- c.cassandraCluster.start(2);
518- waitFor(CCMBridge.IP_PREFIX + '2', c.cluster);
519-
520- // Test successful reads
521- for (int i = 0; i < 10; ++i) {
522- query(c, 12);
523- }
524-
525- // A weak test to ensure that the nodes were contacted
526- assertQueriedAtLeast(CCMBridge.IP_PREFIX + '1', 1);
527- assertQueriedAtLeast(CCMBridge.IP_PREFIX + '2', 1);
528- resetCoordinators();
529-
530-
531- // Test writes
532- for (int i = 0; i < 100; ++i) {
533- init(c, 12);
534- }
535-
536- // TODO: Missing test to see if nodes were written to
537-
538-
539- // Test failed writes
540- c.cassandraCluster.forceStop(2);
541- Thread t2 = new Thread(new InitRunnable(c, 12));
542- t2.start();
543- t2.join(10000);
544- if (t2.isAlive())
545- t2.interrupt();
546-
547- // TODO: Missing test to see if nodes were written to
548-
549- } catch (Throwable e) {
550- c.errorOut();
551- throw e;
552- } finally {
553- resetCoordinators();
554- c.discard();
555- }
556- }
557-}
modified driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +16 −3
@@ -25,9 +25,7 @@
2525 import com.google.common.collect.Lists;
2626 import org.scassandra.Scassandra;
2727 import org.scassandra.ScassandraFactory;
28-import org.scassandra.http.client.ColumnTypes;
29-import org.scassandra.http.client.PrimingClient;
30-import org.scassandra.http.client.PrimingRequest;
28+import org.scassandra.http.client.*;
3129
3230 /**
3331 * Launches multiple SCassandra instances, and mocks the appropriate request to make the driver think
@@ -43,11 +41,13 @@
4341 private final List<Scassandra> scassandras;
4442 private final List<InetAddress> addresses;
4543 private final List<PrimingClient> primingClients;
44+ private final List<ActivityClient> activityClients;
4645
4746 public SCassandraCluster(String ipPrefix, int nodeCount) {
4847 scassandras = Lists.newArrayListWithCapacity(nodeCount);
4948 addresses = Lists.newArrayListWithCapacity(nodeCount);
5049 primingClients = Lists.newArrayListWithCapacity(nodeCount);
50+ activityClients = Lists.newArrayListWithCapacity(nodeCount);
5151
5252 for (int i = 1; i <= nodeCount; i++) {
5353 String ip = ipPrefix + i;
@@ -64,6 +64,10 @@
6464 primingClients.add(PrimingClient.builder()
6565 .withHost(ip).withPort(scassandra.getAdminPort())
6666 .build());
67+ activityClients.add(ActivityClient.builder()
68+ .withHost(ip).withPort(scassandra.getAdminPort())
69+ .build()
70+ );
6771 }
6872 primePeers();
6973 }
@@ -82,12 +86,21 @@
8286 return this;
8387 }
8488
89+ public List<Query> retrieveQueries(int node) {
90+ return activityClients.get(node - 1).retrieveQueries();
91+ }
92+
8593 public void clearAllPrimes() {
8694 for (PrimingClient primingClient : primingClients)
8795 primingClient.clearAllPrimes();
8896 primePeers();
8997 }
9098
99+ public void clearAllRecordedActivity() {
100+ for (ActivityClient activityClient : activityClients)
101+ activityClient.clearAllRecordedActivity();
102+ }
103+
91104 private void primePeers() {
92105 for (int i = 0; i < scassandras.size(); i++)
93106 primePeers(primingClients.get(i), scassandras.get(i));
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +3 −10
@@ -17,7 +17,6 @@
1717
1818 import java.security.KeyStore;
1919 import java.security.SecureRandom;
20-import java.util.concurrent.TimeUnit;
2120
2221 import com.google.common.base.Optional;
2322 import javax.net.ssl.KeyManagerFactory;
@@ -25,15 +24,9 @@
2524 import javax.net.ssl.TrustManagerFactory;
2625 import org.testng.annotations.AfterClass;
2726 import org.testng.annotations.BeforeClass;
28-import org.testng.annotations.Test;
2927
30-import com.datastax.driver.core.exceptions.NoHostAvailableException;
31-
32-import static com.datastax.driver.core.Assertions.assertThat;
3328 import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD;
34-import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH;
3529 import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD;
36-import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH;
3730 public abstract class SSLTestBase {
3831
3932 private final boolean requireClientAuth;
@@ -46,9 +39,9 @@
4639
4740 @BeforeClass(groups={"short", "long"})
4841 public void beforeClass() {
49- ccm = CCMBridge.create("test");
50- ccm.enableSSL(requireClientAuth);
51- ccm.bootstrapNode(1);
42+ ccm = CCMBridge.builder("test")
43+ .withSSL(requireClientAuth)
44+ .build();
5245 }
5346
5447 @AfterClass(groups={"short", "long"})
modified driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +1 −1
@@ -41,7 +41,7 @@
4141
4242 @BeforeClass(groups = "short")
4343 public void setup() {
44- ccm = CCMBridge.create("schema_agreement", 2);
44+ ccm = CCMBridge.builder("schema_agreement").withNodes(2).build();
4545 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
4646 session = cluster.connect();
4747 session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +6 −5
@@ -42,11 +42,12 @@
4242
4343 @BeforeClass(groups = "short")
4444 public void setup() {
45- ccm = CCMBridge.create("schemaChangesTest");
46- // Only enable user defined functions if protocol version is >= 4.
47- if(TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V4) >= 0)
48- ccm.updateConfig("enable_user_defined_functions", "true");
49- ccm.bootstrapNode(1);
45+ ccm = CCMBridge.builder("schemaChangesTest")
46+ .withNodes(1)
47+ .withCassandraConfiguration("enable_user_defined_functions",
48+ // Only enable user defined functions if protocol version is >= 4.
49+ Boolean.toString(TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V4) >= 0))
50+ .build();
5051
5152 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
5253 cluster2 = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +54 −8
@@ -25,31 +25,33 @@
2525 import com.google.common.collect.Lists;
2626 import org.testng.annotations.Test;
2727
28+import static org.assertj.core.api.Assertions.fail;
29+
30+import com.datastax.driver.core.exceptions.InvalidQueryException;
2831 import com.datastax.driver.core.utils.SocketChannelMonitor;
2932
3033 import static com.datastax.driver.core.Assertions.assertThat;
3134
32-
3335 public class SessionLeakTest {
3436
3537 Cluster cluster;
3638 List<InetSocketAddress> nodes = Lists.newArrayList(
37- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
38- new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
39+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
40+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
3941 SocketChannelMonitor channelMonitor;
4042
4143 @Test(groups = "short")
4244 public void connectionLeakTest() throws Exception {
4345 // Checking for JAVA-342
4446 CCMBridge ccmBridge;
45- ccmBridge = CCMBridge.create("test", 1);
47+ ccmBridge = CCMBridge.builder("test").withNodes(1).build();
4648 channelMonitor = new SocketChannelMonitor();
4749 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
4850 try {
4951 cluster = Cluster.builder()
50- .addContactPointsWithPorts(Collections.singletonList(
51- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
52- .withNettyOptions(channelMonitor.nettyOptions()).build();
52+ .addContactPointsWithPorts(Collections.singletonList(
53+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
54+ .withNettyOptions(channelMonitor.nettyOptions()).build();
5355
5456 cluster.init();
5557
@@ -88,7 +90,51 @@
8890 assertThat(cluster.manager.sessions.size()).isEqualTo(0);
8991 assertOpenConnections(1);
9092 } finally {
91- if(cluster != null){
93+ if (cluster != null) {
94+ cluster.close();
95+ }
96+ if (ccmBridge != null) {
97+ ccmBridge.remove();
98+ }
99+ // Ensure no channels remain open.
100+ channelMonitor.stop();
101+ channelMonitor.report();
102+ assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(0);
103+ }
104+ }
105+
106+ @Test(groups = "short")
107+ public void should_not_leak_session_when_wrong_keyspace() throws Exception {
108+ // Checking for JAVA-806
109+ CCMBridge ccmBridge;
110+ ccmBridge = CCMBridge.builder("test").withNodes(1).build();
111+ channelMonitor = new SocketChannelMonitor();
112+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
113+ try {
114+ cluster = Cluster.builder()
115+ .addContactPointsWithPorts(Collections.singletonList(
116+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
117+ .withNettyOptions(channelMonitor.nettyOptions()).build();
118+
119+ cluster.init();
120+
121+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
122+ // Should be 1 control connection after initialization.
123+ assertOpenConnections(1);
124+
125+ cluster.connect("wrong_keyspace");
126+
127+ fail("Should not have connected to a wrong keyspace");
128+
129+ } catch (InvalidQueryException e) {
130+
131+ // ok
132+
133+ } finally {
134+
135+ assertThat(cluster.manager.sessions.size()).isEqualTo(0);
136+
137+ if (cluster != null) {
92138 cluster.close();
93139 }
94140 if (ccmBridge != null) {
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +46 −41
@@ -17,7 +17,10 @@
1717
1818 import com.datastax.driver.core.utils.SocketChannelMonitor;
1919 import com.google.common.collect.Lists;
20-import com.google.common.util.concurrent.*;
20+import com.google.common.util.concurrent.ListenableFuture;
21+import com.google.common.util.concurrent.ListeningExecutorService;
22+import com.google.common.util.concurrent.MoreExecutors;
23+import com.google.common.util.concurrent.Uninterruptibles;
2124 import org.slf4j.Logger;
2225 import org.slf4j.LoggerFactory;
2326 import org.testng.annotations.Test;
@@ -35,6 +38,10 @@
3538
3639 private ListeningExecutorService executorService;
3740
41+ private Cluster stressCluster;
42+
43+ private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
44+
3845 public SessionStressTest() {
3946 // 8 threads should be enough so that we stress the driver and not the OS thread scheduler
4047 executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(8));
@@ -45,7 +52,6 @@
4552 return new ArrayList<String>(0);
4653 }
4754
48-
4955 /**
5056 * Stress test on opening/closing sessions.
5157 * <p/>
@@ -71,34 +77,34 @@
7177 */
7278 @Test(groups = "long")
7379 public void sessions_should_not_leak_connections() {
80+ List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
7481 // override inherited field with a new cluster object and ensure 0 sessions and connections
75- SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
7682 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
77- List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
78- cluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
83+ stressCluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
7984 .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
8085 .withNettyOptions(channelMonitor.nettyOptions()).build();
81- cluster.init();
82-
83- // The cluster has been initialized, we should have 1 connection.
84- assertEquals(cluster.manager.sessions.size(), 0);
85- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
86-
87- // The first session initializes the cluster and its control connection
88- // This is a local cluster so we also have 2 connections per session
89- Session session = cluster.connect();
90- assertEquals(cluster.manager.sessions.size(), 1);
91- int coreConnections = TestUtils.numberOfLocalCoreConnections(cluster);
92- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections);
93- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections);
94-
95- // Closing the session keeps the control connection opened
96- session.close();
97- assertEquals(cluster.manager.sessions.size(), 0);
98- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
99- assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
10086
10187 try {
88+ stressCluster.init();
89+
90+ // The cluster has been initialized, we should have 1 connection.
91+ assertEquals(stressCluster.manager.sessions.size(), 0);
92+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
93+
94+ // The first session initializes the cluster and its control connection
95+ // This is a local cluster so we also have 2 connections per session
96+ Session session = stressCluster.connect();
97+ assertEquals(stressCluster.manager.sessions.size(), 1);
98+ int coreConnections = TestUtils.numberOfLocalCoreConnections(stressCluster);
99+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections);
100+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections);
101+
102+ // Closing the session keeps the control connection opened
103+ session.close();
104+ assertEquals(stressCluster.manager.sessions.size(), 0);
105+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
106+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
107+
102108 int nbOfSessions = 2000;
103109 int halfOfTheSessions = nbOfSessions / 2;
104110 int nbOfIterations = 5;
@@ -111,8 +117,8 @@
111117
112118 // We should see the exact number of opened sessions
113119 // Since we have 2 connections per session, we should see 2 * sessions + control connection
114- assertEquals(cluster.manager.sessions.size(), nbOfSessions);
115- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
120+ assertEquals(stressCluster.manager.sessions.size(), nbOfSessions);
121+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
116122 coreConnections * nbOfSessions + 1);
117123 assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1);
118124
@@ -121,8 +127,8 @@
121127 waitFor(closeSessionsConcurrently(halfOfTheSessions));
122128
123129 // Check that we have the right number of sessions and connections
124- assertEquals(cluster.manager.sessions.size(), halfOfTheSessions);
125- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
130+ assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
131+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
126132 coreConnections * (nbOfSessions / 2) + 1);
127133 assertEquals(channelMonitor.openChannels(contactPoints).size(),
128134 coreConnections * (nbOfSessions / 2) + 1);
@@ -139,8 +145,8 @@
139145 waitFor(closeSessionsFutures);
140146
141147 // Check that we have the same number of sessions and connections
142- assertEquals(cluster.manager.sessions.size(), halfOfTheSessions);
143- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
148+ assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions);
149+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(),
144150 coreConnections * (nbOfSessions / 2) + 1);
145151 assertEquals(channelMonitor.openChannels(contactPoints).size(),
146152 coreConnections * (nbOfSessions / 2) + 1);
@@ -150,8 +156,8 @@
150156 waitFor(closeSessionsConcurrently(halfOfTheSessions));
151157
152158 // Check that we have a clean state
153- assertEquals(cluster.manager.sessions.size(), 0);
154- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
159+ assertEquals(stressCluster.manager.sessions.size(), 0);
160+ assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1);
155161 assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
156162
157163 // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl)
@@ -159,12 +165,13 @@
159165 Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.SECONDS);
160166 }
161167 } finally {
162- cluster.close();
168+ stressCluster.close();
163169
164170 // Ensure no channels remain open.
171+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
172+
165173 channelMonitor.stop();
166174 channelMonitor.report();
167- assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
168175 }
169176 }
170177
@@ -177,7 +184,7 @@
177184 // Open new sessions once all tasks have been created
178185 List<ListenableFuture<Session>> sessionFutures = Lists.newArrayListWithCapacity(iterations);
179186 for (int i = 0; i < iterations; i++) {
180- sessionFutures.add(executorService.submit(new OpenSession(cluster, countDownLatch)));
187+ sessionFutures.add(executorService.submit(new OpenSession(countDownLatch)));
181188 }
182189 countDownLatch.countDown();
183190 return sessionFutures;
@@ -191,7 +198,7 @@
191198 private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations, CountDownLatch countDownLatch) {
192199 // Get a reference to every session we want to close
193200 Stack<Session> sessionsToClose = new Stack<Session>();
194- Iterator<? extends Session> iterator = cluster.manager.sessions.iterator();
201+ Iterator<? extends Session> iterator = stressCluster.manager.sessions.iterator();
195202 for (int i = 0; i < iterations; i++) {
196203 sessionsToClose.push(iterator.next());
197204 }
@@ -228,19 +235,17 @@
228235 }
229236 }
230237
231- private static class OpenSession implements Callable<Session> {
232- private final Cluster cluster;
238+ private class OpenSession implements Callable<Session> {
233239 private final CountDownLatch startSignal;
234240
235- OpenSession(Cluster cluster, CountDownLatch startSignal) {
236- this.cluster = cluster;
241+ OpenSession(CountDownLatch startSignal) {
237242 this.startSignal = startSignal;
238243 }
239244
240245 @Override
241246 public Session call() throws Exception {
242247 startSignal.await();
243- return cluster.connect();
248+ return stressCluster.connect();
244249 }
245250 }
246251
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +7 −9
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
1918 import java.util.*;
2019 import java.util.concurrent.CountDownLatch;
2120 import java.util.concurrent.ExecutorService;
@@ -23,8 +22,7 @@
2322 import java.util.concurrent.TimeUnit;
2423
2524 import com.datastax.driver.core.utils.CassandraVersion;
26-import com.datastax.driver.core.utils.SocketChannelMonitor;
27-import io.netty.channel.socket.SocketChannel;
25+
2826 import org.slf4j.Logger;
2927 import org.slf4j.LoggerFactory;
3028 import org.testng.annotations.Test;
@@ -49,9 +47,9 @@
4947
5048 @Override
5149 protected Collection<String> getTableDefinitions() {
52- return Arrays.asList(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
53- String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE2),
54- String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE3),
50+ 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),
5553 String.format("CREATE TABLE %s (k text PRIMARY KEY, c counter)", COUNTER_TABLE));
5654 }
5755
@@ -59,7 +57,7 @@
5957 public void executeTest() throws Exception {
6058 // Simple calls to all versions of the execute/executeAsync methods
6159 String key = "execute_test";
62- ResultSet rs = session.execute(String.format(Locale.US, TestUtils.INSERT_FORMAT, TABLE1, key, "foo", 42, 24.03f));
60+ ResultSet rs = session.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE1, key, "foo", 42, 24.03f));
6361 assertTrue(rs.isExhausted());
6462
6563 // execute
@@ -76,7 +74,7 @@
7674 // Simple calls to all versions of the execute/executeAsync methods for prepared statements
7775 // Note: the goal is only to exercice the Session methods, PreparedStatementTest have better prepared statement tests.
7876 String key = "execute_prepared_test";
79- ResultSet rs = session.execute(String.format(Locale.US, TestUtils.INSERT_FORMAT, TABLE2, key, "foo", 42, 24.03f));
77+ ResultSet rs = session.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE2, key, "foo", 42, 24.03f));
8078 assertTrue(rs.isExhausted());
8179
8280 PreparedStatement p = session.prepare(String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = ?", TABLE2));
@@ -146,7 +144,7 @@
146144
147145 // Simple calls to all versions of the execute/executeAsync methods
148146 String key = "execute_compressed_test_" + compression;
149- ResultSet rs = compressedSession.execute(String.format(Locale.US, TestUtils.INSERT_FORMAT, TABLE3, key, "foo", 42, 24.03f));
147+ ResultSet rs = compressedSession.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE3, key, "foo", 42, 24.03f));
150148 assertTrue(rs.isExhausted());
151149
152150 String SELECT_ALL = String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = '%s'", TABLE3, key);
modified driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +1 −1
@@ -41,7 +41,7 @@
4141 // Throttle to a very low value. Even a single thread can generate a higher throughput.
4242 final int maxRequests = 10;
4343 cluster.getConfiguration().getPoolingOptions()
44- .setMaxSimultaneousRequestsPerHostThreshold(HostDistance.LOCAL, maxRequests);
44+ .setMaxRequestsPerConnection(HostDistance.LOCAL, maxRequests);
4545
4646 // Track in flight requests in a dedicated thread every second
4747 final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false);
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +4 −5
@@ -34,11 +34,10 @@
3434 Cluster cluster = null;
3535
3636 try {
37- ccm = CCMBridge.create("test");
38- // force the initial token to a non-min value to validate that the single range will always be ]minToken, minToken]
39- ccm.updateConfig("initial_token", "1");
40- ccm.bootstrapNode(1);
41- ccm.start();
37+ 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();
4241
4342 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
4443
added driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java +82 −0
@@ -0,0 +1,82 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.Collection;
19+import java.util.Comparator;
20+import java.util.Iterator;
21+import java.util.SortedSet;
22+import java.util.concurrent.ConcurrentSkipListSet;
23+
24+import com.google.common.primitives.UnsignedBytes;
25+
26+import com.datastax.driver.core.policies.LoadBalancingPolicy;
27+
28+/**
29+ * A load balancing policy that sorts hosts on the last byte of the address,
30+ * so that the query plan is always [host1, host2, host3].
31+ */
32+public class SortingLoadBalancingPolicy implements LoadBalancingPolicy {
33+
34+ private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() {
35+ @Override
36+ public int compare(Host host1, Host host2) {
37+ byte[] address1 = host1.getAddress().getAddress();
38+ byte[] address2 = host2.getAddress().getAddress();
39+ return UnsignedBytes.compare(
40+ address1[address1.length - 1],
41+ address2[address2.length - 1]);
42+ }
43+ });
44+
45+ @Override
46+ public void init(Cluster cluster, Collection<Host> hosts) {
47+ this.hosts.addAll(hosts);
48+ }
49+
50+ @Override
51+ public HostDistance distance(Host host) {
52+ return HostDistance.LOCAL;
53+ }
54+
55+ @Override
56+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
57+ return hosts.iterator();
58+ }
59+
60+ @Override
61+ public void onAdd(Host host) {
62+ onUp(host);
63+ }
64+
65+ @Override
66+ public void onUp(Host host) {
67+ hosts.add(host);
68+ }
69+
70+ @Override
71+ public void onDown(Host host) {
72+ hosts.remove(host);
73+ }
74+
75+ @Override
76+ public void onRemove(Host host) {
77+ onDown(host);
78+ }
79+
80+ @Override
81+ public void close() {/*nothing to do*/}
82+}
added driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +77 −0
@@ -0,0 +1,77 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.Collection;
19+
20+import com.google.common.collect.Lists;
21+import org.mockito.Mockito;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+import static org.mockito.Mockito.times;
26+
27+import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
28+import com.datastax.driver.core.utils.CassandraVersion;
29+
30+/**
31+ * Test that needs a real CCM cluster (as opposed to SCassandra for other specex tests), because
32+ * it uses a protocol v3 feature.
33+ */
34+public class SpeculativeExecutionIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35+
36+ TimestampGenerator timestampGenerator;
37+
38+ @Override
39+ protected Collection<String> getTableDefinitions() {
40+ return Lists.newArrayList("create table foo(k int primary key, v int)");
41+ }
42+
43+ @Override
44+ protected Cluster.Builder configure(Cluster.Builder builder) {
45+ timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE);
46+ 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));
51+ }
52+
53+ /**
54+ * Validates that if a query gets speculatively re-executed, the second execution uses the same default timestamp.
55+ *
56+ * @test_category tracing
57+ * @jira_ticket JAVA-724
58+ * @expected_result timestamp generator invoked only once for a query that caused two executions.
59+ */
60+ @Test(groups = "short")
61+ @CassandraVersion(major = 2.1)
62+ public void should_use_same_default_timestamp_for_all_executions() {
63+ Metrics.Errors errors = cluster.getMetrics().getErrorMetrics();
64+
65+ Mockito.reset(timestampGenerator);
66+ long execStartCount = errors.getSpeculativeExecutions().getCount();
67+
68+ BatchStatement batch = new BatchStatement();
69+ for (int k = 0; k < 1000; k++) {
70+ batch.add(new SimpleStatement("insert into foo(k,v) values (?,1)", k));
71+ }
72+ session.execute(batch);
73+
74+ assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount + 1);
75+ Mockito.verify(timestampGenerator, times(1)).next();
76+ }
77+}
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +34 −59
@@ -16,19 +16,20 @@
1616 package com.datastax.driver.core;
1717
1818 import java.util.*;
19-import java.util.concurrent.ConcurrentSkipListSet;
2019
20+import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2121 import com.google.common.collect.ImmutableList;
2222 import com.google.common.collect.ImmutableMap;
23-import com.google.common.primitives.UnsignedBytes;
2423 import org.scassandra.http.client.PrimingRequest;
2524 import org.testng.annotations.*;
2625
2726 import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
28-import com.datastax.driver.core.policies.LoadBalancingPolicy;
2927 import com.datastax.driver.core.policies.RetryPolicy;
3028
3129 import static com.datastax.driver.core.Assertions.assertThat;
30+import static org.mockito.Mockito.mock;
31+import static org.mockito.Mockito.times;
32+import static org.mockito.Mockito.verify;
3233
3334 public class SpeculativeExecutionTest {
3435 SCassandraCluster scassandras;
@@ -172,6 +173,36 @@
172173 assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(host3);
173174 }
174175
176+ /**
177+ * Validates that when a Cluster is initialized that {@link SpeculativeExecutionPolicy#init(Cluster)} is called and
178+ * that when a Cluster is closed {@link SpeculativeExecutionPolicy#close()} is called.
179+ *
180+ * @test_category queries:speculative_execution
181+ * @expected_result init and close are called on cluster init and close.
182+ * @jira_ticket JAVA-796
183+ * @since 2.0.11, 2.1.7, 2.2.1
184+ */
185+ @Test(groups="short")
186+ public void should_init_and_close_policy_on_cluster() {
187+ SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class);
188+
189+ Cluster cluster = Cluster.builder()
190+ .addContactPoint(CCMBridge.ipOfNode(2))
191+ .withSpeculativeExecutionPolicy(mockPolicy)
192+ .build();
193+
194+ verify(mockPolicy, times(0)).init(cluster);
195+ verify(mockPolicy, times(0)).close();
196+
197+ try {
198+ cluster.init();
199+ verify(mockPolicy, times(1)).init(cluster);
200+ } finally {
201+ cluster.close();
202+ verify(mockPolicy, times(1)).close();
203+ }
204+ }
205+
175206 @AfterMethod(groups = "short")
176207 public void afterMethod() {
177208 scassandras.clearAllPrimes();
@@ -185,62 +216,6 @@
185216 scassandras.stop();
186217 }
187218
188- /**
189- * A load balancing policy that sorts hosts on the last byte of the address,
190- * so that the query plan is always [host1, host2, host3].
191- */
192- static class SortingLoadBalancingPolicy implements LoadBalancingPolicy {
193-
194- private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() {
195- @Override
196- public int compare(Host host1, Host host2) {
197- byte[] address1 = host1.getAddress().getAddress();
198- byte[] address2 = host2.getAddress().getAddress();
199- return UnsignedBytes.compare(
200- address1[address1.length - 1],
201- address2[address2.length - 1]);
202- }
203- });
204-
205- @Override
206- public void init(Cluster cluster, Collection<Host> hosts) {
207- this.hosts.addAll(hosts);
208- }
209-
210- @Override
211- public HostDistance distance(Host host) {
212- return HostDistance.LOCAL;
213- }
214-
215- @Override
216- public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
217- return hosts.iterator();
218- }
219-
220- @Override
221- public void onAdd(Host host) {
222- onUp(host);
223- }
224-
225- @Override
226- public void onUp(Host host) {
227- hosts.add(host);
228- }
229-
230- @Override
231- public void onDown(Host host) {
232- hosts.remove(host);
233- }
234-
235- @Override
236- public void onRemove(Host host) {
237- onDown(host);
238- }
239-
240- @Override
241- public void close() {}
242- }
243-
244219 /**
245220 * Custom retry policy that retries at ONE on read timeout.
246221 * This deals with the fact that Scassandra only allows read timeouts with 0 replicas.
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +82 −51
@@ -15,78 +15,109 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.google.common.collect.Sets;
19-import org.testng.annotations.Test;
18+import java.util.concurrent.CountDownLatch;
19+
20+import static java.util.concurrent.TimeUnit.MINUTES;
2021
21-import java.util.Set;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
24+import org.testng.annotations.Test;
2225
23-import static org.testng.Assert.assertEquals;
26+import static org.assertj.core.api.Assertions.assertThat;
2427
25-import static com.datastax.driver.core.TestUtils.*;
28+import static com.datastax.driver.core.StateListenerTest.TestListener.Event.*;
2629
27-/**
28- * Simple test of the Sessions methods against a one node cluster.
29- */
3030 public class StateListenerTest {
31+ private static final Logger logger = LoggerFactory.getLogger(StateListenerTest.class);
3132
3233 @Test(groups = "long")
33- public void listenerTest() throws Throwable {
34-
35- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder());
36- Cluster cluster = c.cluster;
37-
34+ public void should_receive_events_when_node_states_change() throws InterruptedException {
35+ CCMBridge ccm = null;
36+ Cluster cluster = null;
3837 try {
39- CountingListener listener = new CountingListener();
38+ ccm = CCMBridge.builder("test").build();
39+ cluster = Cluster.builder()
40+ .addContactPoint(CCMBridge.ipOfNode(1))
41+ .build();
42+ cluster.init();
43+ TestListener listener = new TestListener();
4044 cluster.register(listener);
4145
42- c.cassandraCluster.bootstrapNode(2);
43- waitFor(CCMBridge.IP_PREFIX + '2', cluster);
44-
45- // We sleep slightly before checking the listener because the node is marked UP
46- // just before the listeners are called, and since waitFor is based on isUP,
47- // it can return *just* before the listener are called.
48- Thread.sleep(500);
49- assertEquals(listener.adds.size(), 1);
50-
51- c.cassandraCluster.forceStop(1);
52- waitForDown(CCMBridge.IP_PREFIX + '1', cluster);
53- Thread.sleep(500);
54- assertEquals(listener.downs.size(), 1);
55-
56- c.cassandraCluster.start(1);
57- waitFor(CCMBridge.IP_PREFIX + '1', cluster);
58- Thread.sleep(500);
59- assertEquals(listener.ups.size(), 1);
60-
61- c.cassandraCluster.decommissionNode(2);
62- waitForDecommission(CCMBridge.IP_PREFIX + '2', cluster);
63- Thread.sleep(500);
64- assertEquals(listener.removes.size(), 1);
65- } catch (Throwable e) {
66- c.errorOut();
67- throw e;
46+ listener.setExpectedEvent(ADD);
47+ ccm.bootstrapNode(2);
48+ listener.waitForEvent();
49+
50+ listener.setExpectedEvent(DOWN);
51+ ccm.forceStop(1);
52+ listener.waitForEvent();
53+
54+ listener.setExpectedEvent(UP);
55+ ccm.start(1);
56+ listener.waitForEvent();
57+
58+ listener.setExpectedEvent(REMOVE);
59+ ccm.decommissionNode(2);
60+ listener.waitForEvent();
61+
6862 } finally {
69- c.discard();
63+ if (cluster != null)
64+ cluster.close();
65+ if (ccm != null)
66+ ccm.remove();
7067 }
7168 }
7269
73- private static class CountingListener implements Host.StateListener {
70+ static class TestListener implements Host.StateListener {
71+ enum Event {ADD, UP, SUSPECTED, DOWN, REMOVE}
72+
73+ volatile CountDownLatch latch;
74+ volatile Event expectedEvent;
75+ volatile Event actualEvent;
7476
75- public Set<Host> adds = Sets.newHashSet();
76- public Set<Host> removes = Sets.newHashSet();
77- public Set<Host> ups = Sets.newHashSet();
78- public Set<Host> downs = Sets.newHashSet();
77+ void setExpectedEvent(Event expectedEvent) {
78+ logger.debug("Set expected event {}", expectedEvent);
79+ this.expectedEvent = expectedEvent;
80+ latch = new CountDownLatch(1);
81+ }
7982
80- public void onAdd(Host host) { adds.add(host); }
83+ void waitForEvent() throws InterruptedException {
84+ assertThat(latch.await(2, MINUTES))
85+ .as("Timed out waiting for event " + expectedEvent)
86+ .isTrue();
87+ assertThat(actualEvent).isEqualTo(expectedEvent);
88+ }
8189
82- public void onUp(Host host) { ups.add(host); }
90+ private void reportActualEvent(Event event) {
91+ if (latch.getCount() == 0) {
92+ // TODO this actually happens because C* sends REMOVE/ADD/REMOVE on a remove
93+ logger.error("Was not waiting for an event but got {} (this should eventually be fixed by JAVA-657)", event);
94+ return;
95+ }
96+ logger.debug("Got event {}", event);
97+ actualEvent = event;
98+ latch.countDown();
99+ }
83100
84- public void onSuspected(Host host) {}
101+ @Override
102+ public void onAdd(Host host) {
103+ reportActualEvent(ADD);
104+ }
85105
86- public void onDown(Host host) { downs.add(host); }
106+ @Override
107+ public void onUp(Host host) {
108+ reportActualEvent(UP);
109+ }
87110
88- public void onRemove(Host host) { removes.add(host); }
111+ @Override
112+ public void onDown(Host host) {
113+ reportActualEvent(DOWN);
114+ }
89115
116+ @Override
117+ public void onRemove(Host host) {
118+ reportActualEvent(REMOVE);
119+ }
120+
90121 @Override
91122 public void onRegister(Cluster cluster) {}
92123
modified driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +56 −3
@@ -16,6 +16,9 @@
1616 package com.datastax.driver.core;
1717
1818 import com.google.common.collect.ImmutableList;
19+import com.google.common.collect.ImmutableMap;
20+import com.google.common.collect.Lists;
21+import com.google.common.collect.Sets;
1922 import org.testng.annotations.Test;
2023
2124 import static org.assertj.core.api.Assertions.assertThat;
@@ -89,15 +92,65 @@
8992 return ImmutableList.<BuiltStatement>of(
9093 update("foo").with(set("v", 1)).where(eq("k", 1)), // set simple value
9194 update("foo").with(add("s", 1)).where(eq("k", 1)), // add to set
92- update("foo").with(put("m", "a", 1)).where(eq("k", 1)) // put in map
95+ update("foo").with(put("m", "a", 1)).where(eq("k", 1)), // put in map
96+
97+ // select statements should be idempotent even with function calls
98+ select().countAll() .from("foo").where(eq("k", 1)),
99+ select().ttl("v") .from("foo").where(eq("k", 1)),
100+ select().writeTime("v") .from("foo").where(eq("k", 1)),
101+ select().fcall("token", "k").from("foo").where(eq("k", 1))
102+
93103 );
94104 }
95105
96106 private static ImmutableList<BuiltStatement> nonIdempotentBuiltStatements() {
97- return ImmutableList.<BuiltStatement>of(
107+ return ImmutableList.of(
98108 update("foo").with(append("l", 1)).where(eq("k", 1)), // append to list
99109 update("foo").with(set("v", 1)).and(prepend("l", 1)).where(eq("k", 1)), // prepend to list
100- update("foo").with(incr("c")).where(eq("k", 1)) // counter update
110+ update("foo").with(incr("c")).where(eq("k", 1)), // counter update
111+
112+ // function calls
113+
114+ insertInto("foo").value("k", 1).value("v", fcall("token", "k")),
115+ insertInto("foo").value("k", 1).value("v", now()),
116+ insertInto("foo").value("k", 1).value("v", uuid()),
117+
118+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(fcall("token", "k"))),
119+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())),
120+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(uuid())),
121+
122+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, fcall("token", "k")}),
123+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, now()}),
124+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, uuid()}),
125+
126+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", fcall("token", "k"))}),
127+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", now())}),
128+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", uuid())}),
129+
130+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(fcall("token", "k"), "foo")}),
131+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(now() , "foo")}),
132+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(uuid() , "foo")}),
133+
134+ update("foo").with(set("v", fcall("token", "k"))) .where(eq("k", 1)),
135+ update("foo").with(set("v", now())) .where(eq("k", 1)),
136+ update("foo").with(set("v", uuid())) .where(eq("k", 1)),
137+
138+ update("foo").with(set("v", Lists.newArrayList(fcall("token", "k")))).where(eq("k", 1)),
139+ update("foo").with(set("v", Lists.newArrayList(now()))) .where(eq("k", 1)),
140+ update("foo").with(set("v", Lists.newArrayList(uuid()))) .where(eq("k", 1)),
141+
142+ // raw() calls
143+
144+ insertInto("foo").value("k", 1).value("v", raw("foo()")),
145+ insertInto("foo").value("k", 1).value("v", Sets.newHashSet(raw("foo()"))),
146+
147+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, raw("foo()")}),
148+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of("foo", raw("foo()"))}),
149+ insertInto("foo").values(new String[]{"k", "v"}, new Object[]{1, ImmutableMap.of(raw("foo()"), "foo")}),
150+
151+ update("foo").with(set("v", raw("foo()"))) .where(eq("k", 1)),
152+ update("foo").with(set("v", Lists.newArrayList(raw("foo()")))).where(eq("k", 1))
153+
101154 );
102155 }
103156 }
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +1 −7
@@ -48,9 +48,6 @@
4848 public static final String SIMPLE_KEYSPACE = "ks";
4949 public static final String SIMPLE_TABLE = "test";
5050
51- public static final String CREATE_TABLE_SIMPLE_FORMAT = "CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)";
52-
53- public static final String INSERT_FORMAT = "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)";
5451 public static final String SELECT_ALL_FORMAT = "SELECT * FROM %s";
5552
5653 public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60);
@@ -431,10 +428,7 @@
431428
432429 public static int numberOfLocalCoreConnections(Cluster cluster) {
433430 Configuration configuration = cluster.getConfiguration();
434- ProtocolVersion protocolVersion = configuration.getProtocolOptions().getProtocolVersion();
435- return (protocolVersion.compareTo(ProtocolVersion.V3) < 0)
436- ? configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL)
437- : 1;
431+ return configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL);
438432 }
439433
440434 /**
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +15 −19
@@ -68,11 +68,9 @@
6868
6969 static List<InetSocketAddress> nodes;
7070
71- static PreparedStatement statement;
72-
7371 @BeforeClass(groups = "long")
7472 public void beforeClass() throws Exception {
75- ccmBridge = CCMBridge.create("test", 3);
73+ ccmBridge = CCMBridge.builder("test").withNodes(3).build();
7674 channelMonitor = new SocketChannelMonitor();
7775 nodes = Lists.newArrayList(
7876 new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
@@ -80,16 +78,13 @@
8078 new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
8179 );
8280
83- PoolingOptions poolingOptions = new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 8);
81+ PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, 8, 8);
8482
8583 cluster = Cluster.builder()
8684 .addContactPointsWithPorts(nodes)
8785 .withPoolingOptions(poolingOptions)
8886 .withNettyOptions(channelMonitor.nettyOptions())
8987 .build();
90- Session session = cluster.connect();
91- setupSchema(session);
92- session.close();
9388 }
9489
9590 @AfterClass(groups = "long")
@@ -129,11 +124,17 @@
129124 * @since 2.0.10, 2.1.6
130125 */
131126 @Test(groups = "long")
132- public void host_state_should_be_maintained_with_timeouts() {
127+ public void host_state_should_be_maintained_with_timeouts() throws Exception {
128+ // Setup schema and insert records.
129+ Session session = cluster.connect();
130+ setupSchema(session);
131+ session.close();
132+
133133 // Set very low timeouts.
134134 cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS);
135135 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS);
136- Session session = cluster.connect();
136+ session = cluster.connect();
137+ PreparedStatement statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;");
137138
138139 int workers = Runtime.getRuntime().availableProcessors();
139140 ExecutorService workerPool = Executors.newFixedThreadPool(workers,
@@ -147,7 +148,7 @@
147148 try {
148149 Semaphore concurrentQueries = new Semaphore(CONCURRENT_QUERIES);
149150 for (int i = 0; i < workers; i++) {
150- workerPool.submit(new TimeoutStressWorker(session, concurrentQueries, stopped));
151+ workerPool.submit(new TimeoutStressWorker(session, statement, concurrentQueries, stopped));
151152 }
152153
153154 long startTime = System.currentTimeMillis();
@@ -213,20 +214,13 @@
213214 + ");");
214215
215216 int records = 30000;
216- List<ResultSetFuture> futures = Lists.newArrayListWithExpectedSize(records);
217-
218217 PreparedStatement insertStmt = session.prepare("insert into record (name, phone, value) values (?, ?, ?)");
219218
220219 for (int i = 0; i < records; i++) {
221220 if (i % 1000 == 0)
222221 logger.debug("Inserting record {}.", i);
223- futures.add(session.executeAsync(insertStmt.bind("0", Integer.toString(i), "test")));
222+ session.execute(insertStmt.bind("0", Integer.toString(i), "test"));
224223 }
225-
226- statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;");
227-
228- logger.debug("Completed inserting data. Waiting up to 30 for inserts to complete seconds before proceeding.");
229- Futures.allAsList(futures).get(30, TimeUnit.SECONDS);
230224 logger.debug("Inserts complete.");
231225 }
232226
@@ -235,9 +229,11 @@
235229 private final Semaphore concurrentQueries;
236230 private final AtomicBoolean stopped;
237231 private final Session session;
232+ private final PreparedStatement statement;
238233
239- public TimeoutStressWorker(Session session, Semaphore concurrentQueries, AtomicBoolean stopped) {
234+ public TimeoutStressWorker(Session session, PreparedStatement statement, Semaphore concurrentQueries, AtomicBoolean stopped) {
240235 this.session = session;
236+ this.statement = statement;
241237 this.concurrentQueries = concurrentQueries;
242238 this.stopped = stopped;
243239 }
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +1 −1
@@ -72,7 +72,7 @@
7272
7373 @BeforeClass(groups = "short")
7474 public void setup() {
75- ccm = CCMBridge.create("test", 3, ccmOptions);
75+ ccm = CCMBridge.builder("test").withNodes(3).withStartOptions(ccmOptions).build();
7676
7777 // Only connect to node 1, which makes it easier to query system tables in should_expose_tokens_per_host()
7878 LoadBalancingPolicy lbp = new WhiteListPolicy(new RoundRobinPolicy(),
added driver-core/src/test/java/com/datastax/driver/core/TracingTest.java +98 −0
@@ -0,0 +1,98 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.Collection;
19+import java.util.Collections;
20+import java.util.List;
21+import java.util.UUID;
22+
23+import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
24+import com.datastax.driver.core.utils.CassandraVersion;
25+import org.testng.annotations.BeforeClass;
26+import org.testng.annotations.Test;
27+
28+import static org.assertj.core.api.Assertions.assertThat;
29+
30+@CassandraVersion(major=2.0)
31+public class TracingTest extends CCMBridge.PerClassSingleNodeCluster {
32+
33+ @Override
34+ protected Cluster.Builder configure(Cluster.Builder builder) {
35+ return builder.withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
36+ }
37+
38+ public static final String KEY = "tracing_test";
39+
40+ @Override
41+ protected Collection<String> getTableDefinitions() {
42+ return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
43+ }
44+
45+ @BeforeClass(groups = "short")
46+ public void initData() {
47+ for (int i = 0; i < 100; i++) {
48+ session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", KEY, i));
49+ }
50+ }
51+
52+ /**
53+ * Validates that for each page the {@link ExecutionInfo} will have a different tracing ID.
54+ *
55+ * @test_category tracing
56+ * @expected_result {@link ResultSet} where all the {@link ExecutionInfo} will contains a different tracing ID and
57+ * that the events can be retrieved for the last query.
58+ */
59+ @Test(groups = "short")
60+ public void should_have_a_different_tracingId_for_each_page() {
61+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
62+ ResultSet result = session.execute(st.setFetchSize(40).enableTracing());
63+ result.all();
64+
65+ List<ExecutionInfo> executions = result.getAllExecutionInfo();
66+
67+ UUID previousTraceId = null;
68+ for (ExecutionInfo executionInfo : executions) {
69+ QueryTrace queryTrace = executionInfo.getQueryTrace();
70+ assertThat(queryTrace).isNotNull();
71+ assertThat(queryTrace.getTraceId()).isNotEqualTo(previousTraceId);
72+ previousTraceId = queryTrace.getTraceId();
73+ }
74+
75+ assertThat(result.getExecutionInfo().getQueryTrace().getEvents()).isNotNull()
76+ .isNotEmpty();
77+ }
78+
79+ /**
80+ * Validates that if a query gets retried, the second internal query will still have tracing enabled.
81+ *
82+ * To force a retry, we use the downgrading policy with an impossible CL.
83+ *
84+ * @test_category tracing
85+ * @jira_ticket JAVA-815
86+ * @expected_result {@link ResultSet} where {@link ExecutionInfo} contains trace information after a retry.
87+ */
88+ @Test(groups = "short")
89+ public void should_preserve_tracing_status_across_retries() {
90+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
91+ st.setConsistencyLevel(ConsistencyLevel.THREE).enableTracing();
92+
93+ ResultSet result = session.execute(st);
94+
95+ assertThat(result.getExecutionInfo().getQueryTrace()).isNotNull();
96+ }
97+}
98+
added driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +147 −0
@@ -0,0 +1,147 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import java.util.List;
19+import java.util.Map;
20+
21+import com.google.common.collect.ImmutableList;
22+import com.google.common.collect.ImmutableMap;
23+import org.mockito.Mockito;
24+import org.scassandra.http.client.PrimingRequest;
25+import org.testng.annotations.AfterClass;
26+import org.testng.annotations.AfterMethod;
27+import org.testng.annotations.BeforeClass;
28+import org.testng.annotations.BeforeMethod;
29+
30+import static org.assertj.core.api.Assertions.assertThat;
31+import static org.mockito.Matchers.any;
32+import static org.mockito.Matchers.anyBoolean;
33+import static org.mockito.Matchers.anyInt;
34+import static org.mockito.Mockito.times;
35+
36+import com.datastax.driver.core.*;
37+
38+/**
39+ * Base class for retry policy integration tests.
40+ *
41+ * We use SCassandra to easily simulate specific errors (unavailable, read timeout...) on nodes,
42+ * and SortingLoadBalancingPolicy to get a predictable order of the query plan (always host1, host2, host3).
43+ *
44+ * Note that SCassandra only allows a limited number of test cases, for instance it always returns errors
45+ * with receivedResponses = 0. If that becomes more finely tuneable in the future, we'll be able to add more
46+ * tests in child classes.
47+ */
48+public class AbstractRetryPolicyIntegrationTest {
49+ protected SCassandraCluster scassandras;
50+ protected Cluster cluster = null;
51+ protected Metrics.Errors errors;
52+ protected Host host1, host2, host3;
53+ protected Session session;
54+
55+ protected RetryPolicy retryPolicy;
56+
57+ protected AbstractRetryPolicyIntegrationTest(RetryPolicy retryPolicy) {
58+ this.retryPolicy = Mockito.spy(retryPolicy);
59+ }
60+
61+ @BeforeClass(groups = "short")
62+ public void beforeClass() {
63+ scassandras = new SCassandraCluster(CCMBridge.IP_PREFIX, 3);
64+ }
65+
66+ @BeforeMethod(groups = "short")
67+ public void beforeMethod() {
68+ cluster = Cluster.builder()
69+ .addContactPoint(CCMBridge.ipOfNode(1))
70+ .withRetryPolicy(retryPolicy)
71+ .withLoadBalancingPolicy(new SortingLoadBalancingPolicy())
72+ .build();
73+
74+ session = cluster.connect();
75+
76+ host1 = TestUtils.findHost(cluster, 1);
77+ host2 = TestUtils.findHost(cluster, 2);
78+ host3 = TestUtils.findHost(cluster, 3);
79+
80+ errors = cluster.getMetrics().getErrorMetrics();
81+
82+ Mockito.reset(retryPolicy);
83+ scassandras.clearAllPrimes();
84+ scassandras.clearAllRecordedActivity();
85+ }
86+
87+ protected void simulateError(int hostNumber, PrimingRequest.Result result) {
88+ scassandras
89+ .prime(hostNumber, PrimingRequest.queryBuilder()
90+ .withQuery("mock query")
91+ .withResult(result)
92+ .build());
93+ }
94+
95+ protected void simulateNormalResponse(int hostNumber) {
96+ scassandras
97+ .prime(hostNumber, PrimingRequest.queryBuilder()
98+ .withQuery("mock query")
99+ .withRows(row("result", "result1"))
100+ .build());
101+ }
102+
103+ private static List<Map<String, ?>> row(String key, String value) {
104+ return ImmutableList.<Map<String, ?>>of(ImmutableMap.of(key, value));
105+ }
106+
107+ protected ResultSet query() {
108+ return query(session);
109+ }
110+
111+ protected ResultSet query(Session session) {
112+ return session.execute("mock query");
113+ }
114+
115+ protected void assertOnReadTimeoutWasCalled(int times) {
116+ Mockito.verify(retryPolicy, times(times)).onReadTimeout(
117+ any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyBoolean(), anyInt());
118+
119+ }
120+
121+ protected void assertOnWriteTimeoutWasCalled(int times) {
122+ Mockito.verify(retryPolicy, times(times)).onWriteTimeout(
123+ any(Statement.class), any(ConsistencyLevel.class), any(WriteType.class), anyInt(), anyInt(), anyInt());
124+ }
125+
126+ protected void assertOnUnavailableWasCalled(int times) {
127+ Mockito.verify(retryPolicy, times(times)).onUnavailable(
128+ any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
129+ }
130+
131+ protected void assertQueried(int hostNumber, int times) {
132+ assertThat(scassandras.retrieveQueries(hostNumber)).hasSize(times);
133+ }
134+
135+ @AfterMethod(groups = "short")
136+ public void afterMethod() {
137+ scassandras.clearAllPrimes();
138+ if (cluster != null)
139+ cluster.close();
140+ }
141+
142+ @AfterClass(groups = "short")
143+ public void afterClass() {
144+ if (scassandras != null)
145+ scassandras.stop();
146+ }
147+}
deleted driver-core/src/test/java/com/datastax/driver/core/policies/AlwaysIgnoreRetryPolicy.java +0 −50
@@ -1,50 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core.policies;
17-
18-import com.datastax.driver.core.Cluster;
19-import com.datastax.driver.core.ConsistencyLevel;
20-import com.datastax.driver.core.Statement;
21-import com.datastax.driver.core.WriteType;
22-
23-public class AlwaysIgnoreRetryPolicy implements RetryPolicy {
24-
25- public static final AlwaysIgnoreRetryPolicy INSTANCE = new AlwaysIgnoreRetryPolicy();
26-
27- private AlwaysIgnoreRetryPolicy() {}
28-
29- public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
30- return RetryDecision.ignore();
31- }
32-
33- public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
34- return RetryDecision.ignore();
35- }
36-
37- public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
38- return RetryDecision.ignore();
39- }
40-
41- @Override
42- public void init(Cluster cluster) {
43- // nothing to do
44- }
45-
46- @Override
47- public void close() {
48- // nothing to do
49- }
50-}
deleted driver-core/src/test/java/com/datastax/driver/core/policies/AlwaysRetryRetryPolicy.java +0 −50
@@ -1,50 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core.policies;
17-
18-import com.datastax.driver.core.Cluster;
19-import com.datastax.driver.core.ConsistencyLevel;
20-import com.datastax.driver.core.Statement;
21-import com.datastax.driver.core.WriteType;
22-
23-public class AlwaysRetryRetryPolicy implements RetryPolicy {
24-
25- public static final AlwaysRetryRetryPolicy INSTANCE = new AlwaysRetryRetryPolicy();
26-
27- private AlwaysRetryRetryPolicy() {}
28-
29- public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
30- return RetryDecision.retry(ConsistencyLevel.ONE);
31- }
32-
33- public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
34- return RetryDecision.retry(ConsistencyLevel.ONE);
35- }
36-
37- public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
38- return RetryDecision.retry(ConsistencyLevel.ONE);
39- }
40-
41- @Override
42- public void init(Cluster cluster) {
43- // nothing to do
44- }
45-
46- @Override
47- public void close() {
48- // nothing to do
49- }
50-}
modified driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java +1 −1
@@ -29,7 +29,7 @@
2929 CCMBridge ccm = null;
3030 Cluster cluster = null;
3131 try {
32- ccm = CCMBridge.create("test", 1);
32+ ccm = CCMBridge.builder("test").withNodes(1).build();
3333 cluster = Cluster.builder()
3434 .addContactPoint(CCMBridge.ipOfNode(1))
3535 .withLoadBalancingPolicy(policy)
added driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +94 −0
@@ -0,0 +1,94 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+import static org.assertj.core.api.Assertions.fail;
22+import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
23+import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
24+
25+import com.datastax.driver.core.*;
26+import com.datastax.driver.core.exceptions.UnavailableException;
27+
28+/**
29+ * Integration test with a custom implementation, to test retry and ignore decisions.
30+ */
31+public class CustomRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
32+ public CustomRetryPolicyIntegrationTest() {
33+ super(new CustomRetryPolicy());
34+ }
35+
36+ @Test(groups = "short")
37+ public void should_ignore_read_timeout() {
38+ simulateError(1, read_request_timeout);
39+
40+ ResultSet rs = query();
41+ assertThat(rs.iterator().hasNext()).isFalse(); // ignore decisions produce empty result sets
42+
43+ assertOnReadTimeoutWasCalled(1);
44+ assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0);
45+ assertQueried(1, 1);
46+ assertQueried(2, 0);
47+ assertQueried(3, 0);
48+ }
49+
50+ @Test(groups = "short")
51+ public void should_retry_once_on_same_host_on_unavailable() {
52+ simulateError(1, unavailable);
53+
54+ try {
55+ query();
56+ fail("expected an UnavailableException");
57+ } catch (UnavailableException e) {/*expected*/}
58+
59+ assertOnUnavailableWasCalled(2);
60+ assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
61+ assertQueried(1, 2);
62+ assertQueried(2, 0);
63+ assertQueried(3, 0);
64+ }
65+
66+ /**
67+ * Ignores read and write timeouts, and retries at most once on unavailable.
68+ */
69+ static class CustomRetryPolicy implements RetryPolicy {
70+
71+ @Override
72+ public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
73+ return RetryDecision.ignore();
74+ }
75+
76+ @Override
77+ public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
78+ return RetryDecision.ignore();
79+ }
80+
81+ @Override
82+ public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
83+ return (nbRetry == 0)
84+ ? RetryDecision.retry(cl)
85+ : RetryDecision.rethrow();
86+ }
87+
88+ @Override
89+ public void init(Cluster cluster) {/*nothing to do*/}
90+
91+ @Override
92+ public void close() {/*nothing to do*/}
93+ }
94+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +1 −1
@@ -36,7 +36,7 @@
3636 @BeforeClass(groups = "short")
3737 public void createCcm() {
3838 // Two-DC cluster with one host in each DC
39- ccm = CCMBridge.create("test", 1, 1);
39+ ccm = CCMBridge.builder("test").withNodes(1, 1).build();
4040 }
4141
4242 @AfterClass(groups = "short")
added driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +145 −0
@@ -0,0 +1,145 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.Cluster;
20+import com.datastax.driver.core.Metrics;
21+import com.datastax.driver.core.Session;
22+import com.datastax.driver.core.exceptions.NoHostAvailableException;
23+import org.testng.annotations.Test;
24+
25+import static org.assertj.core.api.Assertions.assertThat;
26+import static org.assertj.core.api.Assertions.fail;
27+import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
28+import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
29+import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
30+
31+import com.datastax.driver.core.exceptions.ReadTimeoutException;
32+import com.datastax.driver.core.exceptions.UnavailableException;
33+import com.datastax.driver.core.exceptions.WriteTimeoutException;
34+
35+import java.util.Collections;
36+
37+public class DefaultRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
38+ public DefaultRetryPolicyIntegrationTest() {
39+ super(DefaultRetryPolicy.INSTANCE);
40+ }
41+
42+ @Test(groups = "short")
43+ public void should_rethrow_on_read_timeout_with_0_receivedResponses() {
44+ simulateError(1, read_request_timeout);
45+
46+ try {
47+ query();
48+ fail("expected a ReadTimeoutException");
49+ } catch (ReadTimeoutException e) {/*expected*/ }
50+
51+ assertOnReadTimeoutWasCalled(1);
52+ assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0);
53+ assertQueried(1, 1);
54+ assertQueried(2, 0);
55+ assertQueried(3, 0);
56+ }
57+
58+ @Test(groups = "short")
59+ public void should_rethrow_on_write_timeout_with_SIMPLE_write_type() {
60+ simulateError(1, write_request_timeout);
61+
62+ try {
63+ query();
64+ fail("expected a WriteTimeoutException");
65+ } catch (WriteTimeoutException e) {/*expected*/}
66+
67+ assertOnWriteTimeoutWasCalled(1);
68+ assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0);
69+ assertQueried(1, 1);
70+ assertQueried(2, 0);
71+ assertQueried(3, 0);
72+ }
73+
74+ @Test(groups = "short")
75+ public void should_try_next_host_on_first_unavailable() {
76+ simulateError(1, unavailable);
77+ simulateNormalResponse(2);
78+
79+ query();
80+
81+ assertOnUnavailableWasCalled(1);
82+ assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
83+ assertQueried(1, 1);
84+ assertQueried(2, 1);
85+ assertQueried(3, 0);
86+ }
87+
88+ @Test(groups = "short")
89+ public void should_rethrow_on_second_unavailable() {
90+ simulateError(1, unavailable);
91+ simulateError(2, unavailable);
92+
93+ try {
94+ query();
95+ fail("expected an UnavailableException");
96+ } catch (UnavailableException e) {/*expected*/}
97+
98+ assertOnUnavailableWasCalled(2);
99+ assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
100+ assertQueried(1, 1);
101+ assertQueried(2, 1);
102+ assertQueried(3, 0);
103+ }
104+
105+ @Test(groups = "short")
106+ public void should_rethrow_unavailable_in_no_host_available_exception() {
107+ LoadBalancingPolicy firstHostOnlyPolicy =
108+ new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
109+ Collections.singletonList(host1.getSocketAddress()));
110+
111+ Cluster whiteListedCluster = Cluster.builder()
112+ .addContactPoint(CCMBridge.ipOfNode(1))
113+ .withRetryPolicy(retryPolicy)
114+ .withLoadBalancingPolicy(firstHostOnlyPolicy)
115+ .build();
116+
117+ try {
118+ Session whiteListedSession = whiteListedCluster.connect();
119+ // Clear all activity as result of connect.
120+ scassandras.clearAllRecordedActivity();
121+
122+ simulateError(1, unavailable);
123+
124+ try {
125+ query(whiteListedSession);
126+ fail("expected an NoHostAvailableException");
127+ } catch(NoHostAvailableException e) {
128+ // ok
129+ Throwable error = e.getErrors().get(host1.getSocketAddress());
130+ assertThat(error).isNotNull();
131+ assertThat(error).isInstanceOf(UnavailableException.class);
132+ }
133+
134+ assertOnUnavailableWasCalled(1);
135+ // We expect a retry, but it was never sent because there were no more hosts.
136+ Metrics.Errors whiteListErrors = whiteListedCluster.getMetrics().getErrorMetrics();
137+ assertThat(whiteListErrors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
138+ assertQueried(1, 1);
139+ assertQueried(2, 0);
140+ assertQueried(3, 0);
141+ } finally {
142+ whiteListedCluster.close();
143+ }
144+ }
145+}
added driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +109 −0
@@ -0,0 +1,109 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import com.google.common.base.Objects;
19+import org.mockito.Mockito;
20+import org.mockito.verification.VerificationMode;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+import static org.mockito.Matchers.any;
25+import static org.mockito.Matchers.anyInt;
26+import static org.mockito.Mockito.never;
27+import static org.mockito.Mockito.times;
28+
29+import com.datastax.driver.core.*;
30+
31+import static com.datastax.driver.core.ConsistencyLevel.ALL;
32+import static com.datastax.driver.core.ConsistencyLevel.ONE;
33+import static com.datastax.driver.core.ConsistencyLevel.QUORUM;
34+import static com.datastax.driver.core.ConsistencyLevel.TWO;
35+
36+/**
37+ * Note: we can't extend {@link AbstractRetryPolicyIntegrationTest} here, because SCassandra doesn't allow custom values for
38+ * receivedResponses in primed responses.
39+ * If that becomes possible in the future, we could refactor this test.
40+ */
41+public class DowngradingConsistencyRetryPolicyIntegrationTest {
42+
43+ @Test(groups = "long")
44+ public void should_downgrade_if_not_enough_replicas_for_requested_CL() {
45+ CCMBridge ccm = null;
46+ Cluster cluster = null;
47+ try {
48+ // 3-node cluster, keyspace with RF = 3
49+ ccm = CCMBridge.builder(this.getClass().getName()).withNodes(3).build();
50+ cluster = Cluster.builder()
51+ .addContactPoint(CCMBridge.ipOfNode(1))
52+ .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE))
53+ .build();
54+ Session session = cluster.connect();
55+
56+ session.execute("CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}");
57+ session.execute("CREATE TABLE test.foo(k int primary key)");
58+ session.execute("INSERT INTO test.foo(k) VALUES (0)");
59+
60+ // All replicas up: should achieve all levels without downgrading
61+ checkAchievedConsistency(ALL, ALL, session);
62+ checkAchievedConsistency(QUORUM, QUORUM, session);
63+ checkAchievedConsistency(ONE, ONE, session);
64+
65+ ccm.stop(1);
66+ ccm.waitForDown(1);
67+ // Two replicas remaining: should downgrade to 2 when CL > 2
68+ checkAchievedConsistency(ALL, TWO, session);
69+ checkAchievedConsistency(QUORUM, QUORUM, session); // since RF = 3, quorum is still achievable with two nodes
70+ checkAchievedConsistency(TWO, TWO, session);
71+ checkAchievedConsistency(ONE, ONE, session);
72+
73+ ccm.stop(2);
74+ ccm.waitForDown(2);
75+ // One replica remaining: should downgrade to 1 when CL > 1
76+ checkAchievedConsistency(ALL, ONE, session);
77+ checkAchievedConsistency(QUORUM, ONE, session);
78+ checkAchievedConsistency(TWO, ONE, session);
79+ checkAchievedConsistency(ONE, ONE, session);
80+
81+ } finally {
82+ if (cluster != null)
83+ cluster.close();
84+ if (ccm != null)
85+ ccm.remove();
86+ }
87+ }
88+
89+ private void checkAchievedConsistency(ConsistencyLevel requested, ConsistencyLevel expected, Session session) {
90+ RetryPolicy retryPolicy = session.getCluster().getConfiguration().getPolicies().getRetryPolicy();
91+ Mockito.reset(retryPolicy);
92+
93+ Statement s = new SimpleStatement("SELECT * FROM test.foo WHERE k = 0")
94+ .setConsistencyLevel(requested);
95+
96+ ResultSet rs = session.execute(s);
97+
98+ ConsistencyLevel achieved = rs.getExecutionInfo().getAchievedConsistencyLevel();
99+ // ExecutionInfo returns null when the requested level was met.
100+ ConsistencyLevel actual = Objects.firstNonNull(achieved, requested);
101+
102+ assertThat(actual).isEqualTo(expected);
103+
104+ // If the level was downgraded the policy should have been invoked
105+ VerificationMode expectedCallsToPolicy = (expected == requested) ? never() : times(1);
106+ Mockito.verify(retryPolicy, expectedCallsToPolicy).onUnavailable(
107+ any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
108+ }
109+}
added driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +82 −0
@@ -0,0 +1,82 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+import static org.assertj.core.api.Assertions.fail;
22+import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
23+import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
24+import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
25+
26+import com.datastax.driver.core.exceptions.ReadTimeoutException;
27+import com.datastax.driver.core.exceptions.UnavailableException;
28+import com.datastax.driver.core.exceptions.WriteTimeoutException;
29+
30+public class FallthroughRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
31+ public FallthroughRetryPolicyIntegrationTest() {
32+ super(FallthroughRetryPolicy.INSTANCE);
33+ }
34+
35+ @Test(groups = "short")
36+ public void should_rethrow_on_read_timeout_with_0_receivedResponses() {
37+ simulateError(1, read_request_timeout);
38+
39+ try {
40+ query();
41+ fail("expected a ReadTimeoutException");
42+ } catch (ReadTimeoutException e) {/*expected*/ }
43+
44+ assertOnReadTimeoutWasCalled(1);
45+ assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0);
46+ assertQueried(1, 1);
47+ assertQueried(2, 0);
48+ assertQueried(3, 0);
49+ }
50+
51+ @Test(groups = "short")
52+ public void should_rethrow_on_write_timeout_with_SIMPLE_write_type() {
53+ simulateError(1, write_request_timeout);
54+
55+ try {
56+ query();
57+ fail("expected a WriteTimeoutException");
58+ } catch (WriteTimeoutException e) {/*expected*/}
59+
60+ assertOnWriteTimeoutWasCalled(1);
61+ assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0);
62+ assertQueried(1, 1);
63+ assertQueried(2, 0);
64+ assertQueried(3, 0);
65+ }
66+
67+ @Test(groups = "short")
68+ public void should_rethrow_on_unavailable() {
69+ simulateError(1, unavailable);
70+
71+ try {
72+ query();
73+ fail("expected an UnavailableException");
74+ } catch (UnavailableException e) {/*expected*/}
75+
76+ assertOnUnavailableWasCalled(1);
77+ assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(0);
78+ assertQueried(1, 1);
79+ assertQueried(2, 0);
80+ assertQueried(3, 0);
81+ }
82+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java +6 −2
@@ -19,6 +19,7 @@
1919
2020 import static java.util.concurrent.TimeUnit.SECONDS;
2121
22+import com.datastax.driver.core.exceptions.NoHostAvailableException;
2223 import org.testng.annotations.Test;
2324
2425 import static org.assertj.core.api.Assertions.assertThat;
@@ -117,9 +118,12 @@
117118 // when
118119 try {
119120 session.execute(query);
120- fail("Should have thrown UnavailableException");
121- } catch(UnavailableException e) {
121+ fail("Should have thrown NoHostAvailableException");
122+ } catch(NoHostAvailableException e) {
122123 // ok
124+ Throwable error = e.getErrors().get(hostAddress);
125+ assertThat(error).isNotNull();
126+ assertThat(error).isInstanceOf(UnavailableException.class);
123127 }
124128 // then
125129 // wait until trackers have been notified
added driver-core/src/test/java/com/datastax/driver/core/policies/RetryDecisionTest.java +65 −0
@@ -0,0 +1,65 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
23+
24+import static com.datastax.driver.core.ConsistencyLevel.ONE;
25+import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.IGNORE;
26+import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.RETHROW;
27+import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.RETRY;
28+
29+public class RetryDecisionTest {
30+
31+ @Test(groups = "unit")
32+ public void should_expose_decision_properties() throws Throwable {
33+ RetryDecision retryAtOne = RetryDecision.retry(ONE);
34+ assertThat(retryAtOne.getType())
35+ .isEqualTo(RETRY);
36+ assertThat(retryAtOne.getRetryConsistencyLevel())
37+ .isEqualTo(ONE);
38+ assertThat(retryAtOne.isRetryCurrent())
39+ .isTrue();
40+ assertThat(retryAtOne.toString())
41+ .isEqualTo("Retry at ONE on same host.");
42+
43+ RetryDecision tryNextAtOne = RetryDecision.tryNextHost(ONE);
44+ assertThat(tryNextAtOne.getType())
45+ .isEqualTo(RETRY);
46+ assertThat(tryNextAtOne.getRetryConsistencyLevel())
47+ .isEqualTo(ONE);
48+ assertThat(tryNextAtOne.isRetryCurrent())
49+ .isFalse();
50+ assertThat(tryNextAtOne.toString())
51+ .isEqualTo("Retry at ONE on next host.");
52+
53+ RetryDecision rethrow = RetryDecision.rethrow();
54+ assertThat(rethrow.getType())
55+ .isEqualTo(RETHROW);
56+ assertThat(rethrow.toString())
57+ .isEqualTo("Rethrow");
58+
59+ RetryDecision ignore = RetryDecision.ignore();
60+ assertThat(ignore.getType())
61+ .isEqualTo(IGNORE);
62+ assertThat(ignore.toString())
63+ .isEqualTo("Ignore");
64+ }
65+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +1 −3
@@ -16,9 +16,7 @@
1616 package com.datastax.driver.core.policies;
1717
1818 import java.nio.ByteBuffer;
19-import java.util.ArrayList;
2019 import java.util.List;
21-import java.util.Set;
2220
2321 import static org.assertj.core.api.Assertions.assertThat;
2422 import com.google.common.collect.Lists;
@@ -44,7 +42,7 @@
4442 CCMBridge ccm = null;
4543 Cluster cluster = null;
4644 try {
47- ccm = CCMBridge.create("test", 3);
45+ ccm = CCMBridge.builder("test").withNodes(3).build();
4846 cluster = Cluster.builder()
4947 .addContactPoint(CCMBridge.ipOfNode(1))
5048 .withLoadBalancingPolicy(loadBalancingPolicy)
added driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java +109 −0
@@ -0,0 +1,109 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.querybuilder;
17+
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.PreparedStatement;
20+import com.datastax.driver.core.ResultSet;
21+import com.datastax.driver.core.Row;
22+import com.datastax.driver.core.utils.CassandraVersion;
23+import org.testng.annotations.Test;
24+
25+import java.util.Arrays;
26+import java.util.Collection;
27+
28+import static com.datastax.driver.core.Assertions.assertThat;
29+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
30+
31+@CassandraVersion(major=2.1)
32+public class QueryBuilder21ExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
33+
34+ @Override
35+ protected Collection<String> getTableDefinitions() {
36+ // Taken from http://www.datastax.com/dev/blog/cql-in-2-1
37+ return Arrays.asList(
38+ "CREATE TABLE products (id int PRIMARY KEY, description text, price int, categories set<text>, buyers list<int>, features_keys map<text, text>, features_values map<text, text>)",
39+ "CREATE INDEX cat_index ON products(categories)",
40+ "CREATE INDEX buyers_index ON products(buyers)",
41+ "CREATE INDEX feat_index ON products(features_values)",
42+ "CREATE INDEX feat_key_index ON products(KEYS(features_keys))",
43+ "INSERT INTO products(id, description, price, categories, buyers, features_keys, features_values) " +
44+ "VALUES (34134, '120-inch 1080p 3D plasma TV', 9999, {'tv', '3D', 'hdtv'}, [1], {'screen' : '120-inch', 'refresh-rate' : '400hz', 'techno' : 'plasma'}, {'screen' : '120-inch', 'refresh-rate' : '400hz', 'techno' : 'plasma'})",
45+ "INSERT INTO products(id, description, price, categories, buyers, features_keys, features_values) " +
46+ "VALUES (29412, '32-inch LED HDTV (black)', 929, {'tv', 'hdtv'}, [1,2,3], {'screen' : '32-inch', 'techno' : 'LED'}, {'screen' : '32-inch', 'techno' : 'LED'})",
47+ "INSERT INTO products(id, description, price, categories, buyers, features_keys, features_values) " +
48+ "VALUES (38471, '32-inch LCD TV', 110, {'tv', 'used'}, [2,4], {'screen' : '32-inch', 'techno' : 'LCD'}, {'screen' : '32-inch', 'techno' : 'LCD'})"
49+ );
50+ }
51+
52+ @Test(groups="short")
53+ public void should_handle_contains_on_set_with_index() {
54+ PreparedStatement byCategory = session.prepare(select("id", "description", "categories")
55+ .from("products")
56+ .where(contains("categories", bindMarker("category"))));
57+
58+ ResultSet results = session.execute(byCategory.bind().setString("category", "hdtv"));
59+
60+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(2);
61+ for(Row row : results) {
62+ assertThat(row.getSet("categories", String.class)).contains("hdtv");
63+ }
64+ }
65+
66+ @Test(groups="short")
67+ public void should_handle_contains_on_list_with_index() {
68+ PreparedStatement byBuyer = session.prepare(select("id", "description", "buyers")
69+ .from("products")
70+ .where(contains("buyers", bindMarker("buyer"))));
71+
72+ ResultSet results = session.execute(byBuyer.bind().setInt("buyer", 4));
73+
74+ Row row = results.one();
75+ assertThat(row).isNotNull();
76+ assertThat(row.getInt("id")).isEqualTo(38471);
77+ assertThat(row.getList("buyers", Integer.class)).contains(4);
78+ }
79+
80+ @Test(groups="short")
81+ public void should_handle_contains_on_map_with_index() {
82+ PreparedStatement byFeatures = session.prepare(select("id", "description", "features_values")
83+ .from("products")
84+ .where(contains("features_values", bindMarker("feature"))));
85+
86+ ResultSet results = session.execute(byFeatures.bind().setString("feature", "LED"));
87+
88+ Row row = results.one();
89+ assertThat(row).isNotNull();
90+ assertThat(row.getInt("id")).isEqualTo(29412);
91+ assertThat(row.getMap("features_values", String.class, String.class)).containsEntry("techno", "LED");
92+ }
93+
94+
95+ @Test(groups="short")
96+ public void should_handle_contains_key_on_map_with_index() {
97+ PreparedStatement byFeatures = session.prepare(select("id", "description", "features_keys")
98+ .from("products")
99+ .where(containsKey("features_keys", bindMarker("feature"))));
100+
101+ ResultSet results = session.execute(byFeatures.bind().setString("feature", "refresh-rate"));
102+
103+ Row row = results.one();
104+ assertThat(row).isNotNull();
105+ assertThat(row.getInt("id")).isEqualTo(34134);
106+ assertThat(row.getMap("features_keys", String.class, String.class)).containsEntry("refresh-rate", "400hz");
107+ }
108+
109+}
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +86 −4
@@ -19,20 +19,26 @@
1919
2020 import org.testng.annotations.Test;
2121
22+import static org.assertj.core.api.Assertions.assertThat;
23+import static org.assertj.core.data.MapEntry.entry;
24+import static org.testng.Assert.assertEquals;
25+import static org.testng.Assert.assertFalse;
26+import static org.testng.Assert.assertTrue;
27+
2228 import com.datastax.driver.core.*;
2329
2430 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2531
26-import static org.testng.Assert.*;
27-
2832 public class QueryBuilderExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
2933
3034 private static final String TABLE1 = "test1";
3135
3236 @Override
3337 protected Collection<String> getTableDefinitions() {
34- return Arrays.asList(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1),
35- "CREATE TABLE dateTest (t timestamp PRIMARY KEY)");
38+ return Arrays.asList(
39+ String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE1),
40+ "CREATE TABLE dateTest (t timestamp PRIMARY KEY)",
41+ "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)");
3642 }
3743
3844 @Test(groups = "short")
@@ -102,4 +108,80 @@
102108 assertEquals("batchTest2", r2.getString("k"));
103109 assertEquals("val2", r2.getString("t"));
104110 }
111+
112+ @Test(groups = "short")
113+ public void should_delete_list_element() throws Exception {
114+ //given
115+ session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, [1,2,3], null)");
116+ //when
117+ BuiltStatement statement = delete().listElt("a", 1).from("test_coll").where(eq("k", 1));
118+ session.execute(statement);
119+ //then
120+ List<Integer> actual = session.execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
121+ assertThat(actual).containsExactly(1, 3);
122+ }
123+
124+ @Test(groups = "short")
125+ public void should_delete_list_element_with_bind_marker() throws Exception {
126+ //given
127+ session.execute("INSERT INTO test_coll (k, a) VALUES (1, [1,2,3])");
128+ //when
129+ BuiltStatement statement = delete().listElt("a", bindMarker()).from("test_coll").where(eq("k", 1));
130+ PreparedStatement ps = session.prepare(statement);
131+ session.execute(ps.bind(1));
132+ //then
133+ List<Integer> actual = session.execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class);
134+ assertThat(actual).containsExactly(1, 3);
135+ }
136+
137+ @Test(groups = "short")
138+ public void should_delete_set_element() throws Exception {
139+ //given
140+ session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
141+ //when
142+ BuiltStatement statement = delete().setElt("c", "foo").from("test_coll").where(eq("k", 1));
143+ session.execute(statement);
144+ //then
145+ Set<String> actual = session.execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
146+ assertThat(actual).containsOnly("bar", "qix");
147+ }
148+
149+ @Test(groups = "short")
150+ public void should_delete_set_element_with_bind_marker() throws Exception {
151+ //given
152+ session.execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})");
153+ //when
154+ BuiltStatement statement = delete().setElt("c", bindMarker()).from("test_coll").where(eq("k", 1));
155+ PreparedStatement ps = session.prepare(statement);
156+ session.execute(ps.bind("foo"));
157+ //then
158+ Set<String> actual = session.execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class);
159+ assertThat(actual).containsOnly("bar", "qix");
160+ }
161+
162+ @Test(groups = "short")
163+ public void should_delete_map_entry() throws Exception {
164+ //given
165+ session.execute("INSERT INTO test_coll (k, b) VALUES (1, {1:'foo', 2:'bar'})");
166+ //when
167+ BuiltStatement statement = delete().mapElt("b", 1).from("test_coll").where(eq("k", 1));
168+ session.execute(statement);
169+ //then
170+ Map<Integer, String> actual = session.execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
171+ assertThat(actual).containsExactly(entry(2, "bar"));
172+ }
173+
174+ @Test(groups = "short")
175+ public void should_delete_map_entry_with_bind_marker() throws Exception {
176+ //given
177+ session.execute("INSERT INTO test_coll (k, a, b) VALUES (1, null, {1:'foo', 2:'bar'})");
178+ //when
179+ BuiltStatement statement = delete().mapElt("b", bindMarker()).from("test_coll").where(eq("k", 1));
180+ PreparedStatement ps = session.prepare(statement);
181+ session.execute(ps.bind().setInt(0, 1));
182+ //then
183+ Map<Integer, String> actual = session.execute("SELECT b FROM test_coll WHERE k = 1").one().getMap("b", Integer.class, String.class);
184+ assertThat(actual).containsExactly(entry(2, "bar"));
185+ }
186+
105187 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +157 −50
@@ -25,10 +25,12 @@
2525 import org.testng.annotations.Test;
2626
2727 import static org.assertj.core.api.Assertions.assertThat;
28-import static org.testng.Assert.*;
28+import static org.testng.Assert.assertEquals;
29+import static org.testng.Assert.assertTrue;
30+import static org.testng.Assert.fail;
2931
3032 import com.datastax.driver.core.*;
31-import com.datastax.driver.core.querybuilder.Delete.Where;
33+import com.datastax.driver.core.exceptions.InvalidQueryException;
3234 import com.datastax.driver.core.utils.Bytes;
3335 import com.datastax.driver.core.utils.CassandraVersion;
3436
@@ -53,10 +55,10 @@
5355
5456 query = "SELECT a,b,\"C\" FROM foo WHERE a IN ('127.0.0.1','127.0.0.3') AND \"C\"='foo' ORDER BY a ASC,b DESC LIMIT 42;";
5557 select = select("a", "b", quote("C")).from("foo")
56- .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3")))
57- .and(eq(quote("C"), "foo"))
58- .orderBy(asc("a"), desc("b"))
59- .limit(42);
58+ .where(in("a", InetAddress.getByName("127.0.0.1"), InetAddress.getByName("127.0.0.3")))
59+ .and(eq(quote("C"), "foo"))
60+ .orderBy(asc("a"), desc("b"))
61+ .limit(42);
6062 assertEquals(select.toString(), query);
6163
6264 query = "SELECT writetime(a),ttl(a) FROM foo ALLOW FILTERING;";
@@ -83,6 +85,14 @@
8385 select = select("a").from("foo").where(in("k", bindMarker()));
8486 assertEquals(select.toString(), query);
8587
88+ query = "SELECT DISTINCT a FROM foo WHERE k=1;";
89+ select = select("a").distinct().from("foo").where(eq("k", 1));
90+ assertEquals(select.toString(), query);
91+
92+ query = "SELECT DISTINCT a,b FROM foo WHERE k=1;";
93+ select = select("a", "b").distinct().from("foo").where(eq("k", 1));
94+ assertEquals(select.toString(), query);
95+
8696 query = "SELECT count(*) FROM foo;";
8797 select = select().countAll().from("foo");
8898 assertEquals(select.toString(), query);
@@ -113,42 +123,53 @@
113123
114124 Date date = new Date();
115125 date.setTime(1234325);
116- query = "SELECT * FROM foo where d=1234325";
126+ query = "SELECT * FROM foo WHERE d=1234325;";
117127 select = select().all().from("foo").where(eq("d", date));
128+ assertEquals(select.toString(), query);
118129
119- query = "SELECT * FROM foo where b=0xCAFEBABE";
130+ query = "SELECT * FROM foo WHERE b=0xcafebabe;";
120131 select = select().all().from("foo").where(eq("b", Bytes.fromHexString("0xCAFEBABE")));
132+ assertEquals(select.toString(), query);
133+
134+ query = "SELECT * FROM foo WHERE e CONTAINS 'text';";
135+ select = select().from("foo").where(contains("e", "text"));
136+ assertEquals(select.toString(), query);
137+
138+ query = "SELECT * FROM foo WHERE e CONTAINS KEY 'key1';";
139+ select = select().from("foo").where(containsKey("e", "key1"));
140+ assertEquals(select.toString(), query);
141+
121142
122143 try {
123- select = select().countAll().from("foo").orderBy(asc("a"), desc("b")).orderBy(asc("a"), desc("b"));
144+ select().countAll().from("foo").orderBy(asc("a"), desc("b")).orderBy(asc("a"), desc("b"));
124145 fail();
125146 } catch (IllegalStateException e) {
126147 assertEquals(e.getMessage(), "An ORDER BY clause has already been provided");
127148 }
128149
129150 try {
130- select = select().column("a").all().from("foo");
151+ select().column("a").all().from("foo");
131152 fail();
132153 } catch (IllegalStateException e) {
133154 assertEquals(e.getMessage(), "Some columns ([a]) have already been selected.");
134155 }
135156
136157 try {
137- select = select().column("a").countAll().from("foo");
158+ select().column("a").countAll().from("foo");
138159 fail();
139160 } catch (IllegalStateException e) {
140161 assertEquals(e.getMessage(), "Some columns ([a]) have already been selected.");
141162 }
142163
143164 try {
144- select = select().all().from("foo").limit(-42);
165+ select().all().from("foo").limit(-42);
145166 fail();
146167 } catch (IllegalArgumentException e) {
147168 assertEquals(e.getMessage(), "Invalid LIMIT value, must be strictly positive");
148169 }
149170
150171 try {
151- select = select().all().from("foo").limit(42).limit(42);
172+ select().all().from("foo").limit(42).limit(42);
152173 fail();
153174 } catch (IllegalStateException e) {
154175 assertEquals(e.getMessage(), "A LIMIT value has already been provided");
@@ -164,48 +185,67 @@
164185
165186 query = "INSERT INTO foo(a,b,\"C\",d) VALUES (123,'127.0.0.1','foo''bar',{'x':3,'y':2}) USING TIMESTAMP 42 AND TTL 24;";
166187 insert = insertInto("foo")
167- .value("a", 123)
168- .value("b", InetAddress.getByName("127.0.0.1"))
169- .value(quote("C"), "foo'bar")
170- .value("d", new TreeMap<String, Integer>(){{ put("x", 3); put("y", 2); }})
171- .using(timestamp(42)).and(ttl(24));
188+ .value("a", 123)
189+ .value("b", InetAddress.getByName("127.0.0.1"))
190+ .value(quote("C"), "foo'bar")
191+ .value("d", new TreeMap<String, Integer>() {{
192+ put("x", 3);
193+ put("y", 2);
194+ }})
195+ .using(timestamp(42)).and(ttl(24));
172196 assertEquals(insert.toString(), query);
173197
174198 query = "INSERT INTO foo(a,b) VALUES (2,null);";
175199 insert = insertInto("foo")
176- .value("a", 2)
177- .value("b", null);
200+ .value("a", 2)
201+ .value("b", null);
178202 assertEquals(insert.toString(), query);
179203
180204 query = "INSERT INTO foo(a,b) VALUES ({2,3,4},3.4) USING TTL 24 AND TIMESTAMP 42;";
181- insert = insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<Integer>(){{ add(2); add(3); add(4); }}, 3.4 }).using(ttl(24)).and(timestamp(42));
205+ insert = insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
206+ add(2);
207+ add(3);
208+ add(4);
209+ }}, 3.4 }).using(ttl(24)).and(timestamp(42));
182210 assertEquals(insert.toString(), query);
183211
184212 query = "INSERT INTO foo.bar(a,b) VALUES ({2,3,4},3.4) USING TTL ? AND TIMESTAMP ?;";
185213 insert = insertInto("foo", "bar")
186- .values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<Integer>(){{ add(2); add(3); add(4); }}, 3.4 })
187- .using(ttl(bindMarker()))
188- .and(timestamp(bindMarker()));
214+ .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
215+ add(2);
216+ add(3);
217+ add(4);
218+ }}, 3.4 })
219+ .using(ttl(bindMarker()))
220+ .and(timestamp(bindMarker()));
189221 assertEquals(insert.toString(), query);
190222
191223 // commutative result of TIMESTAMP
192224 query = "INSERT INTO foo.bar(a,b,c) VALUES ({2,3,4},3.4,123) USING TIMESTAMP 42;";
193225 insert = insertInto("foo", "bar")
194- .using(timestamp(42))
195- .values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<Integer>(){{ add(2); add(3); add(4); }}, 3.4 })
196- .value("c", 123);
226+ .using(timestamp(42))
227+ .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
228+ add(2);
229+ add(3);
230+ add(4);
231+ }}, 3.4 })
232+ .value("c", 123);
197233 assertEquals(insert.toString(), query);
198234
199235 // commutative result of value() and values()
200236 query = "INSERT INTO foo(c,a,b) VALUES (123,{2,3,4},3.4) USING TIMESTAMP 42;";
201237 insert = insertInto("foo")
202- .using(timestamp(42))
203- .value("c", 123)
204- .values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<Integer>(){{ add(2); add(3); add(4); }}, 3.4 });
238+ .using(timestamp(42))
239+ .value("c", 123)
240+ .values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
241+ add(2);
242+ add(3);
243+ add(4);
244+ }}, 3.4 });
205245 assertEquals(insert.toString(), query);
206246
207247 try {
208- insert = insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ 1, 2, 3 });
248+ insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ 1, 2, 3 });
209249 fail();
210250 } catch (IllegalArgumentException e) {
211251 assertEquals(e.getMessage(), "Got 2 names but 3 values");
@@ -247,20 +287,31 @@
247287 assertEquals(update.toString(), query);
248288
249289 query = "UPDATE foo SET b=b-[1,2,3],c=c+{1},d=d+{2,3,4};";
250- update = update("foo").with(discardAll("b", Arrays.asList(1, 2, 3))).and(add("c", 1)).and(addAll("d", new TreeSet<Integer>(){{ add(2); add(3); add(4); }}));
290+ update = update("foo").with(discardAll("b", Arrays.asList(1, 2, 3))).and(add("c", 1)).and(addAll("d", new TreeSet<Integer>() {{
291+ add(2);
292+ add(3);
293+ add(4);
294+ }}));
251295 assertEquals(update.toString(), query);
252296
253297 query = "UPDATE foo SET b=b-{2,3,4},c['k']='v',d=d+{'x':3,'y':2};";
254- update = update("foo").with(removeAll("b", new TreeSet<Integer>(){{ add(2); add(3); add(4); }}))
255- .and(put("c", "k", "v"))
256- .and(putAll("d", new TreeMap<String, Integer>(){{ put("x", 3); put("y", 2); }}));
298+ update = update("foo").with(removeAll("b", new TreeSet<Integer>() {{
299+ add(2);
300+ add(3);
301+ add(4);
302+ }}))
303+ .and(put("c", "k", "v"))
304+ .and(putAll("d", new TreeMap<String, Integer>() {{
305+ put("x", 3);
306+ put("y", 2);
307+ }}));
257308 assertEquals(update.toString(), query);
258309
259310 query = "UPDATE foo USING TTL 400;";
260311 update = update("foo").using(ttl(400));
261312 assertEquals(update.toString(), query);
262313
263- query = "UPDATE foo SET a="+new BigDecimal(3.2)+",b=42 WHERE k=2;";
314+ query = "UPDATE foo SET a=" + new BigDecimal(3.2) + ",b=42 WHERE k=2;";
264315 update = update("foo").with(set("a", new BigDecimal(3.2))).and(set("b", new BigInteger("42"))).where(eq("k", 2));
265316 assertEquals(update.toString(), query);
266317
@@ -277,7 +328,7 @@
277328 assertEquals(update.toString(), query);
278329
279330 try {
280- update = update("foo").using(ttl(-400));
331+ update("foo").using(ttl(-400));
281332 fail();
282333 } catch (IllegalArgumentException e) {
283334 assertEquals(e.getMessage(), "Invalid ttl, must be positive");
@@ -303,6 +354,10 @@
303354 delete = delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1));
304355 assertEquals(delete.toString(), query);
305356
357+ query = "DELETE a[?],b[?],c FROM foo WHERE k=1;";
358+ delete = delete().listElt("a", bindMarker()).mapElt("b", bindMarker()).column("c").from("foo").where(eq("k", 1));
359+ assertEquals(delete.toString(), query);
360+
306361 // Invalid CQL, testing edge case
307362 query = "DELETE a,b,c FROM foo;";
308363 delete = delete("a", "b", "c").from("foo");
@@ -323,14 +378,14 @@
323378 assertEquals(delete.toString(), query);
324379
325380 try {
326- delete = delete().column("a").all().from("foo");
381+ delete().column("a").all().from("foo");
327382 fail();
328383 } catch (IllegalStateException e) {
329384 assertEquals(e.getMessage(), "Some columns ([a]) have already been selected.");
330385 }
331386
332387 try {
333- delete = delete().from("foo").using(timestamp(-1240003134L));
388+ delete().from("foo").using(timestamp(-1240003134L));
334389 fail();
335390 } catch (IllegalArgumentException e) {
336391 assertEquals(e.getMessage(), "Invalid timestamp, must be positive");
@@ -361,7 +416,11 @@
361416 query += "DELETE a[3],b['foo'],c FROM foo WHERE k=1;";
362417 query += "APPLY BATCH;";
363418 batch = batch()
364- .add(insertInto("foo").values(new String[]{ "a", "b"}, new Object[]{ new TreeSet<Integer>(){{ add(2); add(3); add(4); }}, 3.4 }))
419+ .add(insertInto("foo").values(new String[]{ "a", "b" }, new Object[]{ new TreeSet<Integer>() {{
420+ add(2);
421+ add(3);
422+ add(4);
423+ }}, 3.4 }))
365424 .add(update("foo").with(setIdx("a", 2, "foo")).and(prependAll("b", Arrays.asList(3, 2, 1))).and(remove("c", "a")).where(eq("k", 2)))
366425 .add(delete().listElt("a", 3).mapElt("b", "foo").column("c").from("foo").where(eq("k", 1)))
367426 .using(timestamp(42));
@@ -448,12 +507,9 @@
448507 assertEquals(batch.toString(), query);
449508 }
450509
451- @Test(groups = "unit", expectedExceptions={IllegalArgumentException.class})
510+ @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
452511 public void batchMixedCounterTest() throws Exception {
453- String query;
454- Statement batch;
455-
456- batch = batch()
512+ batch()
457513 .add(update("foo").with(incr("a", 1)))
458514 .add(update("foo").with(set("b", 2)))
459515 .add(update("foo").with(incr("c", 3)))
@@ -467,8 +523,8 @@
467523
468524 query = "INSERT INTO test(k,c) VALUES (0,?);";
469525 insert = insertInto("test")
470- .value("k", 0)
471- .value("c", bindMarker());
526+ .value("k", 0)
527+ .value("c", bindMarker());
472528 assertEquals(insert.toString(), query);
473529 }
474530
@@ -495,7 +551,6 @@
495551 assertEquals(select.toString(), query);
496552 }
497553
498-
499554 @Test(groups = "unit")
500555 public void selectInjectionTests() throws Exception {
501556
@@ -627,7 +682,7 @@
627682
628683 query = "DELETE a,b FROM foo WHERE a IN ('b','c''); --comment');";
629684 delete = delete("a", "b").from("foo")
630- .where(in("a", "b", "c'); --comment"));
685+ .where(in("a", "b", "c'); --comment"));
631686 assertEquals(delete.toString(), query);
632687
633688 query = "DELETE FROM foo WHERE \"k=1 OR k\">42;";
@@ -656,6 +711,7 @@
656711 public void rejectUnknownValueTest() throws Exception {
657712
658713 try {
714+ //noinspection ResultOfMethodCallIgnored
659715 update("foo").with(set("a", new byte[13])).where(eq("k", 2)).toString();
660716 fail("Byte arrays should not be valid, ByteBuffer should be used instead");
661717 } catch (IllegalArgumentException e) {
@@ -701,7 +757,7 @@
701757
702758 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)>=('a',2) AND (c1,c2)<('b',0);";
703759 select = select().all().from("foo").where(eq("k", 4)).and(gte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)))
704- .and(lt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("b", 0)));
760+ .and(lt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("b", 0)));
705761 assertEquals(select.toString(), query);
706762
707763 query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)<=('a',2);";
@@ -767,4 +823,55 @@
767823 statement = update("foo").with(prependAll("l", list)).where(eq("k", 1));
768824 assertThat(statement.toString()).isEqualTo(query);
769825 }
826+
827+ @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
828+ public void should_not_allow_bind_marker_for_add() {
829+ // This generates the query "UPDATE foo SET s = s + {?} WHERE k = 1", which is invalid in Cassandra
830+ update("foo").with(add("s", bindMarker())).where(eq("k", 1));
831+ }
832+
833+ @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
834+ public void should_now_allow_bind_marker_for_prepend() {
835+ update("foo").with(prepend("l", bindMarker())).where(eq("k", 1));
836+ }
837+
838+ @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
839+ public void should_not_allow_bind_marker_for_append() {
840+ update("foo").with(append("l", bindMarker())).where(eq("k", 1));
841+ }
842+
843+ @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
844+ public void should_not_allow_bind_marker_for_remove() {
845+ update("foo").with(remove("s", bindMarker())).where(eq("k", 1));
846+ }
847+
848+ @Test(groups = "unit", expectedExceptions = InvalidQueryException.class)
849+ public void should_not_allow_bind_marker_for_discard() {
850+ update("foo").with(discard("l", bindMarker())).where(eq("k", 1));
851+ }
852+
853+ @Test(groups = "unit")
854+ public void should_quote_complex_column_names() {
855+ // A column name can be anything as long as it's quoted, so "foo.bar" is a valid name
856+ String query = "SELECT * FROM foo WHERE \"foo.bar\"=1;";
857+ Statement statement = select().from("foo").where(eq(quote("foo.bar"), 1));
858+
859+ assertThat(statement.toString()).isEqualTo(query);
860+ }
861+
862+ @Test(groups = "unit")
863+ public void should_quote_column_names_with_escaped_quotes() {
864+ // A column name can include quotes as long as it is escaped with another set of quotes, so "foo""bar" is a valid name.
865+ String query = "SELECT * FROM foo WHERE \"foo \"\" bar\"=1;";
866+ Statement statement = select().from("foo").where(eq(quote("foo \"\" bar"), 1));
867+
868+ assertThat(statement.toString()).isEqualTo(query);
869+ }
870+
871+ @Test(groups = "unit")
872+ public void should_not_serialize_raw_query_values() {
873+ RegularStatement select = select().from("test").where(gt("i", raw("1")));
874+ assertThat(select.getQueryString()).doesNotContain("?");
875+ assertThat(select.getValues(ProtocolVersion.V3)).isNull();
876+ }
770877 }
modified driver-dist/src/assembly/binary-tarball.xml +1 −0
@@ -37,6 +37,7 @@
3737 <outputDirectory>lib</outputDirectory>
3838 <excludes>
3939 <exclude>com.datastax.cassandra:*</exclude>
40+ <exclude>io.netty:netty-transport-native-epoll:*</exclude>
4041 </excludes>
4142 </dependencySet>
4243 </dependencySets>
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java +1 −1
@@ -33,7 +33,7 @@
3333 private CCMBridge ccm;
3434
3535 @Override public void onStart(ITestContext context) {
36- ccm = CCMBridge.create("test", 1);
36+ ccm = CCMBridge.builder("test").withNodes(1).build();
3737 }
3838
3939 @Override public void onFinish(ITestContext context) {
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Stress.java +1 −1
@@ -210,7 +210,7 @@
210210 : concurrency / maxRequestsPerConnection + 1;
211211
212212 PoolingOptions pools = new PoolingOptions();
213- pools.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, concurrency);
213+ pools.setNewConnectionThreshold(HostDistance.LOCAL, concurrency);
214214 pools.setCoreConnectionsPerHost(HostDistance.LOCAL, maxConnections);
215215 pools.setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
216216 pools.setCoreConnectionsPerHost(HostDistance.REMOTE, maxConnections);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationChecks.java +8 −0
@@ -75,6 +75,7 @@
7575 field.getDeclaringClass().getName(), e.getMessage()));
7676 }
7777 }
78+ checkValidComputed(field);
7879 }
7980
8081 // Returns the offending annotation if there is one
@@ -100,6 +101,13 @@
100101 checkFrozenTypes(javaType, declaredFrozenType);
101102 }
102103
104+ static void checkValidComputed(Field field) {
105+ Computed computed = field.getAnnotation(Computed.class);
106+ if (computed != null && computed.value().isEmpty()){
107+ throw new IllegalArgumentException(String.format("Field %s: attribute 'value' of annotation @Computed is mandatory for computed fields", field.getName()));
108+ }
109+ }
110+
103111 // Builds a DeclaredFrozenType hierarchy based on the @Frozen* annotations on a field.
104112 private static DeclaredFrozenType getDeclaredFrozenType(Field field) {
105113 Frozen frozen = field.getAnnotation(Frozen.class);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +38 −11
@@ -22,6 +22,7 @@
2222 import java.util.Collections;
2323 import java.util.Comparator;
2424 import java.util.List;
25+import java.util.concurrent.atomic.AtomicInteger;
2526
2627 import com.google.common.base.Strings;
2728
@@ -73,10 +74,13 @@
7374 for (Field field : entityClass.getDeclaredFields()) {
7475 if(field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
7576 continue;
76-
77+
78+ if (mappingManager.isCassandraV1 && field.getAnnotation(Computed.class) != null)
79+ throw new UnsupportedOperationException("Computed fields are not supported with native protocol v1");
80+
7781 AnnotationChecks.validateAnnotations(field, "entity",
7882 Column.class, ClusteringColumn.class, Enumerated.class, Frozen.class, FrozenKey.class,
79- FrozenValue.class, PartitionKey.class, Transient.class);
83+ FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
8084
8185 if (field.getAnnotation(Transient.class) != null)
8286 continue;
@@ -94,15 +98,17 @@
9498 }
9599 }
96100
101+ AtomicInteger columnCounter = mappingManager.isCassandraV1 ? null : new AtomicInteger(0);
102+
97103 Collections.sort(pks, fieldComparator);
98104 Collections.sort(ccs, fieldComparator);
99105
100106 validateOrder(pks, "@PartitionKey");
101107 validateOrder(ccs, "@ClusteringColumn");
102108
103- mapper.addColumns(convert(pks, factory, mapper.entityClass, mappingManager),
104- convert(ccs, factory, mapper.entityClass, mappingManager),
105- convert(rgs, factory, mapper.entityClass, mappingManager));
109+ mapper.addColumns(convert(pks, factory, mapper.entityClass, mappingManager, columnCounter),
110+ convert(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
111+ convert(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
106112 return mapper;
107113 }
108114
@@ -148,16 +154,16 @@
148154 }
149155 }
150156
151- mapper.addColumns(convert(columns, factory, udtClass, mappingManager));
157+ mapper.addColumns(convert(columns, factory, udtClass, mappingManager, null));
152158 return mapper;
153159 }
154160
155- private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager) {
161+ private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
156162 List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
157163 for (int i = 0; i < fields.size(); i++) {
158164 Field field = fields.get(i);
159165 int pos = position(field);
160- mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager));
166+ mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter));
161167 }
162168 return mappers;
163169 }
@@ -186,12 +192,20 @@
186192 public static ColumnMapper.Kind kind(Field field) {
187193 PartitionKey pk = field.getAnnotation(PartitionKey.class);
188194 ClusteringColumn cc = field.getAnnotation(ClusteringColumn.class);
195+ Computed comp = field.getAnnotation(Computed.class);
189196 if (pk != null && cc != null)
190197 throw new IllegalArgumentException("Field " + field.getName() + " cannot have both the @PartitionKey and @ClusteringColumn annotations");
191198
192- return pk != null
193- ? ColumnMapper.Kind.PARTITION_KEY
194- : (cc != null ? ColumnMapper.Kind.CLUSTERING_COLUMN : ColumnMapper.Kind.REGULAR);
199+ if (pk != null) {
200+ return ColumnMapper.Kind.PARTITION_KEY;
201+ }
202+ if (cc != null) {
203+ return ColumnMapper.Kind.CLUSTERING_COLUMN;
204+ }
205+ if (comp != null) {
206+ return ColumnMapper.Kind.COMPUTED;
207+ }
208+ return ColumnMapper.Kind.REGULAR;
195209 }
196210
197211 public static EnumType enumType(Field field) {
@@ -205,7 +219,11 @@
205219
206220 public static String columnName(Field field) {
207221 Column column = field.getAnnotation(Column.class);
222+ Computed computedField = field.getAnnotation(Computed.class);
208223 if (column != null && !column.name().isEmpty()) {
224+ if (computedField != null){
225+ throw new IllegalArgumentException("Cannot use @Column and @Computed on the same field");
226+ }
209227 return column.caseSensitive() ? column.name() : column.name().toLowerCase();
210228 }
211229
@@ -214,9 +232,18 @@
214232 return udtField.caseSensitive() ? udtField.name() : udtField.name().toLowerCase();
215233 }
216234
235+ if (computedField != null) {
236+ return computedField.value();
237+ }
238+
217239 return field.getName().toLowerCase();
218240 }
219241
242+ public static String newAlias(Field field, int columnNumber) {
243+ return "col" + columnNumber;
244+
245+ }
246+
220247 public static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) {
221248 if (!accClass.isInterface())
222249 throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +20 −11
@@ -16,15 +16,18 @@
1616 package com.datastax.driver.mapping;
1717
1818 import java.lang.reflect.Field;
19+import java.util.concurrent.atomic.AtomicInteger;
1920
2021 import com.datastax.driver.core.DataType;
22+
2123 import static com.datastax.driver.core.querybuilder.QueryBuilder.quote;
2224
2325 abstract class ColumnMapper<T> {
2426
25- public enum Kind { PARTITION_KEY, CLUSTERING_COLUMN, REGULAR };
27+ public enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED};
2628
2729 private final String columnName;
30+ private final String alias;
2831 protected final String fieldName;
2932 protected final Class<?> javaType;
3033 // Note: dataType is not guaranteed to be exact. Typically, it will be uuid even if the underlying
@@ -34,24 +37,30 @@
3437 protected final Kind kind;
3538 protected final int position;
3639
37- protected ColumnMapper(Field field, DataType dataType, int position) {
38- this(AnnotationParser.columnName(field), field.getName(), field.getType(), dataType, AnnotationParser.kind(field), position);
39- }
40-
41- private ColumnMapper(String columnName, String fieldName, Class<?> javaType, DataType dataType, Kind kind, int position) {
42- this.columnName = columnName;
43- this.fieldName = fieldName;
44- this.javaType = javaType;
40+ protected ColumnMapper(Field field, DataType dataType, int position, AtomicInteger columnCounter) {
41+ this.columnName = AnnotationParser.columnName(field);
42+ this.alias = (columnCounter != null)
43+ ? AnnotationParser.newAlias(field, columnCounter.incrementAndGet())
44+ : null;
45+ this.fieldName = field.getName();
46+ this.javaType = field.getType();
4547 this.dataType = dataType;
46- this.kind = kind;
48+ this.kind = AnnotationParser.kind(field);
4749 this.position = position;
4850 }
4951
5052 public abstract Object getValue(T entity);
53+
5154 public abstract void setValue(T entity, Object value);
5255
5356 public String getColumnName() {
54- return quote(columnName);
57+ return kind == Kind.COMPUTED
58+ ? columnName
59+ : quote(columnName);
60+ }
61+
62+ public String getAlias() {
63+ return alias;
5564 }
5665
5766 public DataType getDataType() {
modified driver-mapping/src/main/java/com/datastax/driver/mapping/EntityMapper.java +2 −1
@@ -17,6 +17,7 @@
1717
1818 import java.lang.reflect.Field;
1919 import java.util.*;
20+import java.util.concurrent.atomic.AtomicInteger;
2021
2122 import com.datastax.driver.core.ConsistencyLevel;
2223 import static com.datastax.driver.core.querybuilder.QueryBuilder.quote;
@@ -83,6 +84,6 @@
8384
8485 interface Factory {
8586 public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency);
86- public <T> ColumnMapper<T> createColumnMapper(Class<T> componentClass, Field field, int position, MappingManager mappingManager);
87+ public <T> ColumnMapper<T> createColumnMapper(Class<T> componentClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter);
8788 }
8889 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +773 −113
@@ -15,19 +15,28 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.Collections;
19-import java.util.HashMap;
20-import java.util.Map;
18+import java.util.*;
2119
2220 import com.google.common.base.Function;
2321 import com.google.common.base.Functions;
22+import com.google.common.base.Objects;
23+import com.google.common.base.Preconditions;
2424 import com.google.common.util.concurrent.Futures;
2525 import com.google.common.util.concurrent.ListenableFuture;
26-
2726 import org.slf4j.Logger;
2827 import org.slf4j.LoggerFactory;
2928
29+import static com.google.common.base.Preconditions.checkArgument;
30+
3031 import com.datastax.driver.core.*;
32+import com.datastax.driver.core.querybuilder.Delete;
33+import com.datastax.driver.core.querybuilder.Insert;
34+import com.datastax.driver.core.querybuilder.QueryBuilder;
35+import com.datastax.driver.mapping.Mapper.Option.SaveNullFields;
36+import com.datastax.driver.mapping.annotations.Accessor;
37+import com.datastax.driver.mapping.annotations.Computed;
38+
39+import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS;
3140
3241 /**
3342 * An object handling the mapping of a particular class.
@@ -46,12 +55,19 @@
4655 final TableMetadata tableMetadata;
4756
4857 // Cache prepared statements for each type of query we use.
49- private volatile Map<QueryType, PreparedStatement> preparedQueries = Collections.<QueryType, PreparedStatement>emptyMap();
58+ private volatile Map<MapperQueryKey, PreparedStatement> preparedQueries = Collections.emptyMap();
59+
60+ private static final Function<Object, Void> NOOP = Functions.constant(null);
61+
62+ private volatile EnumMap<Option.Type, Option> defaultSaveOptions;
63+ private volatile EnumMap<Option.Type, Option> defaultGetOptions;
64+ private volatile EnumMap<Option.Type, Option> defaultDeleteOptions;
5065
51- private static final Function<Object, Void> NOOP = Functions.<Void>constant(null);
66+ private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class);
5267
5368 final Function<ResultSet, T> mapOneFunction;
54- final Function<ResultSet, Result<T>> mapAllFunction;
69+ final Function<ResultSet, T> mapOneFunctionWithoutAliases;
70+ final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases;
5571
5672 Mapper(MappingManager manager, Class<T> klass, EntityMapper<T> mapper) {
5773 this.manager = manager;
@@ -63,32 +79,44 @@
6379
6480 this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
6581 this.mapOneFunction = new Function<ResultSet, T>() {
82+ public T apply(ResultSet rs) {
83+ return Mapper.this.mapAliased(rs).one();
84+ }
85+ };
86+ this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() {
6687 public T apply(ResultSet rs) {
6788 return Mapper.this.map(rs).one();
6889 }
6990 };
70- this.mapAllFunction = new Function<ResultSet, Result<T>>() {
91+ this.mapAllFunctionWithoutAliases = new Function<ResultSet, Result<T>>() {
7192 public Result<T> apply(ResultSet rs) {
7293 return Mapper.this.map(rs);
7394 }
7495 };
96+
97+ this.defaultSaveOptions = NO_OPTIONS;
98+ this.defaultGetOptions = NO_OPTIONS;
99+ this.defaultDeleteOptions = NO_OPTIONS;
75100 }
76101
77102 Session session() {
78103 return manager.getSession();
79104 }
80105
81- PreparedStatement getPreparedQuery(QueryType type) {
82- PreparedStatement stmt = preparedQueries.get(type);
106+ PreparedStatement getPreparedQuery(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) {
107+
108+ MapperQueryKey pqk = new MapperQueryKey(type, columns, options);
109+
110+ PreparedStatement stmt = preparedQueries.get(pqk);
83111 if (stmt == null) {
84112 synchronized (preparedQueries) {
85- stmt = preparedQueries.get(type);
113+ stmt = preparedQueries.get(pqk);
86114 if (stmt == null) {
87- String query = type.makePreparedQueryString(tableMetadata, mapper);
88- logger.debug("Preparing query {}", query);
89- stmt = session().prepare(query);
90- Map<QueryType, PreparedStatement> newQueries = new HashMap<QueryType, PreparedStatement>(preparedQueries);
91- newQueries.put(type, stmt);
115+ String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values());
116+ logger.debug("Preparing query {}", queryString);
117+ stmt = session().prepare(queryString);
118+ Map<MapperQueryKey, PreparedStatement> newQueries = new HashMap<MapperQueryKey, PreparedStatement>(preparedQueries);
119+ newQueries.put(pqk, stmt);
92120 preparedQueries = newQueries;
93121 }
94122 }
@@ -96,6 +124,19 @@
96124 return stmt;
97125 }
98126
127+ PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) {
128+ return getPreparedQuery(type, Collections.<ColumnMapper<?>>emptySet(), options);
129+ }
130+
131+ /**
132+ * The {@code TableMetadata} for this mapper.
133+ *
134+ * @return the {@code TableMetadata} for this mapper or {@code null} if keyspace is not set.
135+ */
136+ public TableMetadata getTableMetadata() {
137+ return tableMetadata;
138+ }
139+
99140 /**
100141 * The {@code MappingManager} managing this mapper.
101142 *
@@ -118,20 +159,68 @@
118159 * @return a query that saves {@code entity} (based on it's defined mapping).
119160 */
120161 public Statement saveQuery(T entity) {
121- PreparedStatement ps = getPreparedQuery(QueryType.SAVE);
162+ return saveQuery(entity, this.defaultSaveOptions);
163+ }
164+
165+ /**
166+ * Creates a query that can be used to save the provided entity.
167+ * <p>
168+ * This method is useful if you want to setup a number of options (tracing,
169+ * conistency level, ...) of the returned statement before executing it manually
170+ * or need access to the {@code ResultSet} object after execution (to get the
171+ * trace, the execution info, ...), but in other cases, calling {@link #save}
172+ * or {@link #saveAsync} is shorter.
173+ * This method allows you to provide a suite of {@link Option} to include in
174+ * the SAVE query. Options currently supported for SAVE are :
175+ * <ul>
176+ * <li>Timestamp</li>
177+ * <li>Time-to-live (ttl)</li>
178+ * <li>Consistency level</li>
179+ * <li>Tracing</li>
180+ * </ul>
181+ *
182+ * @param entity the entity to save.
183+ * @return a query that saves {@code entity} (based on it's defined mapping).
184+ */
185+ public Statement saveQuery(T entity, Option... options) {
186+ return saveQuery(entity, toMapWithDefaults(options, this.defaultSaveOptions));
187+ }
188+
189+ private Statement saveQuery(T entity, EnumMap<Option.Type, Option> options) {
190+ Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>();
191+ boolean saveNullFields = shouldSaveNullFields(options);
122192
123- BoundStatement bs = ps.bind();
124- int i = 0;
125193 for (ColumnMapper<T> cm : mapper.allColumns()) {
126194 Object value = cm.getValue(entity);
127- bs.setBytesUnsafe(i++, value == null ? null : cm.getDataType().serialize(value, protocolVersion));
195+ if (cm.kind != ColumnMapper.Kind.COMPUTED && (saveNullFields || value != null)) {
196+ values.put(cm, value);
197+ }
198+ }
199+
200+ BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind();
201+ int i = 0;
202+ for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) {
203+ DataType type = entry.getKey().getDataType();
204+ Object value = entry.getValue();
205+ bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion));
128206 }
129207
130208 if (mapper.writeConsistency != null)
131209 bs.setConsistencyLevel(mapper.writeConsistency);
210+
211+ for (Option opt : options.values()) {
212+ opt.checkValidFor(QueryType.SAVE, manager);
213+ opt.addToPreparedStatement(bs, i++);
214+ }
215+
132216 return bs;
133217 }
134218
219+ private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) {
220+ SaveNullFields option = (SaveNullFields)options.get(SAVE_NULL_FIELDS);
221+ return option == null || option.saveNullFields;
222+ }
223+
135224 /**
136225 * Save an entity mapped by this mapper.
137226 * <p>
@@ -144,7 +233,25 @@
144233 }
145234
146235 /**
147- * Save an entity mapped by this mapper asynchonously.
236+ * Save an entity mapped by this mapper and using special options for save.
237+ * This method allows you to provide a suite of {@link Option} to include in
238+ * the SAVE query. Options currently supported for SAVE are :
239+ * <ul>
240+ * <li>Timestamp</li>
241+ * <li>Time-to-live (ttl)</li>
242+ * <li>Consistency level</li>
243+ * <li>Tracing</li>
244+ * </ul>
245+ *
246+ * @param entity the entity to save.
247+ * @param options the options object specified defining special options when saving.
248+ */
249+ public void save(T entity, Option... options) {
250+ session().execute(saveQuery(entity, options));
251+ }
252+
253+ /**
254+ * Save an entity mapped by this mapper asynchronously.
148255 * <p>
149256 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
150257 *
@@ -155,6 +262,160 @@
155262 return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP);
156263 }
157264
265+ /**
266+ * Save an entity mapped by this mapper asynchronously using special options for save.
267+ * <p>
268+ * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity, options))}.
269+ *
270+ * @param entity the entity to save.
271+ * @param options the options object specified defining special options when saving.
272+ * @return a future on the completion of the save operation.
273+ */
274+ public ListenableFuture<Void> saveAsync(T entity, Option... options) {
275+ return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP);
276+ }
277+
278+ /**
279+ * Creates a query to fetch entity given its PRIMARY KEY.
280+ * <p>
281+ * The values provided must correspond to the columns composing the PRIMARY
282+ * KEY (in the order of said primary key).
283+ * <p>
284+ * This method is useful if you want to setup a number of options (tracing,
285+ * conistency level, ...) of the returned statement before executing it manually,
286+ * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
287+ * <p>
288+ * This method allows you to provide a suite of {@link Option} to include in
289+ * the GET query. Options currently supported for GET are :
290+ * <ul>
291+ * <li>Consistency level</li>
292+ * <li>Tracing</li>
293+ * </ul>
294+ *
295+ * @param objects the primary key of the entity to fetch, or more precisely
296+ * the values for the columns of said primary key in the order of the primary key.
297+ * Can be followed by {@link Option} to include in the DELETE query.
298+ * @return a query that fetch the entity of PRIMARY KEY {@code objects}.
299+ * @throws IllegalArgumentException if the number of value provided differ from
300+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
301+ * at least one of those values is {@code null}.
302+ */
303+ public Statement getQuery(Object... objects) {
304+ // Order and duplicates matter for primary keys
305+ List<Object> pks = new ArrayList<Object>();
306+ EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions);
307+
308+ for (Object o : objects) {
309+ if (o instanceof Option) {
310+ Option option = (Option)o;
311+ options.put(option.type, option);
312+ } else {
313+ pks.add(o);
314+ }
315+ }
316+ return getQuery(pks, options);
317+ }
318+
319+ private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) {
320+
321+ if (primaryKeys.size() != mapper.primaryKeySize())
322+ throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size()));
323+
324+ BoundStatement bs = getPreparedQuery(QueryType.GET, options).bind();
325+ int i = 0;
326+ for (Object value : primaryKeys) {
327+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
328+ if (value == null) {
329+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
330+ }
331+ bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
332+ }
333+
334+ if (mapper.readConsistency != null)
335+ bs.setConsistencyLevel(mapper.readConsistency);
336+
337+ for (Option opt : options.values()) {
338+ opt.checkValidFor(QueryType.GET, manager);
339+ opt.addToPreparedStatement(bs, i);
340+ if (opt.isIncludedInQuery())
341+ i++;
342+ }
343+
344+ return bs;
345+ }
346+
347+ /**
348+ * Fetch an entity based on its primary key.
349+ * <p>
350+ * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(objects))).one()}.
351+ *
352+ * @param objects the primary key of the entity to fetch, or more precisely
353+ * the values for the columns of said primary key in the order of the primary key.
354+ * Can be followed by {@link Option} to include in the DELETE query.
355+ * @return the entity fetched or {@code null} if it doesn't exist.
356+ * @throws IllegalArgumentException if the number of value provided differ from
357+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
358+ * at least one of those values is {@code null}.
359+ */
360+ public T get(Object... objects) {
361+ return mapAliased(session().execute(getQuery(objects))).one();
362+ }
363+
364+ /**
365+ * Fetch an entity based on its primary key asynchronously.
366+ * <p>
367+ * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(objects))}.
368+ *
369+ * @param objects the primary key of the entity to fetch, or more precisely
370+ * the values for the columns of said primary key in the order of the primary key.
371+ * Can be followed by {@link Option} to include in the DELETE query.
372+ * @return a future on the fetched entity. The return future will yield
373+ * {@code null} if said entity doesn't exist.
374+ * @throws IllegalArgumentException if the number of value provided differ from
375+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
376+ * at least one of those values is {@code null}.
377+ */
378+ public ListenableFuture<T> getAsync(Object... objects) {
379+ return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction);
380+ }
381+
382+ /**
383+ * Creates a query that can be used to delete the provided entity.
384+ * <p>
385+ * This method is a shortcut that extract the PRIMARY KEY from the
386+ * provided entity and call {@link #deleteQuery(Object...)} with it.
387+ * This method allows you to provide a suite of {@link Option} to include in
388+ * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
389+ * is supported for DELETE queries.
390+ * <p>
391+ * This method is useful if you want to setup a number of options (tracing,
392+ * conistency level, ...) of the returned statement before executing it manually
393+ * or need access to the {@code ResultSet} object after execution (to get the
394+ * trace, the execution info, ...), but in other cases, calling {@link #delete}
395+ * or {@link #deleteAsync} is shorter.
396+ * <p>
397+ * This method allows you to provide a suite of {@link Option} to include in
398+ * the DELETE query. Options currently supported for DELETE are :
399+ * <ul>
400+ * <li>Timestamp</li>
401+ * <li>Consistency level</li>
402+ * <li>Tracing</li>
403+ * </ul>
404+ *
405+ * @param entity the entity to delete.
406+ * @param options the options to add to the DELETE query.
407+ * @return a query that delete {@code entity} (based on it's defined mapping) with
408+ * provided USING options.
409+ */
410+ public Statement deleteQuery(T entity, Option... options) {
411+ List<Object> pks = new ArrayList<Object>();
412+ for (int i = 0; i < mapper.primaryKeySize(); i++) {
413+ pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
414+ }
415+
416+ return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions));
417+ }
418+
158419 /**
159420 * Creates a query that can be used to delete the provided entity.
160421 * <p>
@@ -171,50 +432,87 @@
171432 * @return a query that delete {@code entity} (based on it's defined mapping).
172433 */
173434 public Statement deleteQuery(T entity) {
174- Object[] pks = new Object[mapper.primaryKeySize()];
175- for (int i = 0; i < pks.length; i++)
176- pks[i] = mapper.getPrimaryKeyColumn(i).getValue(entity);
435+ List<Object> pks = new ArrayList<Object>();
436+ for (int i = 0; i < mapper.primaryKeySize(); i++) {
437+ pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
438+ }
177439
178- return deleteQuery(pks);
440+ return deleteQuery(pks, defaultDeleteOptions);
179441 }
180442
181443 /**
182444 * Creates a query that can be used to delete an entity given its PRIMARY KEY.
183445 * <p>
184446 * The values provided must correspond to the columns composing the PRIMARY
185- * KEY (in the order of said primary key).
447+ * KEY (in the order of said primary key). The values can also contain, after
448+ * specifying the primary keys columns, a suite of {@link Option} to include in
449+ * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp}
450+ * is supported for DELETE queries.
186451 * <p>
187452 * This method is useful if you want to setup a number of options (tracing,
188453 * conistency level, ...) of the returned statement before executing it manually
189454 * or need access to the {@code ResultSet} object after execution (to get the
190455 * trace, the execution info, ...), but in other cases, calling {@link #delete}
191456 * or {@link #deleteAsync} is shorter.
457+ * This method allows you to provide a suite of {@link Option} to include in
458+ * the DELETE query. Options currently supported for DELETE are :
459+ * <ul>
460+ * <li>Timestamp</li>
461+ * <li>Consistency level</li>
462+ * <li>Tracing</li>
463+ * </ul>
192464 *
193- * @param primaryKey the primary key of the entity to delete, or more precisely
194- * the values for the columns of said primary key in the order of the primary key.
465+ * @param objects the primary key of the entity to delete, or more precisely
466+ * the values for the columns of said primary key in the order of the primary key.
467+ * Can be followed by {@link Option} to include in the DELETE
468+ * query.
195469 * @return a query that delete the entity of PRIMARY KEY {@code primaryKey}.
196- *
197470 * @throws IllegalArgumentException if the number of value provided differ from
198- * the number of columns composing the PRIMARY KEY of the mapped class, or if
199- * at least one of those values is {@code null}.
471+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
472+ * at least one of those values is {@code null}.
200473 */
201- public Statement deleteQuery(Object...primaryKey) {
202- if (primaryKey.length != mapper.primaryKeySize())
203- throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.length));
474+ public Statement deleteQuery(Object... objects) {
475+ // Order and duplicates matter for primary keys
476+ List<Object> pks = new ArrayList<Object>();
477+ EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions);
478+
479+ for (Object o : objects) {
480+ if (o instanceof Option) {
481+ Option option = (Option)o;
482+ options.put(option.type, option);
483+ } else {
484+ pks.add(o);
485+ }
486+ }
487+ return deleteQuery(pks, options);
488+ }
204489
205- PreparedStatement ps = getPreparedQuery(QueryType.DEL);
490+ private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) {
491+ if (primaryKey.size() != mapper.primaryKeySize())
492+ throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size()));
206493
207- BoundStatement bs = ps.bind();
208- for (int i = 0; i < primaryKey.length; i++) {
209- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
210- Object value = primaryKey[i];
211- if (value == null)
212- throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
213- bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
214- }
494+ BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind();
215495
216496 if (mapper.writeConsistency != null)
217497 bs.setConsistencyLevel(mapper.writeConsistency);
498+
499+ int i = 0;
500+ for (Option opt : options.values()) {
501+ opt.checkValidFor(QueryType.DEL, manager);
502+ opt.addToPreparedStatement(bs, i);
503+ if (opt.isIncludedInQuery())
504+ i++;
505+ }
506+
507+ int columnNumber = 0;
508+ for (Object value : primaryKey) {
509+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
510+ if (value == null) {
511+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
512+ }
513+ bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
514+ columnNumber++;
515+ }
218516 return bs;
219517 }
220518
@@ -229,6 +527,18 @@
229527 session().execute(deleteQuery(entity));
230528 }
231529
530+ /**
531+ * Deletes an entity mapped by this mapper using provided options.
532+ * <p>
533+ * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity, options))}.
534+ *
535+ * @param entity the entity to delete.
536+ * @param options the options to add to the DELETE query.
537+ */
538+ public void delete(T entity, Option... options) {
539+ session().execute(deleteQuery(entity, options));
540+ }
541+
232542 /**
233543 * Deletes an entity mapped by this mapper asynchronously.
234544 * <p>
@@ -242,121 +552,471 @@
242552 }
243553
244554 /**
245- * Deletes an entity based on its primary key.
555+ * Deletes an entity mapped by this mapper asynchronously using provided options.
246556 * <p>
247- * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(primaryKey))}.
557+ * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity, options))}.
248558 *
249- * @param primaryKey the primary key of the entity to delete, or more precisely
250- * the values for the columns of said primary key in the order of the primary key.
559+ * @param entity the entity to delete.
560+ * @param options the options to add to the DELETE query.
561+ * @return a future on the completion of the deletion.
562+ */
563+ public ListenableFuture<Void> deleteAsync(T entity, Option... options) {
564+ return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP);
565+ }
566+
567+ /**
568+ * Deletes an entity based on its primary key.
569+ * <p>
570+ * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(objects))}.
251571 *
572+ * @param objects the primary key of the entity to delete, or more precisely
573+ * the values for the columns of said primary key in the order
574+ * of the primary key.Can be followed by {@link Option} to include
575+ * in the DELETE query.
252576 * @throws IllegalArgumentException if the number of value provided differ from
253- * the number of columns composing the PRIMARY KEY of the mapped class, or if
254- * at least one of those values is {@code null}.
577+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
578+ * at least one of those values is {@code null}.
255579 */
256- public void delete(Object... primaryKey) {
257- session().execute(deleteQuery(primaryKey));
580+ public void delete(Object... objects) {
581+ session().execute(deleteQuery(objects));
258582 }
259583
260584 /**
261585 * Deletes an entity based on its primary key asynchronously.
262586 * <p>
263- * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(primaryKey))}.
264- *
265- * @param primaryKey the primary key of the entity to delete, or more precisely
266- * the values for the columns of said primary key in the order of the primary key.
267- * @return a future on the completion of the deletion.
587+ * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(objects))}.
268588 *
589+ * @param objects the primary key of the entity to delete, or more precisely
590+ * the values for the columns of said primary key in the order
591+ * of the primary key. Can be followed by {@link Option} to include
592+ * in the DELETE query.
269593 * @throws IllegalArgumentException if the number of value provided differ from
270- * the number of columns composing the PRIMARY KEY of the mapped class, or if
271- * at least one of those values is {@code null}.
594+ * the number of columns composing the PRIMARY KEY of the mapped class, or if
595+ * at least one of those values is {@code null}.
272596 */
273- public ListenableFuture<Void> deleteAsync(Object... primaryKey) {
274- return Futures.transform(session().executeAsync(deleteQuery(primaryKey)), NOOP);
597+ public ListenableFuture<Void> deleteAsync(Object... objects) {
598+ return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP);
275599 }
276600
277601 /**
278- * Map the rows from a {@code ResultSet} into the class this is mapper of.
602+ * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
603+ * <p>
604+ * Use this method to map a result set that was not generated by the mapper (e.g. a result set coming from a
605+ * manual query or an {@link Accessor method}.
606+ * It expects that the result set contains all column mapped in the target class,
607+ * and that they are not aliased. {@link Computed} fields will not be filled in mapped objects.
279608 *
280609 * @param resultSet the {@code ResultSet} to map.
281610 * @return the mapped result set. Note that the returned mapped result set
282611 * will encapsulate {@code resultSet} and so consuming results from this
283612 * returned mapped result set will consume results from {@code resultSet}
284613 * and vice-versa.
614+ *
615+ * @see #mapAliased(ResultSet)
285616 */
286617 public Result<T> map(ResultSet resultSet) {
287618 return new Result<T>(resultSet, mapper, protocolVersion);
288619 }
289620
290621 /**
291- * Creates a query to fetch entity given its PRIMARY KEY.
292- * <p>
293- * The values provided must correspond to the columns composing the PRIMARY
294- * KEY (in the order of said primary key).
622+ * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
295623 * <p>
296- * This method is useful if you want to setup a number of options (tracing,
297- * conistency level, ...) of the returned statement before executing it manually,
298- * but in other cases, calling {@link #get} or {@link #getAsync} is shorter.
624+ * Use this method to map a result set coming from the execution of the {@code Statement} returned by
625+ * {@link #getQuery(Object...)}. {@link Computed} fields will be filled in the mapped object.
299626 *
300- * @param primaryKey the primary key of the entity to fetch, or more precisely
301- * the values for the columns of said primary key in the order of the primary key.
302- * @return a query that fetch the entity of PRIMARY KEY {@code primaryKey}.
627+ * @param resultSet the {@code ResultSet} to map.
628+ * @return the mapped result set. Note that the returned mapped result set
629+ * will encapsulate {@code resultSet} and so consuming results from this
630+ * returned mapped result set will consume results from {@code resultSet}
631+ * and vice-versa.
303632 *
304- * @throws IllegalArgumentException if the number of value provided differ from
305- * the number of columns composing the PRIMARY KEY of the mapped class, or if
306- * at least one of those values is {@code null}.
633+ * @see #map(ResultSet)
307634 */
308- public Statement getQuery(Object... primaryKey) {
309- if (primaryKey.length != mapper.primaryKeySize())
310- throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.length));
311-
312- PreparedStatement ps = getPreparedQuery(QueryType.GET);
635+ public Result<T> mapAliased(ResultSet resultSet) {
636+ return (manager.isCassandraV1)
637+ ? map(resultSet) // no aliases
638+ : new Result<T>(resultSet, mapper, protocolVersion, true);
639+ }
313640
314- BoundStatement bs = ps.bind();
315- for (int i = 0; i < primaryKey.length; i++) {
316- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
317- Object value = primaryKey[i];
318- if (value == null)
319- throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
320- bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
321- }
641+ /**
642+ * Set the default save {@link Option} for this object mapper, that will be used
643+ * in all save operations unless overridden. Refer to {@link Mapper#save(Object, Option...)})}
644+ * to check available save options.
645+ *
646+ * @param options the options to set. To reset, use {@link Mapper#resetDefaultSaveOptions}.
647+ */
648+ public void setDefaultSaveOptions(Option... options) {
649+ this.defaultSaveOptions = toMap(options);
650+ }
322651
323- if (mapper.readConsistency != null)
324- bs.setConsistencyLevel(mapper.readConsistency);
325- return bs;
652+ /**
653+ * Reset the default save options for this object mapper.
654+ */
655+ public void resetDefaultSaveOptions() {
656+ this.defaultSaveOptions = NO_OPTIONS;
326657 }
327658
328659 /**
329- * Fetch an entity based on its primary key.
330- * <p>
331- * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(primaryKey))).one()}.
660+ * Set the default get {@link Option} for this object mapper, that will be used
661+ * in all get operations unless overridden. Refer to {@link Mapper#get(Object...)} )} to check available
662+ * get options.
332663 *
333- * @param primaryKey the primary key of the entity to fetch, or more precisely
334- * the values for the columns of said primary key in the order of the primary key.
335- * @return the entity fetched or {@code null} if it doesn't exist.
664+ * @param options the options to set. To reset, use {@link Mapper#resetDefaultGetOptions}.
665+ */
666+ public void setDefaultGetOptions(Option... options) {
667+ this.defaultGetOptions = toMap(options);
668+
669+ }
670+
671+ /**
672+ * Reset the default save options for this object mapper.
673+ */
674+ public void resetDefaultGetOptions() {
675+ this.defaultGetOptions = NO_OPTIONS;
676+ }
677+
678+ /**
679+ * Set the default delete {@link Option} for this object mapper, that will be used
680+ * in all delete operations unless overridden. Refer to {@link Mapper#delete(Object...)} )}
681+ * to check available delete options.
336682 *
337- * @throws IllegalArgumentException if the number of value provided differ from
338- * the number of columns composing the PRIMARY KEY of the mapped class, or if
339- * at least one of those values is {@code null}.
683+ * @param options the options to set. To reset, use {@link Mapper#resetDefaultDeleteOptions}.
340684 */
341- public T get(Object... primaryKey) {
342- return map(session().execute(getQuery(primaryKey))).one();
685+ public void setDefaultDeleteOptions(Option... options) {
686+ this.defaultDeleteOptions = toMap(options);
343687 }
344688
345689 /**
346- * Fetch an entity based on its primary key asynchronously.
690+ * Reset the default delete options for this object mapper.
691+ */
692+ public void resetDefaultDeleteOptions() {
693+ this.defaultDeleteOptions = NO_OPTIONS;
694+ }
695+
696+ private static EnumMap<Option.Type, Option> toMap(Option[] options) {
697+ EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(Option.Type.class);
698+ for (Option option : options) {
699+ result.put(option.type, option);
700+ }
701+ return result;
702+ }
703+
704+ private static EnumMap<Option.Type, Option> toMapWithDefaults(Option[] options, EnumMap<Option.Type, Option> defaults) {
705+ EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(defaults);
706+ for (Option option : options) {
707+ result.put(option.type, option);
708+ }
709+ return result;
710+ }
711+
712+ /**
713+ * An option for a mapper operation.
347714 * <p>
348- * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(primaryKey))}.
715+ * Options can be passed to individual operations:
716+ * <pre>
717+ * mapper.save(myObject, Option.ttl(3600));
718+ * </pre>
349719 *
350- * @param primaryKey the primary key of the entity to fetch, or more precisely
351- * the values for the columns of said primary key in the order of the primary key.
352- * @return a future on the fetched entity. The return future will yield
353- * {@code null} if said entity doesn't exist.
720+ * The mapper can also have defaults, that will apply to all operations that do not
721+ * override these particular option:
722+ * <pre>
723+ * mapper.setDefaultSaveOptions(Option.ttl(3600));
724+ * mapper.save(myObject);
725+ * </pre>
354726 *
355- * @throws IllegalArgumentException if the number of value provided differ from
356- * the number of columns composing the PRIMARY KEY of the mapped class, or if
357- * at least one of those values is {@code null}.
358- */
359- public ListenableFuture<T> getAsync(Object... primaryKey) {
360- return Futures.transform(session().executeAsync(getQuery(primaryKey)), mapOneFunction);
727+ * <p>
728+ * See the static methods in this class for available options.
729+ */
730+ public static abstract class Option {
731+
732+ enum Type {TTL, TIMESTAMP, CL, TRACING, SAVE_NULL_FIELDS}
733+
734+ final Type type;
735+
736+ protected Option(Type type) {
737+ this.type = type;
738+ }
739+
740+ /**
741+ * Creates a new Option object to add time-to-live to a mapper operation. This is
742+ * only valid for save operations.
743+ * <p>
744+ * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
745+ *
746+ * @param ttl the TTL (in seconds).
747+ * @return the option.
748+ */
749+ public static Option ttl(int ttl) {
750+ return new Ttl(ttl);
751+ }
752+
753+ /**
754+ * Creates a new Option object to add a timestamp to a mapper operation. This is
755+ * only valid for save and delete operations.
756+ * <p>
757+ * Note that this option is only available if using {@link ProtocolVersion#V2} or above.
758+ *
759+ * @param timestamp the timestamp (in microseconds).
760+ * @return the option.
761+ */
762+ public static Option timestamp(long timestamp) {
763+ return new Timestamp(timestamp);
764+ }
765+
766+ /**
767+ * Creates a new Option object to add a consistency level value to a mapper operation. This
768+ * is valid for save, delete and get operations.
769+ * <p>
770+ * Note that the consistency level can also be defined at the mapper level, as a parameter
771+ * of the {@link com.datastax.driver.mapping.annotations.Table} annotation (this is redundant
772+ * for backward compatibility). This option, whether defined on a specific call or as the
773+ * default, will always take precedence over the annotation.
774+ *
775+ * @param cl the {@link com.datastax.driver.core.ConsistencyLevel} to use for the operation.
776+ * @return the option.
777+ */
778+ public static Option consistencyLevel(ConsistencyLevel cl) {
779+ return new ConsistencyLevelOption(cl);
780+ }
781+
782+ /**
783+ * Creates a new Option object to enable query tracing for a mapper operation. This
784+ * is valid for save, delete and get operations.
785+ *
786+ * @param enabled whether to enable tracing.
787+ * @return the option.
788+ */
789+ public static Option tracing(boolean enabled) {
790+ return new Tracing(enabled);
791+ }
792+
793+ /**
794+ * Creates a new Option object to specify whether null entity fields should be included in
795+ * insert queries. This option is valid only for save operations.
796+ *
797+ * If this option is not specified, it defaults to {@code true} (null fields are saved).
798+ *
799+ * @param enabled whether to include null fields in queries.
800+ * @return the option.
801+ */
802+ public static Option saveNullFields(boolean enabled){
803+ return new SaveNullFields(enabled);
804+ }
805+
806+ public Type getType(){
807+ return this.type;
808+ }
809+
810+ abstract void appendTo(Insert.Options usings);
811+
812+ abstract void appendTo(Delete.Options usings);
813+
814+ abstract void addToPreparedStatement(BoundStatement bs, int i);
815+
816+ abstract void checkValidFor(QueryType qt, MappingManager manager) throws IllegalArgumentException;
817+
818+ abstract boolean isIncludedInQuery();
819+
820+ static class Ttl extends Option {
821+
822+ private int ttlValue;
823+
824+ Ttl(int value) {
825+ super(Type.TTL);
826+ this.ttlValue = value;
827+ }
828+
829+ void appendTo(Insert.Options usings) {
830+ usings.and(QueryBuilder.ttl(QueryBuilder.bindMarker()));
831+ }
832+ @Override
833+ void appendTo(Delete.Options usings) {
834+ throw new UnsupportedOperationException("shouldn't be called");
835+ }
836+ @Override
837+ void addToPreparedStatement(BoundStatement bs, int i) {
838+ bs.setInt(i, this.ttlValue);
839+ }
840+ @Override
841+ void checkValidFor(QueryType qt, MappingManager manager) {
842+ checkArgument(!manager.isCassandraV1, "TTL option requires native protocol v2 or above");
843+ checkArgument(qt == QueryType.SAVE, "TTL option is only allowed in save queries");
844+ }
845+ @Override
846+ boolean isIncludedInQuery() {
847+ return true;
848+ }
849+ }
850+
851+ static class Timestamp extends Option {
852+
853+ private long tsValue;
854+
855+ Timestamp(long value) {
856+ super(Type.TIMESTAMP);
857+ this.tsValue = value;
858+ }
859+ @Override
860+ void appendTo(Insert.Options usings) {
861+ usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
862+ }
863+ @Override
864+ void appendTo(Delete.Options usings) {
865+ usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker()));
866+ }
867+ @Override
868+ void checkValidFor(QueryType qt, MappingManager manager) {
869+ checkArgument(!manager.isCassandraV1, "Timestamp option requires native protocol v2 or above");
870+ checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL, "Timestamp option is only allowed in save and delete queries");
871+ }
872+ @Override
873+ void addToPreparedStatement(BoundStatement bs, int i) {
874+ bs.setLong(i, this.tsValue);
875+ }
876+ @Override
877+ boolean isIncludedInQuery() {
878+ return true;
879+ }
880+ }
881+
882+ static class ConsistencyLevelOption extends Option {
883+
884+ private ConsistencyLevel cl;
885+
886+ ConsistencyLevelOption(ConsistencyLevel cl) {
887+ super(Type.CL);
888+ this.cl = cl;
889+ }
890+ @Override
891+ void appendTo(Insert.Options usings) {
892+ throw new UnsupportedOperationException("shouldn't be called");
893+ }
894+ @Override
895+ void appendTo(Delete.Options usings) {
896+ throw new UnsupportedOperationException("shouldn't be called");
897+ }
898+
899+ @Override
900+ void addToPreparedStatement(BoundStatement bs, int i) {
901+ bs.setConsistencyLevel(cl);
902+ }
903+ @Override
904+ void checkValidFor(QueryType qt, MappingManager manager) {
905+ checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
906+ "Consistency level option is only allowed in save, delete and get queries");
907+ }
908+
909+ @Override
910+ boolean isIncludedInQuery() {
911+ return false;
912+ }
913+ }
914+
915+ static class Tracing extends Option {
916+
917+ private boolean tracing;
918+
919+ Tracing(boolean tracing) {
920+ super(Type.TRACING);
921+ this.tracing = tracing;
922+ }
923+ @Override
924+ void appendTo(Insert.Options usings) {
925+ throw new UnsupportedOperationException("shouldn't be called");
926+ }
927+ @Override
928+ void appendTo(Delete.Options usings) {
929+ throw new UnsupportedOperationException("shouldn't be called");
930+ }
931+
932+ @Override
933+ void addToPreparedStatement(BoundStatement bs, int i) {
934+ if (this.tracing)
935+ bs.enableTracing();
936+ }
937+
938+ @Override
939+ void checkValidFor(QueryType qt, MappingManager manager) {
940+ checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET,
941+ "Tracing option is only allowed in save, delete and get queries");
942+ }
943+
944+ @Override
945+ boolean isIncludedInQuery() {
946+ return false;
947+ }
948+ }
949+
950+ static class SaveNullFields extends Option {
951+
952+ private boolean saveNullFields;
953+
954+ SaveNullFields(boolean saveNullFields) {
955+ super(SAVE_NULL_FIELDS);
956+ this.saveNullFields = saveNullFields;
957+ }
958+
959+ @Override
960+ void appendTo(Insert.Options usings) {
961+ throw new UnsupportedOperationException("shouldn't be called");
962+ }
963+
964+ @Override
965+ void appendTo(Delete.Options usings) {
966+ throw new UnsupportedOperationException("shouldn't be called");
967+ }
968+
969+ @Override
970+ void addToPreparedStatement(BoundStatement bs, int i) {
971+ // nothing to do
972+ }
973+
974+ @Override
975+ void checkValidFor(QueryType qt, MappingManager manager) {
976+ checkArgument(qt == QueryType.SAVE, "SaveNullFields option is only allowed in save queries");
977+ }
978+
979+ @Override
980+ boolean isIncludedInQuery() {
981+ return false;
982+ }
983+ }
984+
985+ }
986+
987+ private static class MapperQueryKey {
988+ private final QueryType queryType;
989+ private final EnumSet<Option.Type> optionTypes;
990+ private final Set<ColumnMapper<?>> columns;
991+
992+ MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) {
993+ Preconditions.checkNotNull(queryType);
994+ Preconditions.checkNotNull(options);
995+ Preconditions.checkNotNull(columnMappers);
996+ this.queryType = queryType;
997+ this.columns = columnMappers;
998+ this.optionTypes = EnumSet.noneOf(Option.Type.class);
999+ for (Option opt : options.values()) {
1000+ if (opt.isIncludedInQuery())
1001+ this.optionTypes.add(opt.type);
1002+ }
1003+ }
1004+
1005+ @Override
1006+ public boolean equals(Object other) {
1007+ if (this == other)
1008+ return true;
1009+ if (other instanceof MapperQueryKey) {
1010+ MapperQueryKey that = (MapperQueryKey)other;
1011+ return this.queryType.equals(that.queryType)
1012+ && this.optionTypes.equals(that.optionTypes)
1013+ && this.columns.equals(that.columns);
1014+ }
1015+ return false;
1016+ }
1017+
1018+ public int hashCode() {
1019+ return Objects.hashCode(queryType, optionTypes, columns);
1020+ }
3611021 }
3621022 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +15 −4
@@ -19,19 +19,18 @@
1919 import java.util.HashMap;
2020 import java.util.Map;
2121
22-import com.datastax.driver.core.*;
23-
22+import com.datastax.driver.core.ProtocolVersion;
23+import com.datastax.driver.core.Session;
2424 import com.datastax.driver.mapping.annotations.Accessor;
2525 import com.datastax.driver.mapping.annotations.Table;
2626
27-import com.datastax.driver.mapping.annotations.UDT;
28-
2927 /**
3028 * Mapping manager from which to obtain entity mappers.
3129 */
3230 public class MappingManager {
3331
3432 private final Session session;
33+ final boolean isCassandraV1;
3534
3635 private volatile Map<Class<?>, Mapper<?>> mappers = Collections.<Class<?>, Mapper<?>>emptyMap();
3736 private volatile Map<Class<?>, UDTMapper<?>> udtMappers = Collections.<Class<?>, UDTMapper<?>>emptyMap();
@@ -39,11 +38,23 @@
3938
4039 /**
4140 * Creates a new {@code MappingManager} using the provided {@code Session}.
41+ * <p>
42+ * Note that this constructor forces the initialization of the session.
4243 *
4344 * @param session the {@code Session} to use.
4445 */
4546 public MappingManager(Session session) {
4647 this.session = session;
48+ // This is not strictly correct because we could connect to C* 2.0 with the v1 protocol.
49+ // But mappers need to make a decision early so that generated queries are compatible, and we don't know in advance
50+ // which nodes might join the cluster later.
51+ // At least if protocol >=2 we know there won't be any 1.2 nodes ever.
52+ this.isCassandraV1 = (getProtocolVersion(session) == ProtocolVersion.V1);
53+ }
54+
55+ private static ProtocolVersion getProtocolVersion(Session session) {
56+ session.init();
57+ return session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
4758 }
4859
4960 /**
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +3 −3
@@ -67,7 +67,7 @@
6767 // TODO: we should also validate the types of the parameters...
6868
6969 Class<?> returnType = method.getReturnType();
70- if (Void.class.isAssignableFrom(returnType) || ResultSet.class.isAssignableFrom(returnType))
70+ if (Void.TYPE.isAssignableFrom(returnType) || ResultSet.class.isAssignableFrom(returnType))
7171 return;
7272
7373 if (Statement.class.isAssignableFrom(returnType)) {
@@ -142,8 +142,8 @@
142142 return future;
143143
144144 return mapOne
145- ? Futures.transform(future, returnMapper.mapOneFunction)
146- : Futures.transform(future, returnMapper.mapAllFunction);
145+ ? Futures.transform(future, returnMapper.mapOneFunctionWithoutAliases)
146+ : Futures.transform(future, returnMapper.mapAllFunctionWithoutAliases);
147147 } else {
148148 ResultSet rs = session.execute(bs);
149149 if (returnMapper == null)
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +100 −66
@@ -15,7 +15,10 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.util.*;
18+import java.util.ArrayList;
19+import java.util.Collection;
20+import java.util.List;
21+import java.util.Set;
1922
2023 import com.google.common.base.Objects;
2124
@@ -23,11 +26,13 @@
2326 import com.datastax.driver.core.querybuilder.Delete;
2427 import com.datastax.driver.core.querybuilder.Insert;
2528 import com.datastax.driver.core.querybuilder.Select;
29+
2630 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2731
2832 class QueryType {
2933
30- private enum Kind { SAVE, GET, DEL, SLICE, REVERSED_SLICE };
34+ private enum Kind {SAVE, GET, DEL, SLICE, REVERSED_SLICE}
35+
3136 private final Kind kind;
3237
3338 // For slices
@@ -56,84 +61,112 @@
5661 return new QueryType(reversed ? Kind.REVERSED_SLICE : Kind.SLICE, startBoundSize, startInclusive, endBoundSize, endInclusive);
5762 }
5863
59- String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper) {
64+ String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) {
6065 switch (kind) {
61- case SAVE:
62- {
63- Insert insert = table == null
64- ? insertInto(mapper.getKeyspace(), mapper.getTable())
65- : insertInto(table);
66- for (ColumnMapper<?> cm : mapper.allColumns())
66+ case SAVE: {
67+ Insert insert = table == null
68+ ? insertInto(mapper.getKeyspace(), mapper.getTable())
69+ : insertInto(table);
70+ for (ColumnMapper<?> cm : columns)
71+ if (cm.kind != ColumnMapper.Kind.COMPUTED)
6772 insert.value(cm.getColumnName(), bindMarker());
68- return insert.toString();
73+
74+ Insert.Options usings = insert.using();
75+ for (Mapper.Option opt : options) {
76+ opt.checkValidFor(QueryType.SAVE, manager);
77+ if (opt.isIncludedInQuery())
78+ opt.appendTo(usings);
79+ }
80+ return insert.toString();
81+ }
82+ case GET: {
83+ Select.Selection selection = select();
84+ for (ColumnMapper cm : mapper.allColumns()) {
85+ Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED)
86+ ? ((Select.SelectionOrAlias)selection).raw(cm.getColumnName())
87+ : selection.column(cm.getColumnName());
88+
89+ if (cm.getAlias() == null) {
90+ selection = column;
91+ } else {
92+ selection = column.as(cm.getAlias());
93+ }
6994 }
70- case GET:
71- {
72- Select select = table == null
73- ? select().all().from(mapper.getKeyspace(), mapper.getTable())
74- : select().all().from(table);
75- Select.Where where = select.where();
76- for (int i = 0; i < mapper.primaryKeySize(); i++)
77- where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
78- return select.toString();
95+ Select select;
96+ if (table == null) {
97+ select = selection.from(mapper.getKeyspace(), mapper.getTable());
98+ } else {
99+ select = selection.from(table);
79100 }
80- case DEL:
81- {
82- Delete delete = table == null
83- ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
84- : delete().all().from(table);
85- Delete.Where where = delete.where();
86- for (int i = 0; i < mapper.primaryKeySize(); i++)
87- where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
88- return delete.toString();
101+ Select.Where where = select.where();
102+ for (int i = 0; i < mapper.primaryKeySize(); i++)
103+ where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
104+
105+ for (Mapper.Option opt : options)
106+ opt.checkValidFor(QueryType.GET, manager);
107+ return select.toString();
108+ }
109+ case DEL: {
110+ Delete delete = table == null
111+ ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
112+ : delete().all().from(table);
113+ Delete.Where where = delete.where();
114+ for (int i = 0; i < mapper.primaryKeySize(); i++)
115+ where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
116+ Delete.Options usings = delete.using();
117+ for (Mapper.Option opt : options) {
118+ opt.checkValidFor(QueryType.DEL, manager);
119+ if (opt.isIncludedInQuery())
120+ opt.appendTo(usings);
89121 }
122+ return delete.toString();
123+ }
90124 case SLICE:
91- case REVERSED_SLICE:
92- {
93- Select select = table == null
94- ? select().all().from(mapper.getKeyspace(), mapper.getTable())
95- : select().all().from(table);
96- Select.Where where = select.where();
97- for (int i = 0; i < mapper.partitionKeys.size(); i++)
98- where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker()));
99-
100- if (startBoundSize > 0) {
101- if (startBoundSize == 1) {
102- String name = mapper.clusteringColumns.get(0).getColumnName();
103- where.and(startInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
104- } else {
105- List<String> names = new ArrayList<String>(startBoundSize);
106- List<Object> values = new ArrayList<Object>(startBoundSize);
107- for (int i = 0; i < startBoundSize; i++) {
108- names.add(mapper.clusteringColumns.get(i).getColumnName());
109- values.add(bindMarker());
110- }
111- where.and(startInclusive ? gte(names, values) : gt(names, values));
125+ case REVERSED_SLICE: {
126+ Select select = table == null
127+ ? select().all().from(mapper.getKeyspace(), mapper.getTable())
128+ : select().all().from(table);
129+ Select.Where where = select.where();
130+ for (int i = 0; i < mapper.partitionKeys.size(); i++)
131+ where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker()));
132+
133+ if (startBoundSize > 0) {
134+ if (startBoundSize == 1) {
135+ String name = mapper.clusteringColumns.get(0).getColumnName();
136+ where.and(startInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
137+ } else {
138+ List<String> names = new ArrayList<String>(startBoundSize);
139+ List<Object> values = new ArrayList<Object>(startBoundSize);
140+ for (int i = 0; i < startBoundSize; i++) {
141+ names.add(mapper.clusteringColumns.get(i).getColumnName());
142+ values.add(bindMarker());
112143 }
144+ where.and(startInclusive ? gte(names, values) : gt(names, values));
113145 }
146+ }
114147
115- if (endBoundSize > 0) {
116- if (endBoundSize == 1) {
117- String name = mapper.clusteringColumns.get(0).getColumnName();
118- where.and(endInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
119- } else {
120- List<String> names = new ArrayList<String>(endBoundSize);
121- List<Object> values = new ArrayList<Object>(endBoundSize);
122- for (int i = 0; i < endBoundSize; i++) {
123- names.add(mapper.clusteringColumns.get(i).getColumnName());
124- values.add(bindMarker());
125- }
126- where.and(endInclusive ? lte(names, values) : lt(names, values));
148+ if (endBoundSize > 0) {
149+ if (endBoundSize == 1) {
150+ String name = mapper.clusteringColumns.get(0).getColumnName();
151+ where.and(endInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
152+ } else {
153+ List<String> names = new ArrayList<String>(endBoundSize);
154+ List<Object> values = new ArrayList<Object>(endBoundSize);
155+ for (int i = 0; i < endBoundSize; i++) {
156+ names.add(mapper.clusteringColumns.get(i).getColumnName());
157+ values.add(bindMarker());
127158 }
159+ where.and(endInclusive ? lte(names, values) : lt(names, values));
128160 }
161+ }
129162
130- select = select.limit(bindMarker());
163+ select = select.limit(bindMarker());
131164
132- if (kind == Kind.REVERSED_SLICE)
133- select = select.orderBy(desc(mapper.clusteringColumns.get(0).getColumnName()));
165+ if (kind == Kind.REVERSED_SLICE)
166+ select = select.orderBy(desc(mapper.clusteringColumns.get(0).getColumnName()));
134167
135- return select.toString();
136- }
168+ return select.toString();
169+ }
137170 }
138171 throw new AssertionError();
139172 }
@@ -157,4 +190,5 @@
157190 public int hashCode() {
158191 return Objects.hashCode(kind, startBoundSize, startInclusive, endBoundSize, endInclusive);
159192 }
193+
160194 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +26 −22
@@ -18,12 +18,16 @@
1818 import java.beans.IntrospectionException;
1919 import java.beans.PropertyDescriptor;
2020 import java.lang.reflect.Field;
21+import java.lang.reflect.Method;
2122 import java.lang.reflect.ParameterizedType;
2223 import java.lang.reflect.Type;
23-import java.lang.reflect.Method;
24-import java.util.*;
24+import java.util.HashMap;
25+import java.util.Map;
26+import java.util.concurrent.atomic.AtomicInteger;
2527
26-import com.datastax.driver.core.*;
28+import com.datastax.driver.core.ConsistencyLevel;
29+import com.datastax.driver.core.DataType;
30+import com.datastax.driver.core.UDTValue;
2731
2832 /**
2933 * An {@link EntityMapper} implementation that use reflection to read and write fields
@@ -55,12 +59,12 @@
5559 private final Method readMethod;
5660 private final Method writeMethod;
5761
58- private LiteralMapper(Field field, int position, PropertyDescriptor pd) {
59- this(field, extractSimpleType(field), position, pd);
62+ private LiteralMapper(Field field, int position, PropertyDescriptor pd, AtomicInteger columnNumber) {
63+ this(field, extractSimpleType(field), position, pd, columnNumber);
6064 }
6165
62- private LiteralMapper(Field field, DataType type, int position, PropertyDescriptor pd) {
63- super(field, type, position);
66+ private LiteralMapper(Field field, DataType type, int position, PropertyDescriptor pd, AtomicInteger columnCounter) {
67+ super(field, type, position, columnCounter);
6468 this.readMethod = pd.getReadMethod();
6569 this.writeMethod = pd.getWriteMethod();
6670 }
@@ -93,8 +97,8 @@
9397 private final EnumType enumType;
9498 private final Map<String, Object> fromString;
9599
96- private EnumMapper(Field field, int position, PropertyDescriptor pd, EnumType enumType) {
97- super(field, enumType == EnumType.STRING ? DataType.text() : DataType.cint(), position, pd);
100+ private EnumMapper(Field field, int position, PropertyDescriptor pd, EnumType enumType, AtomicInteger columnCounter) {
101+ super(field, enumType == EnumType.STRING ? DataType.text() : DataType.cint(), position, pd, columnCounter);
98102 this.enumType = enumType;
99103
100104 if (enumType == EnumType.STRING) {
@@ -108,7 +112,7 @@
108112 }
109113
110114 @SuppressWarnings("rawtypes")
111- @Override
115+ @Override
112116 public Object getValue(T entity) {
113117 Object value = super.getValue(entity);
114118 switch (enumType) {
@@ -138,22 +142,22 @@
138142 private static class UDTColumnMapper<T, U> extends LiteralMapper<T> {
139143 private final UDTMapper<U> udtMapper;
140144
141- private UDTColumnMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<U> udtMapper) {
142- super(field, udtMapper.getUserType(), position, pd);
145+ private UDTColumnMapper(Field field, int position, PropertyDescriptor pd, UDTMapper<U> udtMapper, AtomicInteger columnCounter) {
146+ super(field, udtMapper.getUserType(), position, pd, columnCounter);
143147 this.udtMapper = udtMapper;
144148 }
145149
146150 @Override
147151 public Object getValue(T entity) {
148152 @SuppressWarnings("unchecked")
149- U udtEntity = (U) super.getValue(entity);
153+ U udtEntity = (U)super.getValue(entity);
150154 return udtEntity == null ? null : udtMapper.toUDT(udtEntity);
151155 }
152156
153157 @Override
154158 public void setValue(Object entity, Object value) {
155159 assert value instanceof UDTValue;
156- UDTValue udtValue = (UDTValue) value;
160+ UDTValue udtValue = (UDTValue)value;
157161 assert udtValue.getType().equals(udtMapper.getUserType());
158162
159163 super.setValue(entity, udtMapper.toEntity((udtValue)));
@@ -163,8 +167,8 @@
163167 private static class NestedUDTMapper<T> extends LiteralMapper<T> {
164168 private final InferredCQLType inferredCQLType;
165169
166- public NestedUDTMapper(Field field, int position, PropertyDescriptor pd, InferredCQLType inferredCQLType) {
167- super(field, inferredCQLType.dataType, position, pd);
170+ public NestedUDTMapper(Field field, int position, PropertyDescriptor pd, InferredCQLType inferredCQLType, AtomicInteger columnCounter) {
171+ super(field, inferredCQLType.dataType, position, pd, columnCounter);
168172 this.inferredCQLType = inferredCQLType;
169173 }
170174
@@ -199,32 +203,32 @@
199203 }
200204
201205 @SuppressWarnings({ "unchecked", "rawtypes" })
202- public <T> ColumnMapper<T> createColumnMapper(Class<T> entityClass, Field field, int position, MappingManager mappingManager) {
206+ public <T> ColumnMapper<T> createColumnMapper(Class<T> entityClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter) {
203207 String fieldName = field.getName();
204208 try {
205209 PropertyDescriptor pd = new PropertyDescriptor(fieldName, field.getDeclaringClass());
206210
207211 if (field.getType().isEnum()) {
208- return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field));
212+ return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field), columnCounter);
209213 }
210214
211215 if (TypeMappings.isMappedUDT(field.getType())) {
212216 UDTMapper<?> udtMapper = mappingManager.getUDTMapper(field.getType());
213- return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper);
217+ return (ColumnMapper<T>) new UDTColumnMapper(field, position, pd, udtMapper, columnCounter);
214218 }
215219
216220 if (field.getGenericType() instanceof ParameterizedType) {
217221 InferredCQLType inferredCQLType = InferredCQLType.from(field, mappingManager);
218222 if (inferredCQLType.containsMappedUDT) {
219223 // We need a specialized mapper to convert UDT instances in the hierarchy.
220- return (ColumnMapper<T>)new NestedUDTMapper(field, position, pd, inferredCQLType);
224+ return (ColumnMapper<T>)new NestedUDTMapper(field, position, pd, inferredCQLType, columnCounter);
221225 } else {
222226 // The default codecs will know how to handle the extracted datatype.
223- return new LiteralMapper<T>(field, inferredCQLType.dataType, position, pd);
227+ return new LiteralMapper<T>(field, inferredCQLType.dataType, position, pd, columnCounter);
224228 }
225229 }
226230
227- return new LiteralMapper<T>(field, position, pd);
231+ return new LiteralMapper<T>(field, position, pd, columnCounter);
228232
229233 } catch (IntrospectionException e) {
230234 throw new IllegalArgumentException("Cannot find matching getter and setter for field '" + fieldName + "'");
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +10 −1
@@ -28,17 +28,26 @@
2828 private final ResultSet rs;
2929 private final EntityMapper<T> mapper;
3030 private final ProtocolVersion protocolVersion;
31+ private final boolean useAlias;
3132
3233 Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion) {
34+ this(rs, mapper, protocolVersion, false);
35+ }
36+
37+ Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion, boolean useAlias) {
3338 this.rs = rs;
3439 this.mapper = mapper;
3540 this.protocolVersion = protocolVersion;
41+ this.useAlias = useAlias;
3642 }
3743
3844 private T map(Row row) {
3945 T entity = mapper.newEntity();
4046 for (ColumnMapper<T> cm : mapper.allColumns()) {
41- ByteBuffer bytes = row.getBytesUnsafe(cm.getColumnName());
47+ String name = cm.getAlias() != null && this.useAlias ? cm.getAlias() : cm.getColumnName();
48+ if (!row.getColumnDefinitions().contains(name))
49+ continue;
50+ ByteBuffer bytes = row.getBytesUnsafe(name);
4251 if (bytes != null)
4352 cm.setValue(entity, cm.getDataType().deserialize(bytes, protocolVersion));
4453 }
added driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Computed.java +50 −0
@@ -0,0 +1,50 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.mapping.annotations;
17+
18+
19+import java.lang.annotation.ElementType;
20+import com.datastax.driver.mapping.Mapper;
21+import java.lang.annotation.Retention;
22+import java.lang.annotation.RetentionPolicy;
23+import java.lang.annotation.Target;
24+
25+/**
26+ * Annotates a "computed" field, which gets filled from a CQL expression in the SELECT query
27+ * used to retrieve an entity.
28+ * <p>
29+ * Note that such fields are only filled by default mapper operations ({@link Mapper#get(Object...)}),
30+ * they will be ignored in accessor queries and save operations.
31+ * <p>
32+ * As opposed to other mapper annotation, this one doesn't handle case sensitivity. If your expression
33+ * contains case-sensitive names, you'll need to quote them explicitly:
34+ * <pre>
35+ * {@code @Computed("\"caseSensitiveFunction\"(v)")}
36+ * </pre>
37+ */
38+@Target(ElementType.FIELD)
39+@Retention(RetentionPolicy.RUNTIME)
40+public @interface Computed {
41+ /**
42+ * The formula used to compute the field.
43+ * <p>
44+ * This is a CQL expression like you would use directly in a query, for instance
45+ * "writetime(v)".
46+ *
47+ * @return the formula.
48+ */
49+ String value();
50+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Enumerated.java +1 −1
@@ -29,7 +29,7 @@
2929 * The optional {@link EnumType} value defined how the enumeration must be
3030 * persisted.
3131 */
32-@Target(ElementType.FIELD)
32+@Target(value = {ElementType.FIELD, ElementType.PARAMETER})
3333 @Retention(RetentionPolicy.RUNTIME)
3434 public @interface Enumerated {
3535 /**
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +152 −0
@@ -0,0 +1,152 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.mapping;
17+
18+import java.util.Collection;
19+
20+import com.datastax.driver.core.ResultSet;
21+import com.google.common.collect.Lists;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.CCMBridge;
27+import com.datastax.driver.mapping.annotations.*;
28+
29+public class MapperAccessorParamsTest extends CCMBridge.PerClassSingleNodeCluster {
30+ @Override
31+ protected Collection<String> getTableDefinitions() {
32+ return Lists.newArrayList(
33+ "CREATE TABLE user ( key int primary key, gender int)",
34+ "CREATE INDEX on user(gender)",
35+ "CREATE TABLE user_str ( key int primary key, gender text)",
36+ "CREATE INDEX on user_str(gender)");
37+ }
38+
39+ @Test(groups = "short")
40+ void should_include_enumtype_in_accessor_ordinal() {
41+ UserAccessor accessor = new MappingManager(session)
42+ .createAccessor(UserAccessor.class);
43+
44+ accessor.addUser(0, Enum.FEMALE);
45+ accessor.addUser(1, Enum.MALE);
46+
47+ assertThat(accessor.getUser(Enum.MALE).one().getGender()).isEqualTo(Enum.MALE);
48+ assertThat(accessor.getUser(Enum.MALE).one().getKey()).isEqualTo(1);
49+
50+ assertThat(accessor.getUser(Enum.FEMALE).one().getGender()).isEqualTo(Enum.FEMALE);
51+ assertThat(accessor.getUser(Enum.FEMALE).one().getKey()).isEqualTo(0);
52+ }
53+
54+ @Test(groups = "short")
55+ void should_include_enumtype_in_accessor_string() {
56+ UserAccessor accessor = new MappingManager(session)
57+ .createAccessor(UserAccessor.class);
58+
59+ accessor.addUserStr(0, Enum.FEMALE);
60+ accessor.addUserStr(1, Enum.MALE);
61+
62+ assertThat(accessor.getUserStr(Enum.MALE).one().getGender()).isEqualTo(Enum.MALE);
63+ assertThat(accessor.getUserStr(Enum.MALE).one().getKey()).isEqualTo(1);
64+
65+ assertThat(accessor.getUserStr(Enum.FEMALE).one().getGender()).isEqualTo(Enum.FEMALE);
66+ assertThat(accessor.getUserStr(Enum.FEMALE).one().getKey()).isEqualTo(0);
67+ }
68+
69+ enum Enum {
70+ MALE, FEMALE
71+ }
72+
73+ @Accessor
74+ public interface UserAccessor {
75+ @Query("select * from user where gender=?")
76+ Result<User> getUser(@Enumerated(EnumType.ORDINAL) Enum value);
77+
78+ @Query("select * from user_str where gender=?")
79+ Result<UserStr> getUserStr(@Enumerated(EnumType.STRING) Enum value);
80+
81+ @Query("insert into user (key, gender) values (?,?)")
82+ ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value);
83+
84+ @Query("insert into user_str (key, gender) values (?,?)")
85+ ResultSet addUserStr(int key, @Enumerated(EnumType.STRING) Enum value);
86+ }
87+
88+ @Table(name = "user")
89+ public static class User {
90+ @PartitionKey
91+ private int key;
92+
93+ @Enumerated(EnumType.ORDINAL)
94+ private Enum gender;
95+
96+ public User() {
97+ }
98+
99+ public User(int k, Enum val) {
100+ this.key = k;
101+ this.gender = val;
102+ }
103+
104+ public int getKey() {
105+ return this.key;
106+ }
107+
108+ public void setKey(int pk) {
109+ this.key = pk;
110+ }
111+
112+ public Enum getGender() {
113+ return this.gender;
114+ }
115+
116+ public void setGender(Enum val) {
117+ this.gender = val;
118+ }
119+ }
120+
121+ @Table(name = "user")
122+ public static class UserStr {
123+ @PartitionKey
124+ private int key;
125+
126+ private Enum gender;
127+
128+ public UserStr() {
129+ }
130+
131+ public UserStr(int k, Enum val) {
132+ this.key = k;
133+ this.gender = val;
134+ }
135+
136+ public int getKey() {
137+ return this.key;
138+ }
139+
140+ public void setKey(int pk) {
141+ this.key = pk;
142+ }
143+
144+ public Enum getGender() {
145+ return this.gender;
146+ }
147+
148+ public void setGender(Enum val) {
149+ this.gender = val;
150+ }
151+ }
152+}
No newline at the end of the file
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorTest.java +16 −0
@@ -79,6 +79,15 @@
7979 assertThat(row.getString("v")).isNull();
8080 }
8181
82+ @Test(groups = "short")
83+ public void should_allow_void_return_type_in_accessor() {
84+ VoidAccessor accessor = new MappingManager(session).createAccessor(VoidAccessor.class);
85+ accessor.insert(1, "bar");
86+ Row row = session.execute("select * from foo where k = 1").one();
87+ assertThat(row.getInt("k")).isEqualTo(1);
88+ assertThat(row.getString("v")).isEqualTo("bar");
89+ }
90+
8291 @Accessor
8392 public interface SystemAccessor {
8493 @Query("select release_version from system.local")
@@ -96,4 +105,11 @@
96105 @Query("insert into foo (k, v) values (?, ?)")
97106 ResultSet insert(int k, String v);
98107 }
108+
109+ @Accessor
110+ public interface VoidAccessor {
111+ @Query("insert into foo (k, v) values (?, ?)")
112+ void insert(int k, String v);
113+ }
114+
99115 }
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +285 −0
@@ -0,0 +1,285 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.mapping;
17+
18+import java.util.Collection;
19+
20+import com.google.common.collect.Lists;
21+import org.testng.SkipException;
22+import org.testng.annotations.BeforeMethod;
23+import org.testng.annotations.Test;
24+
25+import static com.datastax.driver.core.ProtocolVersion.V1;
26+import static org.assertj.core.api.Assertions.fail;
27+
28+import com.datastax.driver.core.*;
29+import com.datastax.driver.core.exceptions.InvalidQueryException;
30+import com.datastax.driver.core.utils.CassandraVersion;
31+import com.datastax.driver.mapping.annotations.*;
32+
33+import static com.datastax.driver.core.Assertions.assertThat;
34+
35+/**
36+ * Tests to ensure validity of {@link com.datastax.driver.mapping.annotations.Computed}
37+ * annotation to map computed fields.
38+ */
39+@SuppressWarnings("unused")
40+public class MapperComputedFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
41+
42+ @Override
43+ protected Collection<String> getTableDefinitions() {
44+ return Lists.newArrayList(
45+ "CREATE TABLE user (login text primary key, name text)",
46+ "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
47+ }
48+
49+ ProtocolVersion protocolVersion;
50+ MappingManager mappingManager;
51+ Mapper<User> userMapper;
52+
53+ @BeforeMethod(groups = "short")
54+ void setup() {
55+ mappingManager = new MappingManager(session);
56+ protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
57+ if (protocolVersion.compareTo(V1) > 0)
58+ userMapper = mappingManager.mapper(User.class);
59+ }
60+
61+ @Test(groups = "short", expectedExceptions = { UnsupportedOperationException.class })
62+ void should_get_unsupported_operation_exception_on_v1() {
63+ if (protocolVersion.compareTo(V1) > 0)
64+ throw new SkipException("Skipped when protocol version > V1");
65+
66+ userMapper = mappingManager.mapper(User.class);
67+ }
68+
69+ @Test(groups = "short")
70+ @CassandraVersion(major = 2.0)
71+ void should_save_and_get_entity_with_computed_fields() {
72+ long writeTime = System.currentTimeMillis() * 1000;
73+ User newUser = new User("testlogin2", "blah");
74+ newUser.setWriteTime(1); // will be ignored
75+
76+ userMapper.save(newUser);
77+
78+ User fetched = userMapper.get("testlogin2");
79+ assertThat(fetched.getLogin()).isEqualTo("testlogin2");
80+ assertThat(fetched.getName()).isEqualTo("blah");
81+ // write time should be within 30 seconds.
82+ assertThat(fetched.getWriteTime()).isGreaterThanOrEqualTo(writeTime).isLessThan(writeTime + 30000000L);
83+ assertThat(fetched.getTtl()).isNull(); // TTL should be null since it was not set.
84+
85+ // Overwrite with TTL
86+ session.execute("insert into user (login, name) values ('testlogin2', 'blah') using TTL 600");
87+ fetched = userMapper.get("testlogin2");
88+ assertThat(fetched.getWriteTime()).isGreaterThanOrEqualTo(writeTime).isLessThan(writeTime + 30000000L);
89+ assertThat(fetched.getTtl()).isBetween(570, 600); // TTL should be within 30 secs.
90+
91+ // cleanup
92+ userMapper.delete(newUser);
93+ }
94+
95+ @Test(groups = "short")
96+ @CassandraVersion(major = 2.0)
97+ void should_add_aliases_for_fields_in_select_queries() {
98+ BoundStatement bs = (BoundStatement)userMapper.getQuery("test");
99+ assertThat(bs.preparedStatement().getQueryString())
100+ .contains("SELECT", "\"login\" AS col1", "\"name\" AS col2", "writetime(\"name\") AS col3");
101+ }
102+
103+ @Test(groups = "short")
104+ @CassandraVersion(major = 2.0)
105+ public void should_map_aliased_resultset_to_objects() {
106+ Statement getQuery = userMapper.getQuery("testlogin");
107+ getQuery.setConsistencyLevel(ConsistencyLevel.QUORUM);
108+ ResultSet rs = session.execute(getQuery);
109+
110+ Result<User> result = userMapper.mapAliased(rs);
111+ User user = result.one();
112+
113+ assertThat(user.getLogin()).isEqualTo("testlogin");
114+ }
115+
116+ @Test(groups = "short")
117+ @CassandraVersion(major = 2.0)
118+ void should_map_unaliased_resultset_to_objects() {
119+ UserAccessor userAccessor = mappingManager.createAccessor(UserAccessor.class);
120+ ResultSet rs = userAccessor.all();
121+
122+ Result<User> result = userMapper.map(rs);
123+ User user = result.one();
124+ assertThat(user.getLogin()).isEqualTo("testlogin");
125+ assertThat(user.getWriteTime()).isEqualTo(0);
126+ }
127+
128+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
129+ @CassandraVersion(major = 2.0)
130+ void should_fail_if_computed_field_is_not_right_type() {
131+ mappingManager.mapper(User_WrongComputedType.class);
132+ }
133+
134+ @Test(groups = "short")
135+ @CassandraVersion(major = 2.0)
136+ void should_fail_if_computed_field_marked_with_column_annotation() {
137+ Mapper<User_WrongAnnotationForComputed> mapper = mappingManager.mapper(User_WrongAnnotationForComputed.class);
138+ try {
139+ mapper.save(new User_WrongAnnotationForComputed("test", "foo"));
140+ fail("Expected an InvalidQueryException");
141+ } catch (InvalidQueryException e) {/*expected*/}
142+
143+ try {
144+ User_WrongAnnotationForComputed saved = mapper.get(42);
145+ fail("Expected an InvalidQueryException");
146+ } catch (InvalidQueryException e) {/*expected*/}
147+ }
148+
149+ @Table(name = "user")
150+ public static class User {
151+ @PartitionKey
152+ private String login;
153+ private String name;
154+
155+ public User() {
156+ }
157+
158+ public User(String login, String name) {
159+ this.login = login;
160+ this.name = name;
161+ }
162+
163+ // quotes in the column name inserted on purpose
164+ // to test the alias generation mechanism
165+ @Computed(value = "writetime(\"name\")")
166+ long writeTime;
167+
168+ @Computed("ttl(name)")
169+ Integer ttl;
170+
171+ public String getLogin() {
172+ return login;
173+ }
174+
175+ public void setLogin(String login) {
176+ this.login = login;
177+ }
178+
179+ public String getName() {
180+ return name;
181+ }
182+
183+ public void setName(String name) {
184+ this.name = name;
185+ }
186+
187+ public long getWriteTime() {
188+ return writeTime;
189+ }
190+
191+ public void setWriteTime(long writeTime) {
192+ this.writeTime = writeTime;
193+ }
194+
195+ public Integer getTtl() {
196+ return ttl;
197+ }
198+
199+ public void setTtl(Integer ttl) {
200+ this.ttl = ttl;
201+ }
202+ }
203+
204+ @Accessor
205+ interface UserAccessor {
206+ @Query("select * from user")
207+ ResultSet all();
208+ }
209+
210+ @Table(name = "user")
211+ public static class User_WrongComputedType {
212+ @PartitionKey
213+ private String login;
214+ private String name;
215+
216+ @Column(name = "writetime(v)")
217+ byte writeTime;
218+
219+ public String getLogin() {
220+ return login;
221+ }
222+
223+ public void setLogin(String login) {
224+ this.login = login;
225+ }
226+
227+ public String getName() {
228+ return name;
229+ }
230+
231+ public void setName(String name) {
232+ this.name = name;
233+ }
234+
235+ public byte getWriteTime() {
236+ return writeTime;
237+ }
238+
239+ public void setWriteTime(byte writeTime) {
240+ this.writeTime = writeTime;
241+ }
242+ }
243+
244+ @Table(name = "user")
245+ public static class User_WrongAnnotationForComputed {
246+ @PartitionKey
247+ private String login;
248+ private String name;
249+
250+ @Column(name = "writetime(v)")
251+ long writeTime;
252+
253+ public User_WrongAnnotationForComputed() {
254+ }
255+
256+ public User_WrongAnnotationForComputed(String login, String name) {
257+ this.login = login;
258+ this.name = name;
259+ }
260+
261+ public String getLogin() {
262+ return login;
263+ }
264+
265+ public void setLogin(String login) {
266+ this.login = login;
267+ }
268+
269+ public String getName() {
270+ return name;
271+ }
272+
273+ public void setName(String name) {
274+ this.name = name;
275+ }
276+
277+ public long getWriteTime() {
278+ return writeTime;
279+ }
280+
281+ public void setWriteTime(long writeTime) {
282+ this.writeTime = writeTime;
283+ }
284+ }
285+}
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +397 −0
@@ -0,0 +1,397 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.mapping;
17+
18+import java.util.Collection;
19+import java.util.concurrent.ExecutionException;
20+
21+import com.google.common.collect.Lists;
22+import org.testng.SkipException;
23+import org.testng.annotations.BeforeMethod;
24+import org.testng.annotations.Test;
25+
26+import static com.datastax.driver.core.ConsistencyLevel.*;
27+import static org.assertj.core.api.Assertions.assertThat;
28+import static org.assertj.core.api.Assertions.fail;
29+
30+import com.datastax.driver.core.*;
31+import com.datastax.driver.core.exceptions.NoHostAvailableException;
32+import com.datastax.driver.core.exceptions.UnavailableException;
33+import com.datastax.driver.core.utils.CassandraVersion;
34+import com.datastax.driver.mapping.annotations.PartitionKey;
35+import com.datastax.driver.mapping.annotations.Table;
36+
37+import static com.datastax.driver.core.ProtocolVersion.V1;
38+import static com.datastax.driver.mapping.Mapper.Option;
39+
40+public class MapperOptionTest extends CCMBridge.PerClassSingleNodeCluster {
41+
42+ ProtocolVersion protocolVersion;
43+ Mapper<User> mapper;
44+
45+ @Override
46+ protected Collection<String> getTableDefinitions() {
47+ return Lists.newArrayList("CREATE TABLE user (key int primary key, v text)");
48+ }
49+
50+ @BeforeMethod(groups = "short")
51+ public void setup() {
52+ mapper = new MappingManager(session).mapper(User.class);
53+ protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
54+ }
55+
56+ @Test(groups = "short")
57+ @CassandraVersion(major = 2.0)
58+ void should_use_save_options() throws Exception {
59+ Long tsValue = futureTimestamp();
60+ mapper.save(new User(42, "helloworld"), Option.timestamp(tsValue), Option.tracing(true));
61+ assertThat(mapper.get(42).getV()).isEqualTo("helloworld");
62+ Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
63+ assertThat(tsReturned).isEqualTo(tsValue);
64+ }
65+
66+ @Test(groups = "short")
67+ @CassandraVersion(major = 2.0)
68+ void should_use_delete_options() {
69+ User todelete = new User(45, "todelete");
70+ mapper.save(todelete);
71+ Option opt = Option.timestamp(35);
72+ BoundStatement bs = (BoundStatement)mapper.deleteQuery(45, opt, Option.consistencyLevel(QUORUM));
73+ assertThat(bs.preparedStatement().getQueryString()).contains("USING TIMESTAMP");
74+ assertThat(bs.getConsistencyLevel()).isEqualTo(QUORUM);
75+ }
76+
77+ @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
78+ @CassandraVersion(major = 2.0)
79+ void should_use_get_options() {
80+ User user = new User(45, "toget");
81+ mapper.save(user);
82+
83+ BoundStatement bs = (BoundStatement)mapper.getQuery(45, Option.tracing(true), Option.consistencyLevel(ALL));
84+ assertThat(bs.isTracing()).isTrue();
85+ assertThat(bs.getConsistencyLevel()).isEqualTo(ALL);
86+
87+ ResultSet rs = session.execute(bs);
88+ assertThat(rs.getExecutionInfo().getQueryTrace()).isNotNull();
89+ User us = mapper.mapAliased(rs).one();
90+ assertThat(us.getV()).isEqualTo("toget");
91+
92+ mapper.getQuery(45, Option.timestamp(1337));
93+ }
94+
95+ @Test(groups = "short")
96+ @CassandraVersion(major = 2.0)
97+ void should_use_options_only_once() {
98+ Long tsValue = futureTimestamp();
99+ mapper.save(new User(43, "helloworld"), Option.timestamp(tsValue));
100+ mapper.save(new User(44, "test"));
101+ Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 44).one().getLong(0);
102+ // Assuming we cannot go back in time (yet) and execute the write at ts=1
103+ assertThat(tsReturned).isNotEqualTo(tsValue);
104+ }
105+
106+ @Test(groups = "short")
107+ @CassandraVersion(major = 2.0)
108+ void should_use_default_options() {
109+ mapper.setDefaultSaveOptions(Option.timestamp(644746L), Option.ttl(76324));
110+ BoundStatement bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"));
111+ assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP").contains("TTL");
112+
113+ mapper.resetDefaultSaveOptions();
114+ bs = (BoundStatement)mapper.saveQuery(new User(47, "rjhrgce"));
115+ assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP").doesNotContain("TTL");
116+
117+ mapper.setDefaultDeleteOptions(Option.timestamp(3245L), Option.tracing(true));
118+ bs = (BoundStatement)mapper.deleteQuery(47);
119+ assertThat(bs.preparedStatement().getQueryString()).contains("TIMESTAMP");
120+ assertThat(bs.isTracing()).isTrue();
121+
122+ mapper.resetDefaultDeleteOptions();
123+ bs = (BoundStatement)mapper.deleteQuery(47);
124+ assertThat(bs.preparedStatement().getQueryString()).doesNotContain("TIMESTAMP");
125+ assertThat(bs.isTracing()).isFalse();
126+
127+ bs = (BoundStatement)mapper.saveQuery(new User(46, "rjhrgce"), Option.timestamp(23), Option.consistencyLevel(ConsistencyLevel.ANY));
128+ assertThat(bs.getConsistencyLevel()).isEqualTo(ConsistencyLevel.ANY);
129+
130+ mapper.setDefaultGetOptions(Option.tracing(true));
131+ bs = (BoundStatement)mapper.getQuery(46);
132+ assertThat(bs.isTracing()).isTrue();
133+
134+ mapper.resetDefaultGetOptions();
135+ bs = (BoundStatement)mapper.getQuery(46);
136+ assertThat(bs.isTracing()).isFalse();
137+ }
138+
139+ @Test(groups = "short")
140+ @CassandraVersion(major = 2.0)
141+ void should_prioritize_option_over_model_consistency() {
142+ // Generate Write Query and ensure User model writeConsistency is used.
143+ User user = new User(1859, "Steve");
144+ Statement saveDefault = mapper.saveQuery(user);
145+ assertThat(saveDefault.getConsistencyLevel()).isEqualTo(ONE);
146+
147+ // Generate Write Query and ensure provided Option for consistencyLevel is used.
148+ Statement saveProvidedCL = mapper.saveQuery(user, Option.consistencyLevel(QUORUM));
149+ assertThat(saveProvidedCL.getConsistencyLevel()).isEqualTo(QUORUM);
150+
151+ // Generate Read Query and ensure User model readConsistency is used.
152+ Statement readDefault = mapper.getQuery(1859);
153+ assertThat(readDefault.getConsistencyLevel()).isEqualTo(LOCAL_ONE);
154+
155+ // Generate Ready Query and ensure provided Option for consistencyLevel is used.
156+ Statement readProvidedCL = mapper.getQuery(1859, Option.consistencyLevel(LOCAL_QUORUM));
157+ assertThat(readProvidedCL.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
158+ }
159+
160+ @Test(groups = "short")
161+ @CassandraVersion(major = 2.0)
162+ void should_use_explicit_options_over_default_options() {
163+ long defaultTimestamp = futureTimestamp();
164+ long explicitTimestamp = futureTimestamp();
165+
166+ mapper.setDefaultSaveOptions(Option.timestamp(defaultTimestamp));
167+
168+ mapper.save(new User(42, "helloworld"), Option.timestamp(explicitTimestamp));
169+ Long savedTimestamp = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
170+ assertThat(savedTimestamp).isEqualTo(explicitTimestamp);
171+ }
172+
173+ /** Cover all versions of save() to check that methods that call each other properly propagate the options */
174+ @Test(groups = "short")
175+ @CassandraVersion(major = 2.0)
176+ void should_use_save_options_for_all_variants() throws ExecutionException, InterruptedException {
177+ Long timestamp = futureTimestamp();
178+ User user = new User(42, "helloworld");
179+
180+ mapper.save(user, Option.timestamp(timestamp));
181+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
182+ mapper.delete(user.getKey());
183+
184+ mapper.saveAsync(user, Option.timestamp(timestamp)).get();
185+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
186+ mapper.delete(user.getKey());
187+
188+ session.execute(mapper.saveQuery(user, Option.timestamp(timestamp)));
189+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
190+ mapper.delete(user.getKey());
191+
192+ // Set as default and try optionless methods
193+ mapper.setDefaultSaveOptions(Option.timestamp(timestamp));
194+
195+ mapper.save(user);
196+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
197+ mapper.delete(user.getKey());
198+
199+ mapper.saveAsync(user).get();
200+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
201+ mapper.delete(user.getKey());
202+
203+ session.execute(mapper.saveQuery(user));
204+ assertThat(getWriteTime(user.getKey())).isEqualTo(timestamp);
205+ mapper.delete(user.getKey());
206+ }
207+
208+ private Long getWriteTime(int key) {
209+ Row row = session.execute("SELECT writetime(v) FROM user WHERE key=" + key).one();
210+ return row.getLong(0);
211+ }
212+
213+ @Test(groups = "short")
214+ @CassandraVersion(major = 2.0)
215+ void should_use_get_options_for_all_variants() throws InterruptedException {
216+ try {
217+ mapper.get(42, Option.consistencyLevel(TWO));
218+ fail("Expected a NoHostAvailableException");
219+ } catch (NoHostAvailableException e) {
220+ assertFirstNodeUnavailable(e);
221+ }
222+
223+ try {
224+ mapper.getAsync(42, Option.consistencyLevel(TWO)).get();
225+ fail("Expected an ExecutionException");
226+ } catch (ExecutionException e) {
227+ assertFirstNodeUnavailable(e);
228+ }
229+
230+ Statement statement = mapper.getQuery(42, Option.consistencyLevel(TWO));
231+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
232+
233+ // Set as default and try optionless methods
234+ mapper.setDefaultGetOptions(Option.consistencyLevel(TWO));
235+
236+ try {
237+ mapper.get(42);
238+ fail("Expected a NoHostAvailableException");
239+ } catch (NoHostAvailableException e) {
240+ assertFirstNodeUnavailable(e);
241+ }
242+
243+ try {
244+ mapper.getAsync(42).get();
245+ fail("Expected an ExecutionException");
246+ } catch (ExecutionException e) {
247+ assertFirstNodeUnavailable(e);
248+ }
249+
250+ statement = mapper.getQuery(42);
251+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
252+ }
253+
254+ @Test(groups = "short")
255+ @CassandraVersion(major = 2.0)
256+ void should_use_delete_options_for_all_variants() throws InterruptedException {
257+ User user = new User(42, "helloworld");
258+
259+ try {
260+ mapper.delete(user, Option.consistencyLevel(TWO));
261+ fail("Expected a NoHostAvailableException");
262+ } catch (NoHostAvailableException e) {
263+ assertFirstNodeUnavailable(e);
264+ }
265+
266+ try {
267+ mapper.deleteAsync(user, Option.consistencyLevel(TWO)).get();
268+ fail("Expected an ExecutionException");
269+ } catch (ExecutionException e) {
270+ assertFirstNodeUnavailable(e);
271+ }
272+
273+ Statement statement = mapper.deleteQuery(user, Option.consistencyLevel(TWO));
274+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
275+
276+ try {
277+ mapper.delete(user.getKey(), Option.consistencyLevel(TWO));
278+ fail("Expected a NoHostAvailableException");
279+ } catch (NoHostAvailableException e) {
280+ assertFirstNodeUnavailable(e);
281+ }
282+
283+ try {
284+ mapper.deleteAsync(user.getKey(), Option.consistencyLevel(TWO)).get();
285+ fail("Expected an ExecutionException");
286+ } catch (ExecutionException e) {
287+ assertFirstNodeUnavailable(e);
288+ }
289+
290+ statement = mapper.deleteQuery(user.getKey(), Option.consistencyLevel(TWO));
291+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
292+
293+ // Set as default and try optionless methods
294+ mapper.setDefaultDeleteOptions(Option.consistencyLevel(TWO));
295+
296+ try {
297+ mapper.delete(user);
298+ fail("Expected a NoHostAvailableException");
299+ } catch (NoHostAvailableException e) {
300+ assertFirstNodeUnavailable(e);
301+ }
302+
303+ try {
304+ mapper.deleteAsync(user).get();
305+ fail("Expected an ExecutionException");
306+ } catch (ExecutionException e) {
307+ assertFirstNodeUnavailable(e);
308+ }
309+
310+ statement = mapper.deleteQuery(user);
311+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
312+
313+ try {
314+ mapper.delete(user.getKey());
315+ fail("Expected a NoHostAvailableException");
316+ } catch (NoHostAvailableException e) {
317+ assertFirstNodeUnavailable(e);
318+ }
319+
320+ try {
321+ mapper.deleteAsync(user.getKey()).get();
322+ fail("Expected an ExecutionException");
323+ } catch (ExecutionException e) {
324+ assertFirstNodeUnavailable(e);
325+ }
326+
327+ statement = mapper.deleteQuery(user.getKey());
328+ assertThat(statement.getConsistencyLevel()).isEqualTo(TWO);
329+ }
330+
331+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
332+ void should_fail_if_option_does_not_apply_to_query() {
333+ mapper.get(42, Option.ttl(1));
334+ }
335+
336+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
337+ void should_fail_when_using_ttl_with_protocol_v1() {
338+ if (protocolVersion.compareTo(V1) > 0)
339+ throw new SkipException("Skipped when protocol version > V1");
340+
341+ mapper.saveQuery(new User(42, "helloworld"), Option.ttl(15));
342+ }
343+
344+ @Test(groups="short", expectedExceptions = IllegalArgumentException.class)
345+ void should_fail_when_using_timestamp_with_protocol_v1() {
346+ if (protocolVersion.compareTo(V1) > 0)
347+ throw new SkipException("Skipped when protocol version > V1");
348+
349+ mapper.saveQuery(new User(42, "helloworld"), Option.timestamp(15));
350+ }
351+
352+ private static void assertFirstNodeUnavailable(NoHostAvailableException e) {
353+ Throwable node1Error = e.getErrors().values().iterator().next();
354+ assertThat(node1Error).isInstanceOf(UnavailableException.class);
355+ }
356+
357+ private static void assertFirstNodeUnavailable(ExecutionException e) {
358+ Throwable cause = e.getCause();
359+ assertThat(cause).isInstanceOf(NoHostAvailableException.class);
360+ assertFirstNodeUnavailable((NoHostAvailableException) cause);
361+ }
362+
363+ private static long futureTimestamp() {
364+ return (System.currentTimeMillis() + 1000) * 1000;
365+ }
366+
367+ @Table(name = "user", readConsistency = "LOCAL_ONE", writeConsistency = "ONE")
368+ public static class User {
369+ @PartitionKey
370+ private int key;
371+ private String v;
372+
373+ public User() {
374+ }
375+
376+ public User(int k, String val) {
377+ this.key = k;
378+ this.v = val;
379+ }
380+
381+ public int getKey() {
382+ return this.key;
383+ }
384+
385+ public void setKey(int pk) {
386+ this.key = pk;
387+ }
388+
389+ public String getV() {
390+ return this.v;
391+ }
392+
393+ public void setV(String val) {
394+ this.v = val;
395+ }
396+ }
397+}
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperSaveNullFieldsTest.java +151 −0
@@ -0,0 +1,151 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.mapping;
17+
18+import java.util.Collection;
19+
20+import com.google.common.collect.Lists;
21+import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.BoundStatement;
27+import com.datastax.driver.core.CCMBridge;
28+import com.datastax.driver.mapping.Mapper.Option;
29+import com.datastax.driver.mapping.annotations.PartitionKey;
30+import com.datastax.driver.mapping.annotations.Table;
31+
32+public class MapperSaveNullFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
33+
34+ Mapper<User> mapper;
35+
36+ @Override
37+ protected Collection<String> getTableDefinitions() {
38+ return Lists.newArrayList("CREATE TABLE user (login text primary key, name text, phone text)");
39+ }
40+
41+ @BeforeMethod(groups = "short")
42+ public void setup() {
43+ mapper = new MappingManager(session).mapper(User.class);
44+ }
45+
46+ @Test(groups = "short")
47+ void should_save_null_fields_if_requested() {
48+ should_save_null_fields(true, Option.saveNullFields(true));
49+
50+ mapper.setDefaultSaveOptions(Option.saveNullFields(true));
51+ should_save_null_fields(true);
52+ }
53+
54+ @Test(groups = "short")
55+ void should_save_null_fields_by_default() {
56+ should_save_null_fields(true);
57+ }
58+
59+ @Test(groups = "short")
60+ void should_ignore_null_fields_if_requested() {
61+ should_save_null_fields(false, Option.saveNullFields(false));
62+
63+ mapper.setDefaultSaveOptions(Option.saveNullFields(false));
64+ should_save_null_fields(false);
65+ }
66+
67+ private void should_save_null_fields(boolean saveExpected, Option... options) {
68+ // Try different combinations of null fields
69+ should_save_null_fields(true, true, saveExpected, options);
70+ should_save_null_fields(true, false, saveExpected, options);
71+ should_save_null_fields(false, true, saveExpected, options);
72+ should_save_null_fields(false, false, saveExpected, options);
73+ }
74+
75+ private void should_save_null_fields(boolean nullName, boolean nullPhone, boolean saveExpected, Option... options) {
76+ // Start with clean data
77+ session.execute("insert into user(login, name, phone) "
78+ + "values ('test_login', 'previous_name', 'previous_phone')");
79+
80+ String newName = nullName ? null : "new_name";
81+ String newPhone = nullPhone ? null : "new_phone";
82+ String description = String.format("update with name=%s, phone = %s", newName, newPhone);
83+ User newUser = new User("test_login", newName, newPhone);
84+
85+ // Check if null fields are included in generated statement:
86+ BoundStatement bs = (BoundStatement)mapper.saveQuery(newUser, options);
87+ String queryString = bs.preparedStatement().getQueryString();
88+ if (nullName && !saveExpected)
89+ assertThat(queryString).as(description).doesNotContain("\"name\"");
90+ else
91+ assertThat(queryString).as(description).contains("\"name\"");
92+
93+ if (nullPhone && !saveExpected)
94+ assertThat(queryString).as(description).doesNotContain("\"phone\"");
95+ else
96+ assertThat(queryString).as(description).contains("\"phone\"");
97+
98+ // Save entity and check the data
99+ mapper.save(newUser, options);
100+ User savedUser = mapper.get("test_login");
101+ String expectedName = nullName
102+ ? (saveExpected ? null : "previous_name")
103+ : "new_name";
104+ String expectedPhone = nullPhone
105+ ? (saveExpected ? null : "previous_phone")
106+ : "new_phone";
107+ assertThat(savedUser.getName()).as(description).isEqualTo(expectedName);
108+ assertThat(savedUser.getPhone()).as(description).isEqualTo(expectedPhone);
109+ }
110+
111+ @Table(name = "user")
112+ public static class User {
113+ @PartitionKey
114+ private String login;
115+ private String name;
116+ private String phone;
117+
118+ public User() {
119+ }
120+
121+ public User(String login, String name, String phone) {
122+ this.login = login;
123+ this.name = name;
124+ this.phone = phone;
125+ }
126+
127+ public String getLogin() {
128+ return login;
129+ }
130+
131+ public void setLogin(String login) {
132+ this.login = login;
133+ }
134+
135+ public String getName() {
136+ return name;
137+ }
138+
139+ public void setName(String name) {
140+ this.name = name;
141+ }
142+
143+ public String getPhone() {
144+ return phone;
145+ }
146+
147+ public void setPhone(String phone) {
148+ this.phone = phone;
149+ }
150+ }
151+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +41 −0
@@ -16,12 +16,16 @@
1616 package com.datastax.driver.mapping;
1717
1818 import java.net.InetAddress;
19+
20+import com.datastax.driver.core.utils.CassandraVersion;
1921 import com.datastax.driver.mapping.annotations.Table;
2022 import java.util.*;
2123
2224 import com.google.common.base.Objects;
2325 import com.google.common.util.concurrent.ListenableFuture;
2426 import org.testng.annotations.Test;
27+
28+import static org.assertj.core.api.Assertions.assertThat;
2529 import static org.testng.Assert.*;
2630
2731 import com.datastax.driver.mapping.MapperTest.User.Gender;
@@ -310,6 +314,7 @@
310314 }
311315
312316 @Test(groups = "short")
317+ @CassandraVersion(major=2.0)
313318 public void testDynamicEntity() throws Exception {
314319 MappingManager manager = new MappingManager(session);
315320
@@ -377,4 +382,40 @@
377382 userAccessor.updateNameAndGender("Paule", null, u1.getUserId());
378383 assertEquals(userMapper.get(u1.getUserId()).getGender(), null);
379384 }
385+
386+ @Test(groups="short")
387+ public void should_map_objects_from_partial_queries() throws Exception {
388+ MappingManager manager = new MappingManager(session);
389+
390+ Mapper<Post> m = manager.mapper(Post.class);
391+
392+ // Insert a few posts
393+ User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
394+ Post p1 = new Post(u1, "Something about mapping");
395+ Post p2 = new Post(u1, "Something else");
396+ Post p3 = new Post(u1, "Something more");
397+
398+ p1.setDevice(InetAddress.getLocalHost());
399+ p2.setTags(new HashSet<String>(Arrays.asList("important", "keeper")));
400+
401+ m.save(p1);
402+ m.save(p2);
403+ m.save(p3);
404+
405+ // Retrieve posts with a projection query that only retrieves some of the fields
406+ ResultSet rs = session.execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
407+
408+ Result<Post> result = m.map(rs);
409+ for (Post post : result) {
410+ assertThat(post.getUserId()).isEqualTo(u1.getUserId());
411+ assertThat(post.getPostId()).isNotNull();
412+ assertThat(post.getTitle()).isNotNull();
413+
414+ assertThat(post.getDevice()).isNull();
415+ assertThat(post.getTags()).isNull();
416+ }
417+
418+ // cleanup
419+ session.execute("delete from posts where user_id = " + u1.getUserId());
420+ }
380421 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/UDTFieldMapperTest.java +2 −2
@@ -38,7 +38,7 @@
3838
3939 try {
4040 // Create type and table
41- ccm = CCMBridge.create("test", 1);
41+ ccm = CCMBridge.builder("test").build();
4242 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
4343 Session session1 = cluster.connect();
4444 session1.execute("create schema if not exists java_509 " +
@@ -85,7 +85,7 @@
8585
8686 try {
8787 // Create type and table
88- ccm = CCMBridge.create("test", 1);
88+ ccm = CCMBridge.builder("test").build();
8989 cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
9090 Session session1 = cluster.connect();
9191 session1.execute("create schema if not exists java_509 " +
added driver-mapping/src/test/resources/log4j.properties +28 −0
@@ -0,0 +1,28 @@
1+#
2+# Copyright (C) 2012-2015 DataStax Inc.
3+#
4+# Licensed under the Apache License, Version 2.0 (the "License");
5+# you may not use this file except in compliance with the License.
6+# You may obtain a copy of the License at
7+#
8+# http://www.apache.org/licenses/LICENSE-2.0
9+#
10+# Unless required by applicable law or agreed to in writing, software
11+# distributed under the License is distributed on an "AS IS" BASIS,
12+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+# See the License for the specific language governing permissions and
14+# limitations under the License.
15+#
16+
17+# Set root logger level to DEBUG and its only appender to A1.
18+log4j.rootLogger=INFO, A1
19+
20+# Scassandra's info log is a bit verbose
21+log4j.logger.org.scassandra=WARN
22+
23+# A1 is set to be a ConsoleAppender.
24+log4j.appender.A1=org.apache.log4j.ConsoleAppender
25+
26+# A1 uses PatternLayout.
27+log4j.appender.A1.layout=org.apache.log4j.PatternLayout
28+log4j.appender.A1.layout.ConversionPattern=\ %-6r [%t] %-5p %c %x - %m%n
added features/compression/README.md +88 −0
@@ -0,0 +1,88 @@
1+## Compression
2+
3+Cassandra's binary protocol supports optional compression of
4+transport-level requests and responses, for example:
5+
6+* a query with its serialized parameters;
7+* a [page](../paging/) from a result set, i.e. a list of serialized
8+ rows.
9+
10+It reduces network traffic at the cost of CPU overhead, therefore it
11+will likely be beneficial when you have larger payloads.
12+
13+Two algorithms are available:
14+[LZ4](https://github.com/jpountz/lz4-java) and
15+[Snappy](https://code.google.com/p/snappy/).
16+Both rely on third-party libraries, declared by the driver as *optional*
17+dependencies. So If you use a build tool like Maven, you'll need to
18+declare an explicit dependency to pull the appropriate library in your
19+application's classpath. Then you configure compression at driver
20+startup.
21+
22+### LZ4
23+
24+Maven dependency:
25+
26+```xml
27+<dependency>
28+ <groupId>net.jpountz.lz4</groupId>
29+ <artifactId>lz4</artifactId>
30+ <version>1.2.0</version>
31+</dependency>
32+```
33+
34+Always check the exact version of the library: go to the driver's
35+[parent POM][pom] (change the URL to match your driver version) and look
36+for the `lz4.version` property.
37+
38+Driver configuration:
39+
40+```java
41+cluster = Cluster.builder()
42+ .addContactPoint("127.0.0.1")
43+ .withCompression(ProtocolOptions.Compression.LZ4)
44+ .build();
45+```
46+
47+LZ4-java has three internal implementations (from fastest to slowest):
48+
49+* JNI;
50+* pure Java using sun.misc.Unsafe;
51+* pure Java using only "safe" classes.
52+
53+It will pick the best implementation depending on what's possible on
54+your platform. To find out which one was chosen, [enable INFO
55+logs](../logging/) on the category
56+`com.datastax.driver.core.FrameCompressor` and look for a log similar to
57+this:
58+
59+```
60+INFO com.datastax.driver.core.FrameCompressor - Using LZ4Factory:JNI
61+```
62+
63+### Snappy
64+
65+Maven dependency:
66+
67+```xml
68+<dependency>
69+ <groupId>org.xerial.snappy</groupId>
70+ <artifactId>snappy-java</artifactId>
71+ <version>1.0.5</version>
72+</dependency>
73+```
74+
75+Always check the exact version of the library: go to the driver's
76+[parent POM][pom] (change the URL to match your driver version) and look
77+for the `snappy.version` property.
78+
79+Driver configuration:
80+
81+```java
82+cluster = Cluster.builder()
83+ .addContactPoint("127.0.0.1")
84+ .withCompression(ProtocolOptions.Compression.SNAPPY)
85+ .build();
86+```
87+
88+[pom]: https://repo1.maven.org/maven2/com/datastax/cassandra/cassandra-driver-parent/2.2.0-rc1/cassandra-driver-parent-2.2.0-rc1.pom
modified features/native_protocol/README.md +1 −1
@@ -7,7 +7,7 @@
77 aspect is that some features are only available with specific protocol
88 versions.
99
10-[native_spec]: https://git-wip-us.apache.org/repos/asf?p=cassandra.git;a=tree;f=doc;hb=HEAD
10+[native_spec]: https://github.com/apache/cassandra/tree/trunk/doc
1111
1212 ### Compatibility matrix
1313
added features/object_mapper/README.md +18 −0
@@ -0,0 +1,18 @@
1+# Object Mapper
2+
3+Version 2.1 of the driver introduces a simple object mapper, which
4+avoids most of the boilerplate when converting your domain classes to
5+and from query results. It handles basic CRUD operations in Cassandra tables
6+containing UDTs, collections and all native CQL types.
7+
8+The mapper is published as a separate Maven artifact:
9+
10+```xml
11+<dependency>
12+ <groupId>com.datastax.cassandra</groupId>
13+ <artifactId>cassandra-driver-mapping</artifactId>
14+ <version>2.2.0-rc1</version>
15+</dependency>
16+```
17+
18+This documentation is organized in subsections describing mapper features.
added features/object_mapper/creating/README.md +246 −0
@@ -0,0 +1,246 @@
1+## Definition of mapped classes
2+
3+The object mapper is configured by annotations on the mapped classes.
4+
5+### Creating a table entity
6+
7+A table entity is a class that will be mapped to a table in Cassandra.
8+It is annotated with [@Table][table]:
9+
10+```
11+CREATE TABLE user (user_id uuid PRIMARY KEY, name text);
12+```
13+
14+```java
15+@Table(keyspace = "ks", name = "users",
16+ readConsistency = "QUORUM",
17+ writeConsistency = "QUORUM",
18+ caseSensitiveKeyspace = false,
19+ caseSensitiveTable = false)
20+public static class User {
21+ @PartitionKey
22+ @Column(name = "user_id")
23+ private UUID userId;
24+ private String name;
25+ // ... constructors / getters / setters
26+}
27+```
28+
29+`@Table` takes the following options:
30+
31+- `keyspace`: the keyspace for the table.
32+- `name`: the name of the table in the database.
33+- `caseSensitiveKeyspace`: whether the keyspace name is [case-sensitive].
34+- `caseSensitiveTable`: whether the table name is [case-sensitive].
35+- `readConsistency`: the [consistency level] that will be used on each
36+ get operation in the mapper. (if unspecified, it defaults to the
37+ cluster-wide setting)
38+- `writeConsistency`: the [consistency level] that will be used on each
39+ save, or delete operation in the mapper. (if unspecified, it defaults
40+ to the cluster-wide setting)
41+
42+The class must provide a default constructor, and all fields (except the
43+ones annotated `@Transient`) must have corresponding setters and
44+getters.
45+
46+[table]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Table.html
47+[case-sensitive]:http://docs.datastax.com/en/cql/3.2/cql/cql_reference/ucase-lcase_r.html
48+[consistency level]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/ConsistencyLevel.html
49+
50+#### Column names
51+
52+By default, the mapper tries to map each Java property to a
53+case insensitive column of the same name. If you want to use a different
54+name, or [case-sensitive] names, use the [@Column][column] annotation on
55+the field.
56+
57+[column]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Column.html
58+
59+#### Primary key fields
60+
61+[@PartitionKey][pk] and [@ClusteringColumn][cc] are used to indicate the
62+[partition key][pks] and [clustering columns][pks]. In the case of a
63+composite partition key or multiple clustering columns, the integer
64+value indicates the position of the column in the key:
65+
66+```
67+CREATE TABLE sales(countryCode text, areaCode text, sales int,
68+ PRIMARY KEY((countryCode, area Code)));
69+```
70+
71+```java
72+@PartitionKey(0)
73+private String countryCode;
74+@PartitionKey(1)
75+private String areaCode;
76+```
77+
78+The order of the indices must match that of the columns in the table
79+declaration.
80+
81+[pk]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/PartitionKey.html
82+[cc]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/ClusteringColumn.html
83+[pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html
84+
85+#### Enumerations
86+
87+[@Enumerated][enum] is used to map Java enumerations. Since Cassandra
88+does not support enumerations, the object mapper defines two ways to
89+persist an enum value :
90+
91+- `EnumType.ORDINAL` : the value is persisted as a Cassandra's `int` and
92+ its value is its position in the enum.
93+- `EnumType.STRING` : the value is persisted as a Cassandra's `text` and
94+ its value is its name in the enum.
95+
96+According to the chosen type, the matching database column must be the
97+same type.
98+
99+```
100+CREATE TABLE person (id uuid PRIMARY KEY, name text, gender int);
101+```
102+
103+```java
104+@Enumerated(EnumType.ORDINAL)
105+private Gender gender;
106+```
107+
108+[enum]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Enumerated.html
109+
110+#### Computed fields
111+
112+[@Computed][computed] can be used on fields that are the result of a
113+computation on the Cassandra side. Typically a function call. Native
114+functions in Cassandra like `writetime()` or [User Defined Functions] are
115+supported.
116+
117+```java
118+@Computed("ttl(name)")
119+Integer ttl;
120+```
121+
122+The CQL return type of function must match the type of the field,
123+otherwise an exception will be thrown.
124+
125+Computed fields are ignored when saving an entity.
126+
127+`@Computed` does not support case-sensitivity. If the expression
128+contains case-sensitive column or function names, you'll have to escape
129+them:
130+
131+```java
132+@Computed("\"myFunction\"(\"myColumn\")")
133+int f;
134+```
135+
136+Finally, computed fields are only supported with [basic read
137+operations](../using/#basic-crud-operations) at this time.
138+Support in [accessors](../using/#accessors) in planned for a future
139+version (see
140+[JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)).
141+
142+[User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/
143+[computed]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Computed.html
144+
145+#### Transient fields
146+
147+[@Transient][transient] can be used to prevent a field from being mapped.
148+
149+[transient]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Transient.html
150+
151+### Mapping User Types
152+
153+[User Defined Types] can also be mapped by using [@UDT][udt]:
154+
155+```
156+CREATE TYPE address (street text, zip_code int);
157+```
158+
159+```java
160+@UDT(keyspace = "ks", name = "address")
161+class Address {
162+ private String street;
163+ @Field(name = "zip_code")
164+ private int zipCode;
165+ // ... constructors / getters / setters
166+}
167+```
168+
169+`@UDT` takes the following options:
170+
171+- `keyspace`: the keyspace for the UDT.
172+- `name`: the name of the UDT in the database.
173+- `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive.
174+- `caseSensitiveType`: whether the UDT name is case-sensitive.
175+
176+The class must provide a default constructor, and all fields (except the
177+ones annotated `@Transient`) must have corresponding setters and
178+getters.
179+
180+As in table entities, fields are mapped to an UDT field of the same
181+name by default. To declare a different name or use case-sensitivity,
182+use the [@Field][field] annotation:
183+
184+```java
185+@Field(name = "zip_code")
186+private int zipCode;
187+```
188+
189+When a table has a UDT column, the mapper will automatically map it to
190+the corresponding class:
191+
192+```
193+CREATE TABLE company (company_id uuid PRIMARY KEY, name text, address address);
194+```
195+
196+```java
197+public static class Company {
198+ @PartitionKey
199+ @Column(name = "company_id")
200+ private UUID companyId;
201+ private String name;
202+ private Address address;
203+}
204+```
205+
206+(this also works with UDTs inside collections or other UDTs, with
207+arbitrary level of nesting)
208+
209+[User Defined Types]:http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/reference/userDefinedTypes.html
210+[udt]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/UDT.html
211+[field]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Field.html
212+
213+### Mapping collections
214+
215+Java collections will be automatically mapped into corresponding
216+Cassandra types. As in Cassandra, collections can contain all native
217+types and all [user types](#mapping-user-types) previously defined is
218+the database.
219+
220+Collection fields must be annotated to indicate whether they are frozen
221+or not (currently this is only for informational purposes, but the
222+mapper will check that the declared state match the rules in Cassandra).
223+The default annotation is [@Frozen][frozen], [@FrozenKey][frozenkey] and
224+[@FrozenValue][frozenvalue]` are also provided for convenience:
225+
226+```java
227+// Will be mapped as a 'list<text>'
228+private List<String> stringList;
229+
230+// Will be mapped as a 'frozen<list<text>>'
231+@Frozen
232+private List<String> frozenStringList;
233+
234+// Will be mapped as 'map<frozen<address>, frozen<list<text>>>'
235+@FrozenKey
236+@FrozenValue
237+private Map<Address, List<String>> frozenKeyValueMap;
238+
239+// Will be mapped as 'map<text, frozen<list<address>>>'
240+@FrozenValue
241+private Map<String, List<Address>> frozenValueMap;
242+```
243+
244+[frozen]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Frozen.html
245+[frozenkey]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/FrozenKey.html
246+[frozenvalue]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/FrozenValue.html
added features/object_mapper/using/README.md +312 −0
@@ -0,0 +1,312 @@
1+## Using the mapper
2+
3+First, create a [MappingManager]. It wraps an existing [Session]
4+instance:
5+
6+```java
7+MappingManager manager = new MappingManager(session);
8+```
9+
10+`MappingManager` is thread-safe and can be safely shared throughout your
11+application. You would typically create one instance at startup, right
12+after your `Session`.
13+
14+Note that `MappingManager` will initialize the `Session` if not
15+previously done (this was not the case in previous driver versions; if
16+this is a problem for you, see `MappingManager(session, protocolVersion)`).
17+
18+### Entity mappers
19+
20+Each entity class (annotated with `@Table`) is managed by a dedicated
21+[Mapper] object. You obtain this object from the `MappingManager`:
22+
23+```java
24+Mapper<User> mapper = manager.mapper(User.class);
25+```
26+
27+`Mapper` objects are thread-safe. The manager caches them internally, so
28+calling `manager#mapper` more than once for the same class will return
29+the previously generated mapper.
30+
31+[Mapper]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/Mapper.html
32+[MappingManager]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/MappingManager.html
33+[Session]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/Session.html
34+
35+#### Basic CRUD operations
36+
37+To save an object, use `Mapper#save`:
38+
39+```java
40+UUID userId = ...;
41+User u = new User(userId, "John Doe", new Address("street", 01000));
42+mapper.save(u);
43+```
44+
45+--------------
46+
47+To retrieve an object, use `Mapper#get`:
48+
49+```java
50+UUID userId = ...;
51+User u = mapper.get(userId);
52+```
53+
54+`get`'s arguments must match the partition key components (number of
55+arguments and their types).
56+
57+--------------
58+
59+To delete a row in a table, use `Mapper#delete`. This method support
60+deleting a row given either its primary keys, or the object to delete:
61+
62+```java
63+UUID userId = ...;
64+mapper.delete(userId);
65+mapper.delete(u);
66+```
67+
68+--------------
69+
70+All these CRUD operations are synchronous, but the `Mapper` provides
71+their asynchronous equivalents:
72+
73+```java
74+ListenableFuture<Void> saveFuture = mapper.saveAsync(u);
75+ListenableFuture<User> userFuture = mapper.getAsync(userId);
76+ListenableFuture<Void> deleteFuture = mapper.deleteAsync(userId);
77+```
78+
79+#### Mapper options
80+
81+The basic CRUD operations accept additional options to customize the
82+underlying query:
83+
84+- `ttl`: add a time-to-live value for the operation.
85+- `timestamp`: add a timestamp value for the operation.
86+- `consistencyLevel`: specify a consistency level.
87+- `tracing`: set tracing flag for the query.
88+- `saveNullFields`: if set to true, fields with value `null` in an
89+ instance that is to be persisted, will be explicitly written as `null`
90+ in the query. If set to false, fields with null value won't be included
91+ in the write query (thus avoiding tombstones).
92+
93+To use options, add them to the mapper call after regular parameters:
94+
95+```java
96+import static com.datastax.driver.mapping.Mapper.Option.*;
97+
98+mapper.save(new User(userId, "helloworld"),
99+ timestamp(123456L), tracing(true), ttl(42));
100+```
101+
102+Some options don't apply to all operations:
103+
104+<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
105+ <tr> <td><b>Option</b></td> <td><b>save/saveQuery</b></td> <td><b>get/getQuery</b></td> <td><b>delete/deleteQuery</b></td></tr>
106+ <tr> <td>Ttl</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
107+ <tr> <td>Timestamp</td> <td>yes</td> <td>no</td> <td>yes</td> </tr>
108+ <tr> <td>ConsistencyLevel</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
109+ <tr> <td>Tracing</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
110+ <tr> <td>SaveNullFields</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
111+</table>
112+
113+Note that `Option.consistencyLevel` is redundant with the consistency
114+level defined by [@Table](../creating/#creating-a-table-entity).
115+If both are defined, the option will take precedence over the
116+annotation.
117+
118+Default options can be defined for each type of operation:
119+
120+```java
121+mapper.setDefaultGetOption(tracing(true), consistencyLevel(QUORUM));
122+mapper.setDefaultSaveOption(saveNullFields(false));
123+mapper.setDefaultDeleteOption(consistencyLevel(ONE));
124+
125+// Given the defaults above, this will use tracing(true), consistencyLevel(ONE)
126+mapper.get(uuid, consistencyLevel(ONE));
127+```
128+
129+To reset default options, use the following methods:
130+
131+```java
132+mapper.resetDefaultGetOption();
133+mapper.resetDefaultSaveOption();
134+mapper.resetDefaultDeleteOption();
135+```
136+
137+#### Access to underlying `Statement`s
138+
139+Instead of performing an operation directly, it's possible to ask the
140+`Mapper` to just return the corresponding `Statement` object. This gives
141+the client a chance to customize the statement before executing it.
142+
143+- `Mapper.saveQuery(entity)`: returns a statement generated by the
144+ mapper to save `entity` into the database.
145+- `Mapper.getQuery(userId)`: returns a statement to select a row in the
146+ database, selected on the given `userId`, and matching the mapped
147+ object structure.
148+- `Mapper.deleteQuery(userID)`: returns a statement delete a row in the
149+ database given the `userId` provided. This method can also accept a
150+ mapped object instance.
151+
152+#### Manual mapping
153+
154+`Mapper#map` provides a way to converts the results of a regular query:
155+
156+```java
157+ResultSet results = session.execute("SELECT * FROM user");
158+Result<User> users = mapper.map(results);
159+for (User u : users) {
160+ System.out.println("User : " + u.getUserId());
161+}
162+```
163+
164+This method will ignore:
165+
166+* extra columns in the `ResultSet` that are not mapped for this entity.
167+* mapped fields that are not present in the `ResultSet` (setters won't
168+ be called so the value will be the one after invocation of the class's
169+ default constructor).
170+
171+[Result] is similar to `ResultSet` but for a given mapped class.
172+It provides methods `one()`, `all()`, `iterator()`, `getExecutionInfo()`
173+and `isExhausted()`. Note that iterating the `Result` will consume the
174+`ResultSet`, and vice-versa.
175+
176+[Result]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/Result.html
177+
178+### UDT Mappers
179+
180+A UDT will be automatically mapped when it is part of a table-level
181+class (as shown [here](../creating/#mapping-user-types)).
182+
183+However, there might be cases where it is useful to convert a mapped
184+instance to the corresponding [UDTValue][UDTValue] (and back). The
185+mapper provides an [UDTMapper] for that purpose:
186+
187+```java
188+UDTMapper<Address> addressMapper = manager.getUDTMapper(Address.class);
189+Address address = addressMapper.fromUDT(udtValue);
190+UDTValue value = addressMapper.toUDT(address);
191+```
192+
193+[UDTValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UDTValue.html
194+[UDTMapper]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/UDTMapper.html
195+
196+### Accessors
197+
198+`Accessor`s provide a way to map custom queries not supported by the
199+default entity mappers.
200+
201+To create an accessor, define a Java interface and annotate each method
202+to provide the corresponding CQL query:
203+
204+```java
205+@Accessor
206+public interface UserAccessor {
207+ @Query("SELECT * FROM user")
208+ Result<User> getAll();
209+}
210+```
211+
212+The `MappingManager` can then process this class and generate an
213+implementation:
214+
215+```java
216+UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
217+User user = userAccessor.getOne(uuid);
218+```
219+
220+Like mappers, accessors are cached at the manager level and thus, are
221+thread-safe/sharable.
222+
223+#### Parameters
224+
225+A query can have bind markers, that will be set with the method's
226+arguments.
227+
228+With unnamed markers, the order of the arguments must match the order of
229+the markers:
230+
231+```java
232+@Query("insert into user (id, name) values (?, ?)")
233+ResultSet insert(UUID userId, String name);
234+```
235+
236+With named markers, use [@Param][param] to indicate which parameter
237+corresponds to which marker:
238+
239+```java
240+@Query("insert into user (userId, name) values (:u, :n)")
241+ResultSet insert(@Param("u") UUID userId, @Param("n") String name);
242+```
243+
244+[param]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Param.html
245+
246+If a method argument is a Java enumeration, it must be annotated with
247+`@Enumerated` to indicate how to convert it to a CQL type (the rules are
248+the same as in [mapping definition](http://localhost:9090/features/object_mapper/creating/#enumerations)):
249+
250+```java
251+@Query("insert into user (key, gender) values (?,?)")
252+ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value);
253+```
254+
255+#### Return type
256+
257+The declared return type of each method affects how the query will get
258+executed:
259+
260+<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
261+ <tr> <td><b>Return type</b></td> <td><b>Effect</b></td> </tr>
262+ <tr>
263+ <td><code>void</code></td>
264+ <td>Synchronous execution, discards the results of the query.</td>
265+ </tr>
266+ <tr>
267+ <td><code>ResultSet</code></td>
268+ <td>Synchronous execution, returns unmapped results.</td>
269+ </tr>
270+ <tr>
271+ <td><code>T</code></td>
272+ <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns the first row (or <code>null</code> if there are no results).</td>
273+ </tr>
274+ <tr>
275+ <td><code>Result&lt;T&gt;</code></td>
276+ <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns a list of mapped objects.</td>
277+ </tr>
278+ <tr>
279+ <td><code>ResultSetFuture</code></td>
280+ <td>Asynchronous execution, returns unmapped results.</td>
281+ </tr>
282+ <tr>
283+ <td><code>ListenableFuture&lt;T&gt;</code></td>
284+ <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns the first row (or <code>null</code> if there are no results).</td>
285+ </tr>
286+ <tr>
287+ <td><code>ListenableFuture&lt;Result&lt;T&gt;&gt;</code></td>
288+ <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns a list of mapped objects.</td>
289+ </tr>
290+</table>
291+
292+Example:
293+
294+```java
295+@Query("SELECT * FROM user")
296+public ListenableFuture<Result<User>> getAllAsync();
297+```
298+
299+
300+#### Customizing the statement
301+
302+It is possible to customize query parameters to include in a `Accessor`
303+query with the annotation [@QueryParameters]. Then, options like
304+*consistency level*, *fetchsize* or *tracing* are settable:
305+
306+```java
307+@Query("SELECT * FROM ks.users")
308+@QueryParameters(consistency="QUORUM")
309+public ListenableFuture<Result<User>> getAllAsync();
310+```
311+
312+[@QueryParameters]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/QueryParameters.html
modified features/pooling/README.md +119 −61
@@ -7,7 +7,7 @@
77 connection to handle multiple simultaneous requests:
88
99 * when a query gets executed, a *stream id* gets assigned to it. It is a
10- unique identifier for the current connection;
10+ unique identifier on the current connection;
1111 * the driver writes a request containing the stream id and the query on
1212 the connection, and then proceeds without waiting for the response (if
1313 you're using the asynchronous API, this is when the driver will send you
@@ -23,19 +23,17 @@
2323 connections to each host. **For each `Session` object, there is one
2424 connection pool per connected host**.
2525
26-The number of connections and stream ids depends on the [native protocol
27-version](../native_protocol/):
26+The number of connections per pool is configurable (this will be
27+described in the next section). The number of stream ids depends on the
28+[native protocol version](../native_protocol/):
2829
29-* **protocol v2 or below**: there are **128 stream ids per connection.**
30- The number of connections per pool is configurable (this will be
31- described in the next section).
32-* v3 or above: there are **up to 32768 stream ids per connection**, and
33- **1 connection per pool**.
30+* protocol v2 or below: 128 stream ids per connection.
31+* protocol v3 or above: up to 32768 stream ids per connection.
3432
3533 ```ditaa
36-+-------+1 n+-------+1 n+----+1 n/1+----------+1 128/32K+-------+
37-|Cluster+-----+Session+-----+Pool+-------+Connection+-----------+Request+
38-+-------+ +-------+ +----+ +----------+ +-------+
34++-------+1 n+-------+1 n+----+1 n+----------+1 128/32K+-------+
35+|Cluster+-----+Session+-----+Pool+-----+Connection+-----------+Request+
36++-------+ +-------+ +----+ +----------+ +-------+
3937 ```
4038
4139 ### Configuring the connection pool
@@ -62,7 +60,7 @@
6260 // customize options...
6361 ```
6462
65-#### Pool size (protocol v2 only)
63+#### Pool size
6664
6765 Connection pools have a variable size, which gets adjusted automatically
6866 depending on the current load. There will always be at least a *core*
@@ -79,36 +77,73 @@
7977 .setMaxConnectionsPerHost( HostDistance.REMOTE, 4);
8078 ```
8179
82-Note: the setters always enforce core <= max, which can get annoying
83-when you try to set both values at once.
84-[JAVA-662](https://datastax-oss.atlassian.net/browse/JAVA-662) will
85-address this issue.
86-
87-[PoolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold][msrpct]
88-has a slightly misleading name: it does not limit the number of requests per
89-connection, but only determines the threshold that triggers the creation
90-of a new connection when the pool is not at its maximum capacity. In
91-general, you shouldn't have to change its default value.
92-
93-#### Number of simultaneous requests per host (protocol v3 only)
94-
95-Protocol v3 uses a single connection per host. While the number of
96-simultaneous requests can go up to 32768, it is limited by
97-[PoolingOptions.setMaxSimultaneousRequestsPerHostThreshold][msrpht]. The
98-goal of this option is to throttle the load that each client can
99-generate on the server. By default, it is set to 1024 for local hosts,
100-and 256 for remote hosts (this was chosen to match the capacity of a v2
101-pool with the default configuration).
102-
103-If your performance tests show that your cluster can handle a higher
104-load, you can raise this threshold:
80+For convenience, core and max can be set simultaneously:
10581
10682 ```java
10783 poolingOptions
108- .setMaxSimultaneousRequestsPerHostThreshold(HostDistance.LOCAL, 20000)
109- .setMaxSimultaneousRequestsPerHostThreshold(HostDistance.REMOTE, 1000);
84+ .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
85+ .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
11086 ```
11187
88+The default settings are:
89+
90+* protocol v2:
91+ * `LOCAL` hosts: core = 2, max = 8
92+ * `REMOTE` hosts: core = 1, max = 2
93+* protocol v3:
94+ * `LOCAL` hosts: core = max = 1
95+ * `REMOTE` hosts: core = max = 1
96+
97+[PoolingOptions.setNewConnectionThreshold][nct] determines the threshold
98+that triggers the creation of a new connection when the pool is not at
99+its maximum capacity. In general, you shouldn't need to change its
100+default value.
101+
102+#### Dynamic resizing
103+
104+If core != max, the pool will resize automatically to adjust to the
105+current activity on the host.
106+
107+When activity goes up and there are *n* connections with n < max, the driver
108+will add a connection when the number of concurrent requests is more than
109+(n - 1) * 128 + [PoolingOptions.setNewConnectionThreshold][nct]
110+(in layman's terms, when all but the last connection are full and the last
111+connection is above the threshold).
112+
113+When activity goes down, the driver will "trash" connections if the maximum
114+number of requests in a 10 second time period can be satisfied by less than
115+the number of connections opened. Trashed connections are kept open but do
116+not accept new requests. After a given timeout (defined by
117+[PoolingOptions.setIdleTimeoutSeconds][sits]), trashed connections are closed
118+and removed. If during that idle period activity increases again, those
119+connections will be resurrected back into the active pool and reused. The
120+main intent of that is to not constantly recreate connections if activity
121+changes quickly over an interval.
122+
123+#### Simultaneous requests per connection
124+
125+[PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to
126+throttle the number of concurrent requests per connection.
127+
128+With protocol v2, there is no reason to throttle. It is set to 128 (the
129+max) and you should not change it.
130+
131+With protocol v3, it is set to 1024 for `LOCAL` hosts, and 256 for
132+`REMOTE` hosts. These low defaults were chosen so that the default
133+configuration for protocol v2 and v3 allow the same total number of
134+simultaneous requests (to avoid bad surprises when clients migrate from
135+v2 to v3). You can raise this threshold, or even set it to the max:
136+
137+```java
138+poolingOptions
139+ .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768)
140+ .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000);
141+```
142+
143+Just keep in mind that high values will give clients more bandwidth and
144+therefore put more pressure on your cluster. This might require some
145+tuning, especially if you have many clients.
146+
112147 #### Heartbeat
113148
114149 If connections stay idle for too long, they might be dropped by
@@ -173,24 +208,11 @@
173208 ```java
174209 final LoadBalancingPolicy loadBalancingPolicy =
175210 cluster.getConfiguration().getPolicies().getLoadBalancingPolicy();
176-PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
177-ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions();
178-
179-final Map<HostDistance, Integer> requestsPerConnection;
180-ProtocolVersion protocolVersion = protocolOptions.getProtocolVersionEnum();
181-if (protocolVersion == ProtocolVersion.V3) {
182- requestsPerConnection = ImmutableMap.of(
183- HostDistance.LOCAL,
184- poolingOptions.getMaxSimultaneousRequestsPerHostThreshold(HostDistance.LOCAL),
185- HostDistance.REMOTE,
186- poolingOptions.getMaxSimultaneousRequestsPerHostThreshold(HostDistance.REMOTE));
187-} else {
188- requestsPerConnection = ImmutableMap.of(
189- HostDistance.LOCAL, 128,
190- HostDistance.REMOTE, 128);
191-}
192-
193-ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
211+final PoolingOptions poolingOptions =
212+cluster.getConfiguration().getPoolingOptions();
213+
214+ScheduledExecutorService scheduled =
215+Executors.newScheduledThreadPool(1);
194216 scheduled.scheduleAtFixedRate(new Runnable() {
195217 @Override
196218 public void run() {
@@ -199,9 +221,11 @@
199221 HostDistance distance = loadBalancingPolicy.distance(host);
200222 int connections = state.getOpenConnections(host);
201223 int inFlightQueries = state.getInFlightQueries(host);
202- System.out.printf("%s connections=%d current load=%d max load=%d%n",
224+ System.out.printf("%s connections=%d, current load=%d, max
225+load=%d%n",
203226 host, connections, inFlightQueries,
204- connections * requestsPerConnection.get(distance));
227+ connections *
228+poolingOptions.getMaxRequestsPerConnection(distance));
205229 }
206230 }
207231 }, 5, 5, TimeUnit.SECONDS);
@@ -213,18 +237,52 @@
213237
214238 If you find that the current load stays close or equal to the maximum
215239 load at all time, it's a sign that your connection pools are saturated
216-and you should raise the max connections per host (protocol v2) or max
217-requests per host (protocol v3).
240+and you should raise the max connections per host, or max requests per
241+connection (protocol v3).
218242
219243 If you're using protocol v2 and the load is often less than core * 128,
220244 your pools are underused and you could get away with less core
221245 connections.
222246
247+#### Tuning protocol v3 for very high throughputs
248+
249+As mentioned above, the default pool size for protocol v3 is core = max
250+= 1. This means all requests to a given node will share a single
251+connection, and therefore a single Netty I/O thread.
252+
253+There is a corner case where this I/O thread can max out its CPU core
254+and become a bottleneck in the driver; in our benchmarks, this happened
255+with a single-node cluster and a high throughput (approximately 80K
256+requests / second).
257+
258+It's unlikely that you'll run into this issue: in most real-world
259+deployments, the driver connects to more than one node, so the load will
260+spread across more I/O threads. However if you suspect that you
261+experience the issue, here's what to look out for:
262+
263+* the driver throughput plateaus but the process does not appear to
264+ max out any system resource (in particular, overall CPU usage is well
265+ below 100%);
266+* one of the driver's I/O threads maxes out its CPU core. You can see
267+ that with a profiler, or OS-level tools like `pidstat -tu` on Linux.
268+ I/O threads are called `<cluster_name>-nio-worker-<n>`, unless you're
269+ injecting your own `EventLoopGroup` with `NettyOptions`.
270+
271+The solution is to add more connections per node. To ensure that
272+additional connections get created before you run into the bottleneck,
273+either:
274+
275+* set core = max;
276+* keep core = 1, but adjust [maxRequestsPerConnection][mrpc] and
277+ [newConnectionThreshold][nct] so that enough connections are added by
278+ the time you reach the bottleneck.
279+
223280 [result_set_future]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/ResultSetFuture.html
224281 [pooling_options]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/PoolingOptions.html
225282 [lbp]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/policies/LoadBalancingPolicy.html
226-[msrpct]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/PoolingOptions.html#setMaxSimultaneousRequestsPerConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
227-[msrpht]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/PoolingOptions.html#setMaxSimultaneousRequestsPerHostThreshold(com.datastax.driver.core.HostDistance,%20int)
283+[nct]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
284+[mrpc]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection(com.datastax.driver.core.HostDistance,%20int)
285+[sits]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds(int)
228286 [rtm]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis()
229287 [exec_async]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement)
230288 [ptm]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
modified features/shaded_jar/README.md +1 −1
@@ -10,7 +10,7 @@
1010
1111 ```xml
1212 <dependency>
13- <groupId>${project.groupId}</groupId>
13+ <groupId>com.datastax.cassandra</groupId>
1414 <artifactId>cassandra-driver-core</artifactId>
1515 <version>2.2.0-rc1</version>
1616 <classifier>shaded</classifier>
modified features/speculative_execution/README.md +14 −9
@@ -78,12 +78,14 @@
7878 about what the query actually does. Therefore:
7979
8080 * **`Statement#isIdempotent()` is only computed automatically for
81- statements built with [QueryBuilder][QueryBuilder]**. Note that there
82- is a known issue in 2.2.0-rc1 where calls to `now()` or `uuid()` are not
83- taken into account (see
84- [JAVA-733](https://datastax-oss.atlassian.net/browse/JAVA-733)). If
85- you're using these CQL functions with built statements, force
86- idempotence to `false` manually (see below);
81+ statements built with [QueryBuilder][QueryBuilder]**.
82+ Note that the driver takes a rather conservative approach with uses
83+ of `fcall()` or `raw()`: whenever they appear in a value to be
84+ inserted in the database (like the values of an `Insert` or the
85+ right-hand side of an assignment in an `Update`), the statement
86+ will be considered non-idempotent by default. If you know that your
87+ CQL functions or expressions are safe, force idempotence to `true`
88+ on the statement manually (see below);
8789 * **for all other types of statements, it defaults to `false`.** You'll
8890 need to set it manually, with one of the mechanism described below.
8991
@@ -332,7 +334,10 @@
332334 target node, which applies the mutation. The row that you've just
333335 deleted is back!
334336
335-The workaround is to use
336-[client-sidetimestamps](../query_timestamps/#client-side-generation) (if
337-you're using native protocol v3 or more, the driver already does this
337+The workaround is to use a timestamp with your queries:
338+
339+ insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000;
340+
341+If you're using native protocol v3, you can also enable [client-side
342+timestamps](../query_timestamps/#client-side-generation) to have this done
338343 automatically.
modified pom.xml +8 −1
@@ -155,8 +155,14 @@
155155 <groupId>org.codehaus.mojo</groupId>
156156 <artifactId>clirr-maven-plugin</artifactId>
157157 <version>2.6.1</version>
158+ <executions>
159+ <execution>
160+ <phase>compile</phase>
161+ <goals><goal>check</goal></goals>
162+ </execution>
163+ </executions>
158164 <configuration>
159- <comparisonVersion>2.1.0</comparisonVersion>
165+ <comparisonVersion>2.2.0</comparisonVersion>
160166 <ignoredDifferencesFile>../clirr-ignores.xml</ignoredDifferencesFile>
161167 <excludes>
162168 <!-- Package-private, internal classes -->
@@ -165,6 +171,7 @@
165171 <exclude>com/datastax/driver/core/Message$*</exclude>
166172 <exclude>com/datastax/driver/core/Requests$*</exclude>
167173 <exclude>com/datastax/driver/core/Responses$*</exclude>
174+ <exclude>com/datastax/driver/core/Connection$*</exclude>
168175 </excludes>
169176 </configuration>
170177 </plugin>
modified upgrade_guide/README.md +73 −6
@@ -125,6 +125,60 @@
125125 exception hierarchy, it now has new child classes that are not
126126 related to timeouts).
127127
128+### 2.1.7
129+
130+This version brings a few changes in the driver's behavior; none of them break
131+binary compatibility.
132+
133+1. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable
134+ exception received from a request. The new behaviour will cause the driver to
135+ process a Retry on a different node at most once, otherwise an exception will
136+ be thrown. This change makes sense in the case where the node tried initially
137+ for the request happens to be isolated from the rest of the cluster (e.g.
138+ because of a network partition) but can still answer to the client normally.
139+ In this case, trying another node has a chance of success.
140+ The previous behaviour was to always throw an exception.
141+
142+2. The following properties in `PoolingOptions` were renamed:
143+ * `MaxSimultaneousRequestsPerConnectionThreshold` to `NewConnectionThreshold`
144+ * `MaxSimultaneousRequestsPerHostThreshold` to `MaxRequestsPerConnection`
145+
146+ The old getters/setters were deprecated, but they delegate to the new
147+ ones.
148+
149+ Also, note that the connection pool for protocol v3 can now be configured to
150+ use multiple connections. See [this page](../features/pooling) for more
151+ information.
152+
153+3. `MappingManager(Session)` will now force the initialization of the `Session`
154+ if needed. This is a change from 2.1.6, where if you gave it an uninitialized
155+ session (created with `Cluster#newSession()` instead of `Cluster#connect()`),
156+ it would only get initialized on the first request.
157+
158+ If this is a problem for you, `MappingManager(Session, ProtocolVersion)`
159+ preserves the previous behavior (see the API docs for more details).
160+
161+Merged from 2.0.11:
162+
163+4. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable
164+ exception received from a request. The new behaviour will cause the driver to
165+ process a Retry on a different node at most once, otherwise an exception will
166+ be thrown. This change makes sense in the case where the node tried initially
167+ for the request happens to be isolated from the rest of the cluster (e.g.
168+ because of a network partition) but can still answer to the client normally.
169+ In this case, trying another node has a chance of success.
170+ The previous behaviour was to always throw an exception.
171+5. A `BuiltStatement` is now considered non-idempotent whenever a `fcall()`
172+ or `raw()` is used to build a value to be inserted in the database.
173+ If you know that the CQL functions or expressions are safe, use
174+ `setIdempotent(true)` on the statement.
175+
176+
177+### 2.1.6
178+
179+See [2.0.10](20x-to-2010).
180+
181+
128182 ### 2.1.2
129183
130184 2.1.2 brings important internal changes with native protocol v3 support, but
@@ -226,6 +280,21 @@
226280 (`cluster.getConfiguration().getProtocolOptions().getProtocolVersion()`).
227281
228282
283+### 2.0.11
284+
285+1. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable
286+ exception received from a request. The new behaviour will cause the driver to
287+ process a Retry on a different node at most once, otherwise an exception will
288+ be thrown. This change makes sense in the case where the node tried initially
289+ for the request happens to be isolated from the rest of the cluster (e.g.
290+ because of a network partition) but can still answer to the client normally.
291+ In this case, trying another node has a chance of success.
292+ The previous behaviour was to always throw an exception.
293+2. A `BuiltStatement` is now considered non-idempotent whenever a `fcall()`
294+ or `raw()` is used to build a value to be inserted in the database.
295+ If you know that the CQL functions or expressions are safe, use
296+ `setIdempotent(true)` on the statement.
297+
229298 ### 2.0.x to 2.0.10
230299
231300 We try to avoid breaking changes within a branch (2.0.x to 2.0.y), but
@@ -326,7 +395,6 @@
326395 This means for instance that `eq("x", raw(foo))` will output `x = foo`,
327396 not `x = 'foo'` (you don't need the raw method to output the latter string).
328397
329-
330398 9. The `QueryBuilder` will now sometimes use the new ability to send value as
331399 bytes instead of serializing everything to string. In general the QueryBuilder
332400 will do the right thing, but if you were calling the `getQueryString()` method
@@ -424,8 +492,8 @@
424492 ```
425493
426494 3. SELECT queries are now "paged" under the hood. In other words, if a query
427- yields a very large result, only the beginning of the `ResultSet` will be fetch
428- initially, the rest being fetch "on-demand". In practice, this means that:
495+ yields a very large result, only the beginning of the `ResultSet` will be fetched
496+ initially, the rest being fetched "on-demand". In practice, this means that:
429497
430498 ```java
431499 for (Row r : session.execute("SELECT * FROM mytable"))
@@ -438,6 +506,5 @@
438506 fine tune the behavior of that paging:
439507 * the size of each "page" can be set per-query (`Statement#setFetchSize()`)
440508 * the `ResultSet` object provides 2 methods to check the state of paging
441- (`ResultSet#getAvailableWithoutFetching` and
442- `ResultSet#isFullyFetched`) as well as a mean to force the pre-fetching
443- of the next page (`ResultSet#fetchMoreResults`).
509+ (`ResultSet#getAvailableWithoutFetching` and `ResultSet#isFullyFetched`)
510+ as well as a mean to force the pre-fetching of the next page (`ResultSet#fetchMoreResults`).