Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into java225

Conflicts:
	changelog/README.md
Changeset81a462b8c8817512b1fa7f29d6ce31acd974120c835a408af2bf0662742e2b9c
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-06-19 18:33 +02:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-06-19 18:33 +02:00
Parentsed244b084a4e, da3cad0e6ca9

Browse the files at this changeset

17 files changed

modified README.md +0 −2
@@ -51,8 +51,6 @@
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
modified changelog/README.md +15 −0
@@ -2,8 +2,11 @@
22
33 ### 2.1.7 (in progress)
44
5+- [improvement] Improve QueryBuilder API for SELECT DISTINCT (JAVA-475)
56 - [improvement] Make NativeColumnType a top-level class (JAVA-715)
67 - [improvement] Unify "Target" enum for schema elements (JAVA-782)
8+- [improvement] Expose ProtocolVersion#toInt (JAVA-700)
9+- [bug] Handle void return types in accessors (JAVA-542)
710 - [improvement] Create values() function for Insert builder using List (JAVA-225)
811
912
@@ -219,6 +222,18 @@
219222 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
220223
221224
225+### 2.0.11 (in progress)
226+
227+- [bug] Fix SpeculativeExecutionPolicy.init() and close() are never called (JAVA-796)
228+
229+Merged from 2.0.10_fixes branch:
230+
231+- [improvement] Use Netty's pooled ByteBufAllocator by default (JAVA-756)
232+- [improvement] Expose "unsafe" paging state API (JAVA-759)
233+- [bug] Fix getObject by name (JAVA-767)
234+- [bug] Prevent race during pool initialization (JAVA-768)
235+
236+
222237 ### 2.0.10.1
223238
224239 - [improvement] Use Netty's pooled ByteBufAllocator by default (JAVA-756)
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +47 −10
@@ -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;
@@ -789,6 +791,38 @@
789791 return this;
790792 }
791793
794+ /**
795+ * Adds a contact point - or many if it host resolves to multiple <code>InetAddress</code>s (A records).
796+ * <p>
797+ *
798+ * If the host name points to a dns records with multiple a-records, all InetAddresses
799+ * returned will be used. Make sure that all resulting <code>InetAddress</code>s returned
800+ * points to the same cluster and datacenter.
801+ * <p>
802+ * See {@link Builder#addContactPoint} for more details on contact
803+ * points and thrown exceptions
804+ *
805+ * @param address address of the nodes to look up InetAddresses from to add as contact points.
806+ * @return this Builder.
807+ *
808+ *
809+ * @see Builder#addContactPoint
810+ */
811+ public Builder addContactPoints(String address) {
812+ // We explicitely check for nulls because InetAdress.getByName() will happily
813+ // accept it and use localhost (while a null here almost likely mean a user error,
814+ // not "connect to localhost")
815+ if (address == null)
816+ throw new NullPointerException();
817+
818+ try {
819+ addContactPoints(InetAddress.getAllByName(address));
820+ } catch (UnknownHostException e) {
821+ throw new IllegalArgumentException(e.getMessage());
822+ }
823+ return this;
824+ }
825+
792826 /**
793827 * Adds contact points.
794828 * <p>
@@ -1292,6 +1326,7 @@
12921326 // Now that the control connection is ready, we have all the information we need about the nodes (datacenter,
12931327 // rack...) to initialize the load balancing policy
12941328 loadBalancingPolicy().init(Cluster.this, contactPointHosts);
1329+ speculativeRetryPolicy().init(Cluster.this);
12951330 for (Host host : downContactPointHosts) {
12961331 loadBalancingPolicy().onDown(host);
12971332 for (Host.StateListener listener : listeners)
@@ -1417,6 +1452,8 @@
14171452 if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
14181453 ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
14191454
1455+ speculativeRetryPolicy().close();
1456+
14201457 AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
14211458 if (translater instanceof CloseableAddressTranslater)
14221459 ((CloseableAddressTranslater)translater).close();
@@ -1550,7 +1587,7 @@
15501587 } catch (ExecutionException e) {
15511588 Throwable t = e.getCause();
15521589 // That future is not really supposed to throw unexpected exceptions
1553- if (!(t instanceof InterruptedException))
1590+ if (!(t instanceof InterruptedException) && !(t instanceof CancellationException))
15541591 logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
15551592 }
15561593
@@ -1821,7 +1858,7 @@
18211858 } catch (ExecutionException e) {
18221859 Throwable t = e.getCause();
18231860 // That future is not really supposed to throw unexpected exceptions
1824- if (!(t instanceof InterruptedException))
1861+ if (!(t instanceof InterruptedException) && !(t instanceof CancellationException))
18251862 logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
18261863 }
18271864
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolVersion.java +8 −1
@@ -62,7 +62,14 @@
6262 return new DriverInternalError("Unsupported protocol version " + this);
6363 }
6464
65- int toInt() {
65+ /**
66+ * Get the int representation of a protocol version.
67+ * This is for use internally by Cassandra to ensure that the
68+ * correct version is specified when serializing and deserializing
69+ * using classes from the imported driver library.
70+ * @return the protocol version as an int
71+ */
72+ public int toInt() {
6673 return asInt;
6774 }
6875
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/SessionManager.java +5 −3
@@ -471,7 +471,11 @@
471471 defaultTimestamp = cluster.getConfiguration().getPolicies().getTimestampGenerator().next();
472472 }
473473
474- return makeRequestMessage(statement, consistency, serialConsistency, pagingState, defaultTimestamp);
474+ Message.Request request = makeRequestMessage(statement, consistency, serialConsistency, pagingState, defaultTimestamp);
475+ if (statement.isTracing())
476+ request.setTracingRequested();
477+
478+ return request;
475479 }
476480
477481 Message.Request makeRequestMessage(Statement statement, ConsistencyLevel cl, ConsistencyLevel scl, ByteBuffer pagingState, long defaultTimestamp) {
@@ -591,8 +595,6 @@
591595 }
592596
593597 ResultSetFuture executeQuery(Message.Request msg, Statement statement) {
594- if (statement.isTracing())
595- msg.setTracingRequested();
596598
597599 DefaultResultSetFuture future = new DefaultResultSetFuture(this, configuration().getProtocolOptions().getProtocolVersionEnum(), msg);
598600 execute(future, statement);
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +1 −1
@@ -83,7 +83,7 @@
8383 * the nodes in that subset were alive but the coordinator hasn't
8484 * detected them as dead. By the time we get the timeout the dead
8585 * nodes will likely have been detected as dead and the retry has thus a
86- * high change of success.
86+ * high chance of success.
8787 *
8888 * @param statement the original query that timed out.
8989 * @param cl the original consistency level of the write that timed out.
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +4 −4
@@ -133,9 +133,9 @@
133133 * and at least one replica acknowledged, the write is retried with a
134134 * lower consistency level (with unlogged batch, a write timeout can
135135 * <b>always</b> mean that part of the batch haven't been persisted at
136- * all, even if {@code receivedAcks > 0}). For other {@code writeType},
137- * if we know the write has been persisted on at least one replica, we
138- * ignore the exception. Otherwise, an exception is thrown.
136+ * all, even if {@code receivedAcks > 0}). For other write types ({@code WriteType.SIMPLE}
137+ * and {@code WriteType.BATCH}), if we know the write has been persisted on at
138+ * least one replica, we ignore the exception. Otherwise, an exception is thrown.
139139 *
140140 * @param statement the original query that timed out.
141141 * @param cl the original consistency level of the write that timed out.
@@ -156,7 +156,7 @@
156156 case SIMPLE:
157157 case BATCH:
158158 // Since we provide atomicity there is no point in retrying
159- return RetryDecision.ignore();
159+ return requiredAcks > 0 ? RetryDecision.ignore() : RetryDecision.rethrow();
160160 case UNLOGGED_BATCH:
161161 // Since only part of the batch could have been persisted,
162162 // retry with whatever consistency should allow to persist all
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +10 −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 *
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +52 −26
@@ -83,6 +83,11 @@
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 {
8792 // Inherit the current environment.
8893 Map<String,String> envMap = Maps.newHashMap(new ProcessBuilder().environment());
@@ -93,8 +98,15 @@
9398 if(existingPath == null) {
9499 existingPath = "";
95100 }
96- envMap.put("PATH", ccmPath + ":" + existingPath);
101+ envMap.put("PATH", ccmPath + File.pathSeparator + existingPath);
102+ }
103+
104+ if (isWindows()) {
105+ CCM_COMMAND = "cmd /c ccm.py";
106+ } else {
107+ CCM_COMMAND = "ccm";
97108 }
109+
98110 // If ccm.java.home is set, override the JAVA_HOME variable with it.
99111 String ccmJavaHome = System.getProperty("ccm.java.home");
100112 if(ccmJavaHome != null) {
@@ -103,6 +115,19 @@
103115 ENVIRONMENT_MAP = ImmutableMap.copyOf(envMap);
104116 }
105117
118+ /**
119+ * Checks if the operating system is a Windows one
120+ * @return <code>true</code> if the operating system is a Windows one, <code>false</code> otherwise.
121+ */
122+ private static boolean isWindows() {
123+
124+ String osName = System.getProperty("os.name");
125+ if (osName == null) {
126+ return false;
127+ }
128+ return osName.startsWith("Windows");
129+ }
130+
106131 static final File CASSANDRA_DIR;
107132 static final String CASSANDRA_VERSION;
108133
@@ -170,7 +195,7 @@
170195 checkArgument(!"current".equals(name.toLowerCase()),
171196 "cluster can't be called \"current\"");
172197 CCMBridge bridge = new CCMBridge();
173- bridge.execute("ccm create %s -b -i %s %s " + Joiner.on(" ").join(options), name, IP_PREFIX, CASSANDRA_VERSION);
198+ bridge.execute(CCM_COMMAND + " create %s -b -i %s %s " + Joiner.on(" ").join(options), name, IP_PREFIX, CASSANDRA_VERSION);
174199 return bridge;
175200 }
176201
@@ -178,7 +203,7 @@
178203 checkArgument(!"current".equals(name.toLowerCase()),
179204 "cluster can't be called \"current\"");
180205 CCMBridge bridge = new CCMBridge();
181- bridge.execute("ccm create %s -n %d -s -i %s -b %s " + Joiner.on(" ").join(options), name, nbNodes, IP_PREFIX, CASSANDRA_VERSION);
206+ bridge.execute(CCM_COMMAND + " create %s -n %d -s -i %s -b %s " + Joiner.on(" ").join(options), name, nbNodes, IP_PREFIX, CASSANDRA_VERSION);
182207 return bridge;
183208 }
184209
@@ -186,7 +211,7 @@
186211 checkArgument(!"current".equals(name.toLowerCase()),
187212 "cluster can't be called \"current\"");
188213 CCMBridge bridge = new CCMBridge();
189- bridge.execute("ccm create %s -n %d -s -i %s -b -v %s ", name, nbNodes, IP_PREFIX, cassandraVersion);
214+ bridge.execute(CCM_COMMAND + " create %s -n %d -s -i %s -b -v %s ", name, nbNodes, IP_PREFIX, cassandraVersion);
190215 return bridge;
191216 }
192217
@@ -194,7 +219,7 @@
194219 checkArgument(!"current".equals(name.toLowerCase()),
195220 "cluster can't be called \"current\"");
196221 CCMBridge bridge = new CCMBridge();
197- bridge.execute("ccm create %s -n %d:%d -s -i %s -b %s", name, nbNodesDC1, nbNodesDC2, IP_PREFIX, CASSANDRA_VERSION);
222+ bridge.execute(CCM_COMMAND + " create %s -n %d:%d -s -i %s -b %s", name, nbNodesDC1, nbNodesDC2, IP_PREFIX, CASSANDRA_VERSION);
198223 return bridge;
199224 }
200225
@@ -207,55 +232,55 @@
207232 }
208233
209234 public void start() {
210- execute("ccm start --wait-other-notice --wait-for-binary-proto");
235+ execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto");
211236 }
212237
213238 public void stop() {
214- execute("ccm stop");
239+ execute(CCM_COMMAND + " stop");
215240 }
216241
217242 public void forceStop() {
218- execute("ccm stop --not-gently");
243+ execute(CCM_COMMAND + " stop --not-gently");
219244 }
220245
221246 public void start(int n) {
222247 logger.info("Starting: " + IP_PREFIX + n);
223- execute("ccm node%d start --wait-other-notice --wait-for-binary-proto", n);
248+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
224249 }
225250
226251 public void start(int n, String option) {
227252 logger.info("Starting: " + IP_PREFIX + n + " with " + option);
228- execute("ccm node%d start --wait-other-notice --wait-for-binary-proto --jvm_arg=%s", n, option);
253+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto --jvm_arg=%s", n, option);
229254 }
230255
231256 public void stop(int n) {
232257 logger.info("Stopping: " + IP_PREFIX + n);
233- execute("ccm node%d stop", n);
258+ execute(CCM_COMMAND + " node%d stop", n);
234259 }
235260
236261 public void stop(String clusterName) {
237262 logger.info("Stopping Cluster : "+clusterName);
238- execute("ccm stop "+clusterName);
263+ execute(CCM_COMMAND + " stop "+clusterName);
239264 }
240265
241266 public void forceStop(int n) {
242267 logger.info("Force stopping: " + IP_PREFIX + n);
243- execute("ccm node%d stop --not-gently", n);
268+ execute(CCM_COMMAND + " node%d stop --not-gently", n);
244269 }
245270
246271 public void remove() {
247272 stop();
248- execute("ccm remove");
273+ execute(CCM_COMMAND + " remove");
249274 }
250275
251276 public void remove(String clusterName) {
252277 stop(clusterName);
253- execute("ccm remove " + clusterName);
278+ execute(CCM_COMMAND + " remove " + clusterName);
254279 }
255280
256281 public void remove(int n) {
257282 logger.info("Removing: " + IP_PREFIX + n);
258- execute("ccm node%d remove", n);
283+ execute(CCM_COMMAND + " node%d remove", n);
259284 }
260285
261286 public void bootstrapNode(int n) {
@@ -264,10 +289,10 @@
264289
265290 public void bootstrapNode(int n, String dc) {
266291 if (dc == null)
267- execute("ccm add node%d -i %s%d -j %d -r %d -b -s", n, IP_PREFIX, n, 7000 + 100 * n, 8000 + 100 * n);
292+ 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);
268293 else
269- execute("ccm add node%d -i %s%d -j %d -b -d %s -s", n, IP_PREFIX, n, 7000 + 100 * n, dc);
270- execute("ccm node%d start --wait-other-notice --wait-for-binary-proto", n);
294+ execute(CCM_COMMAND + " add node%d -i %s%d -j %d -b -d %s -s", n, IP_PREFIX, n, 7000 + 100 * n, dc);
295+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
271296 }
272297
273298 public void bootstrapNodeWithPorts(int n, int thriftPort, int storagePort, int binaryPort, int jmxPort, int remoteDebugPort) {
@@ -275,13 +300,13 @@
275300 String storageItf = IP_PREFIX + n + ":" + storagePort;
276301 String binaryItf = IP_PREFIX + n + ":" + binaryPort;
277302 String remoteLogItf = IP_PREFIX + n + ":" + remoteDebugPort;
278- execute("ccm add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s",
303+ execute(CCM_COMMAND + " add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s",
279304 n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf);
280- execute("ccm node%d start --wait-other-notice --wait-for-binary-proto", n);
305+ execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n);
281306 }
282307
283308 public void decommissionNode(int n) {
284- execute("ccm node%d decommission", n);
309+ execute(CCM_COMMAND + " node%d decommission", n);
285310 }
286311
287312 public void updateConfig(String name, String value) {
@@ -293,16 +318,17 @@
293318 for (Map.Entry<String, String> entry : configs.entrySet()) {
294319 confStr.append(entry.getKey() + ":" + entry.getValue() + " ");
295320 }
296- execute("ccm updateconf " + confStr);
321+ execute(CCM_COMMAND + " updateconf " + confStr);
297322 }
298323
299324 public void populate(int n) {
300- execute("ccm populate -n %d -i %s", n, IP_PREFIX);
325+ execute(CCM_COMMAND + " populate -n %d -i %s", n, IP_PREFIX);
301326 }
302327
303328 private void execute(String command, Object... args) {
329+
330+ String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
304331 try {
305- String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
306332 logger.debug("Executing: " + fullCommand);
307333 CommandLine cli = CommandLine.parse(fullCommand);
308334 Executor executor = new DefaultExecutor();
@@ -327,7 +353,7 @@
327353 throw new RuntimeException();
328354 }
329355 } catch (IOException e) {
330- throw new RuntimeException(e);
356+ throw new RuntimeException(String.format("The command %s failed to execute", fullCommand), e);
331357 }
332358 }
333359
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +53 −7
@@ -25,17 +25,19 @@
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")
@@ -47,9 +49,9 @@
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.create("test", 1);
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) {
added driver-core/src/test/java/com/datastax/driver/core/TracingTest.java +73 −0
@@ -0,0 +1,73 @@
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.utils.CassandraVersion;
24+import org.testng.annotations.BeforeClass;
25+import org.testng.annotations.Test;
26+
27+import static org.assertj.core.api.Assertions.assertThat;
28+
29+@CassandraVersion(major=2.0)
30+public class TracingTest extends CCMBridge.PerClassSingleNodeCluster {
31+
32+ public static final String KEY = "tracing_test";
33+
34+ @Override
35+ protected Collection<String> getTableDefinitions() {
36+ return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))");
37+ }
38+
39+ @BeforeClass(groups = "short")
40+ public void initData() {
41+ for (int i = 0; i < 100; i++) {
42+ session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", KEY, i));
43+ }
44+ }
45+
46+ /**
47+ * Validates that for each page the {@link ExecutionInfo} will have a different tracing ID.
48+ *
49+ * @test_category tracing
50+ * @expected_result {@link ResultSet} where all the {@link ExecutionInfo} will contains a different tracing ID and
51+ * that the events can be retrieved for the last query.
52+ */
53+ @Test(groups = "short")
54+ public void should_have_a_different_tracingId_for_each_page() {
55+ SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY));
56+ ResultSet result = session.execute(st.setFetchSize(40).enableTracing());
57+ result.all();
58+
59+ List<ExecutionInfo> executions = result.getAllExecutionInfo();
60+
61+ UUID previousTraceId = null;
62+ for (ExecutionInfo executionInfo : executions) {
63+ QueryTrace queryTrace = executionInfo.getQueryTrace();
64+ assertThat(queryTrace).isNotNull();
65+ assertThat(queryTrace.getTraceId()).isNotEqualTo(previousTraceId);
66+ previousTraceId = queryTrace.getTraceId();
67+ }
68+
69+ assertThat(result.getExecutionInfo().getQueryTrace().getEvents()).isNotNull()
70+ .isNotEmpty();
71+ }
72+}
73+
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +17 −0
@@ -85,6 +85,14 @@
8585 select = select("a").from("foo").where(in("k", bindMarker()));
8686 assertEquals(select.toString(), query);
8787
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+
8896 query = "SELECT count(*) FROM foo;";
8997 select = select().countAll().from("foo");
9098 assertEquals(select.toString(), query);
@@ -833,6 +841,15 @@
833841 assertThat(statement.toString()).isEqualTo(query);
834842 }
835843
844+ @Test(groups = "unit")
845+ public void should_quote_column_names_with_escaped_quotes() {
846+ // A column name can include quotes as long as it is escaped with another set of quotes, so "foo""bar" is a valid name.
847+ String query = "SELECT * FROM foo WHERE \"foo \"\" bar\"=1;";
848+ Statement statement = select().from("foo").where(eq(quote("foo \"\" bar"), 1));
849+
850+ assertThat(statement.toString()).isEqualTo(query);
851+ }
852+
836853 @Test(groups = "unit")
837854 public void should_not_serialize_raw_query_values() {
838855 RegularStatement select = select().from("test").where(gt("i", raw("1")));
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +1 −1
@@ -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)) {
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +78 −16
@@ -17,6 +17,7 @@
1717
1818 import java.util.Collection;
1919
20+import com.datastax.driver.core.ResultSet;
2021 import com.google.common.collect.Lists;
2122 import org.testng.annotations.Test;
2223
@@ -28,22 +29,41 @@
2829 public class MapperAccessorParamsTest extends CCMBridge.PerClassSingleNodeCluster {
2930 @Override
3031 protected Collection<String> getTableDefinitions() {
31- return Lists.newArrayList("CREATE TABLE user ( key int primary key, gender int)",
32- "CREATE INDEX on user(gender)");
33-
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)");
3437 }
3538
3639 @Test(groups = "short")
37- void should_include_enumtype_in_accessor() {
38- Mapper<User> userMapper = new MappingManager(session).mapper(User.class);
39- userMapper.save(new User(1, 0));
40- userMapper.save(new User(2, 1));
41-
40+ void should_include_enumtype_in_accessor_ordinal() {
4241 UserAccessor accessor = new MappingManager(session)
43- .createAccessor(UserAccessor.class);
44- assertThat(accessor.getUser(Enum.MALE).one().getGender()).isEqualTo(0);
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);
4548 assertThat(accessor.getUser(Enum.MALE).one().getKey()).isEqualTo(1);
4649
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);
4767 }
4868
4969 enum Enum {
@@ -52,8 +72,17 @@
5272
5373 @Accessor
5474 public interface UserAccessor {
55- @Query("select * from user where gender=:val")
56- Result<User> getUser(@Param("val") @Enumerated(EnumType.ORDINAL) Enum value);
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);
5786 }
5887
5988 @Table(name = "user")
@@ -61,12 +90,45 @@
6190 @PartitionKey
6291 private int key;
6392
64- private int gender;
93+ @Enumerated(EnumType.ORDINAL)
94+ private Enum gender;
6595
6696 public User() {
6797 }
6898
69- public User(int k, int val) {
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) {
70132 this.key = k;
71133 this.gender = val;
72134 }
@@ -79,11 +141,11 @@
79141 this.key = pk;
80142 }
81143
82- public int getGender() {
144+ public Enum getGender() {
83145 return this.gender;
84146 }
85147
86- public void setGender(int val) {
148+ public void setGender(Enum val) {
87149 this.gender = val;
88150 }
89151 }
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 (:k, :v)")
112+ void insert(@Param("k") int k, @Param("v") String v);
113+ }
114+
99115 }
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