Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changesetdbe94e517879be4817555d0b6e067f8c5ab494c7f38e268a4fb606e1c6882d8f
Authorolim7t <omichallat+github@gmail.com> · 2014-11-17 17:33 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-11-17 18:08 +01:00
Parentsf61d1e15a96e, fd857ad233bb

Browse the files at this changeset

22 files changed

modified README.rst +1 −0
@@ -10,6 +10,7 @@
1010 - TWITTER: Follow the latest news about DataStax Drivers - `@olim7t <http://twitter.com/olim7t>`_, `@mfiguiere <http://twitter.com/mfiguiere>`_
1111 - DOCS: http://www.datastax.com/documentation/developer/java-driver/2.1/index.html
1212 - API: http://www.datastax.com/drivers/java/2.1
13+- CHANGELOG: https://github.com/datastax/java-driver/blob/2.1/driver-core/CHANGELOG.rst
1314
1415
1516 The driver architecture is based on layers. At the bottom lies the driver core.
modified driver-core/CHANGELOG.rst +15 −1
@@ -34,6 +34,11 @@
3434 - [bug] Fix check for local contact points in DCAware policy's init (JAVA-511)
3535 - [improvement] Make timeout on saturated pool customizable (JAVA-457)
3636 - [improvement] Downgrade Guava to 14.0.1 (JAVA-521)
37+- [bug] Fix token awareness for case-sensitive keyspaces and tables (JAVA-526)
38+- [bug] Check maximum number of values passed to SimpleStatement (JAVA-515)
39+- [improvement] Expose the driver version through the API (JAVA-532)
40+- [improvement] Optimize session initialization when some hosts are not
41+ responsive (JAVA-522)
3742
3843
3944 2.1.2:
@@ -123,6 +128,16 @@
123128 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
124129
125130
131+2.0.8:
132+------
133+
134+- [bug] Fix token awareness for case-sensitive keyspaces and tables (JAVA-526)
135+- [bug] Check maximum number of values passed to SimpleStatement (JAVA-515)
136+- [improvement] Expose the driver version through the API (JAVA-532)
137+- [improvement] Optimize session initialization when some hosts are not
138+ responsive (JAVA-522)
139+
140+
126141 2.0.7:
127142 ------
128143
@@ -166,7 +181,6 @@
166181 - [improvement] Expose child policy in chainable load balancing policies (JAVA-439)
167182
168183
169-
170184 2.0.5:
171185 ------
172186
modified driver-core/pom.xml +6 −0
@@ -92,6 +92,12 @@
9292 </dependencies>
9393
9494 <build>
95+ <resources>
96+ <resource>
97+ <directory>src/main/resources</directory>
98+ <filtering>true</filtering>
99+ </resource>
100+ </resources>
95101 <plugins>
96102 <plugin>
97103 <groupId>org.apache.maven.plugins</groupId>
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +64 −9
@@ -69,6 +69,8 @@
6969 private static final int NON_BLOCKING_EXECUTOR_SIZE = SystemProperties.getInt("com.datastax.driver.NON_BLOCKING_EXECUTOR_SIZE",
7070 Runtime.getRuntime().availableProcessors());
7171
72+ private static final ResourceBundle driverProperties = ResourceBundle.getBundle("com.datastax.driver.core.Driver");
73+
7274 // Some per-JVM number that allows to generate unique cluster names when
7375 // multiple Cluster instance are created in the same JVM.
7476 private static final AtomicInteger CLUSTER_ID = new AtomicInteger(0);
@@ -187,6 +189,18 @@
187189 return new Cluster.Builder();
188190 }
189191
192+ /**
193+ * Returns the current version of the driver.
194+ * <p>
195+ * This is intended for products that wrap or extend the driver, as a way to check
196+ * compatibility if end-users override the driver version in their application.
197+ *
198+ * @return the version.
199+ */
200+ public static String getDriverVersion() {
201+ return driverProperties.getString("driver.version");
202+ }
203+
190204 /**
191205 * Creates a new session on this cluster but does not initialize it.
192206 * <p>
@@ -1226,18 +1240,46 @@
12261240 }
12271241 }
12281242
1243+ // The control connection can mark hosts down if it failed to connect to them, separate them
1244+ Set<Host> downContactPointHosts = Sets.newHashSet();
1245+ for (Host host : contactPointHosts)
1246+ if (host.state == Host.State.DOWN)
1247+ downContactPointHosts.add(host);
1248+ contactPointHosts.removeAll(downContactPointHosts);
1249+
12291250 // Now that the control connection is ready, we have all the information we need about the nodes (datacenter,
12301251 // rack...) to initialize the load balancing policy
12311252 loadBalancingPolicy().init(Cluster.this, contactPointHosts);
1232- // Add the remaining hosts that were discovered by the control connection:
1253+ for (Host host : downContactPointHosts) {
1254+ loadBalancingPolicy().onDown(host);
1255+ for (Host.StateListener listener : listeners)
1256+ listener.onDown(host);
1257+ }
1258+
12331259 for (Host host : metadata.allHosts()) {
1260+ // If the host is down at this stage, it's a contact point that the control connection failed to reach.
1261+ // Reconnection attempts are already scheduled, and the LBP and listeners have been notified above.
1262+ if (host.state == Host.State.DOWN) continue;
1263+
1264+ // Otherwise, we want to do the equivalent of onAdd(). But since we know for sure that no sessions or prepared
1265+ // statements exist at this point, we can skip some of the steps (plus this avoids scheduling concurrent pool
1266+ // creations if a session is created right after this method returns).
1267+ logger.info("New Cassandra host {} added", host);
1268+
1269+ if (!connectionFactory.protocolVersion.isSupportedBy(host)) {
1270+ logUnsupportedVersionProtocol(host, connectionFactory.protocolVersion);
1271+ return;
1272+ }
1273+
12341274 if (!contactPointHosts.contains(host))
12351275 loadBalancingPolicy().onAdd(host);
1276+
1277+ host.setUp();
1278+
1279+ for (Host.StateListener listener : listeners)
1280+ listener.onAdd(host);
12361281 }
12371282 isFullyInit = true;
1238-
1239- for (Host host : metadata.allHosts())
1240- triggerOnAdd(host);
12411283 } catch (NoHostAvailableException e) {
12421284 close();
12431285 throw e;
@@ -1299,9 +1341,9 @@
12991341
13001342 // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications
13011343 // delivery or blocking tasks so we use shutdownNow
1302- reconnectionExecutor.shutdownNow();
1303- scheduledTasksExecutor.shutdownNow();
1304- blockingExecutor.shutdownNow();
1344+ shutdownNow(reconnectionExecutor);
1345+ shutdownNow(scheduledTasksExecutor);
1346+ shutdownNow(blockingExecutor);
13051347
13061348 // but for the worker executor, we want to let submitted tasks finish unless the shutdown is forced.
13071349 executor.shutdown();
@@ -1329,6 +1371,15 @@
13291371 : closeFuture.get(); // We raced, it's ok, return the future that was actually set
13301372 }
13311373
1374+ private void shutdownNow(ExecutorService executor) {
1375+ List<Runnable> pendingTasks = executor.shutdownNow();
1376+ // If some tasks were submitted to this executor but not yet commenced, make sure the corresponding futures complete
1377+ for (Runnable pendingTask : pendingTasks) {
1378+ if (pendingTask instanceof FutureTask<?>)
1379+ ((FutureTask<?>)pendingTask).cancel(false);
1380+ }
1381+ }
1382+
13321383 void logUnsupportedVersionProtocol(Host host, ProtocolVersion version) {
13331384 logger.warn("Detected added or restarted Cassandra host {} but ignoring it since it does not support the version {} of the native "
13341385 + "protocol which is currently in use. If you want to force the use of a particular version of the native protocol, use "
@@ -1562,6 +1613,10 @@
15621613
15631614 // Note: we basically waste the first successful reconnection, but it's probably not a big deal
15641615 logger.debug("{} is down, scheduling connection retries", host);
1616+ startPeriodicReconnectionAttempt(host, isHostAddition);
1617+ }
1618+
1619+ void startPeriodicReconnectionAttempt(final Host host, final boolean isHostAddition) {
15651620 new AbstractReconnectionHandler(reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt) {
15661621
15671622 protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
@@ -1611,7 +1666,7 @@
16111666 }.start();
16121667 }
16131668
1614- public void tryReconnectOnce(final Host host) {
1669+ void startSingleReconnectionAttempt(final Host host) {
16151670 if (isClosed() || host.isUp())
16161671 return;
16171672
@@ -2101,7 +2156,7 @@
21012156 @Override
21022157 public CloseFuture force() {
21032158 // The only ExecutorService we haven't forced yet is executor
2104- executor.shutdownNow();
2159+ shutdownNow(executor);
21052160 return super.force();
21062161 }
21072162
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +6 −0
@@ -187,6 +187,12 @@
187187 return tryConnect(host, isInitialConnection);
188188 } catch (ConnectionException e) {
189189 errors = logError(host, e, errors, iter);
190+ if (isInitialConnection) {
191+ // Mark the host down right away so that we don't try it again during the initialization process.
192+ // We don't call cluster.triggerOnDown because it does a bunch of other things we don't want to do here (notify LBP, etc.)
193+ host.setDown();
194+ cluster.startPeriodicReconnectionAttempt(host, true);
195+ }
190196 } catch (ExecutionException e) {
191197 errors = logError(host, e.getCause(), errors, iter);
192198 } catch (UnsupportedProtocolVersionException e) {
modified driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +2 −2
@@ -50,9 +50,9 @@
5050
5151 List<ColumnMetadata> partitionKeyColumns = null;
5252 int[] pkIndexes = null;
53- KeyspaceMetadata km = clusterMetadata.getKeyspace(defs.getKeyspace(0));
53+ KeyspaceMetadata km = clusterMetadata.getKeyspace(Metadata.quote(defs.getKeyspace(0)));
5454 if (km != null) {
55- TableMetadata tm = km.getTable(defs.getTable(0));
55+ TableMetadata tm = km.getTable(Metadata.quote(defs.getTable(0)));
5656 if (tm != null) {
5757 partitionKeyColumns = tm.getPartitionKey();
5858 pkIndexes = new int[partitionKeyColumns.size()];
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +1 −1
@@ -214,7 +214,7 @@
214214 * is already in progress.
215215 */
216216 public void tryReconnectOnce() {
217- this.manager.tryReconnectOnce(this);
217+ this.manager.startSingleReconnectionAttempt(this);
218218 }
219219
220220 @Override
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +1 −1
@@ -101,7 +101,7 @@
101101 *
102102 * cluster.getMetrics().getRegistry().addListener(new com.codahale.metrics.MetricRegistryListener() {
103103 * &#64;Override
104- * public void onGaugeAdded(String name, Gauge<?> gauge) {
104+ * public void onGaugeAdded(String name, Gauge&lt;?&gt; gauge) {
105105 * if (myRegistry.getNames().contains(name)) {
106106 * // name is already taken, maybe prefix with a namespace
107107 * ...
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +41 −4
@@ -64,10 +64,43 @@
6464 // If we haven't initialized the cluster, do it now
6565 cluster.init();
6666
67- // Create pool to initial nodes (and wait for them to be created)
67+ // Create pools to initial nodes (and wait for them to be created)
68+ Collection<Host> hosts = cluster.getMetadata().allHosts();
69+ if (cluster.manager.sessions.size() == 1) {
70+ // We only do it in parallel if this is the first session (meaning that the cluster just initialized).
71+ createPoolsInParallel(hosts);
72+ } else {
73+ // Otherwise, we don't want to fill executor() because this is also where up/down notifications are processed,
74+ // it's important that existing sessions get them in a timely manner. So we create the pools one by one:
75+ createPoolsSequentially(hosts);
76+ }
77+
78+ isInit = true;
79+ updateCreatedPools(executor());
80+ return this;
81+ }
82+
83+ private void createPoolsInParallel(Collection<Host> hosts) {
84+ List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(hosts.size());
85+ for (Host host : hosts)
86+ if (host.state != Host.State.DOWN)
87+ futures.add(maybeAddPool(host, executor()));
88+ ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
89+ try {
90+ f.get();
91+ } catch (ExecutionException e) {
92+ // This is not supposed to happen
93+ throw new DriverInternalError(e);
94+ } catch (InterruptedException e) {
95+ Thread.currentThread().interrupt();
96+ }
97+ }
98+
99+ private void createPoolsSequentially(Collection<Host> hosts) {
68100 for (Host host : cluster.getMetadata().allHosts()) {
69101 try {
70- maybeAddPool(host, executor()).get();
102+ if (host.state != Host.State.DOWN)
103+ maybeAddPool(host, executor()).get();
71104 } catch (ExecutionException e) {
72105 // This is not supposed to happen
73106 throw new DriverInternalError(e);
@@ -75,8 +108,6 @@
75108 Thread.currentThread().interrupt();
76109 }
77110 }
78- isInit = true;
79- return this;
80111 }
81112
82113 public String getLoggedKeyspace() {
@@ -299,6 +330,12 @@
299330 * have one, and hosts that shouldn't don't.
300331 */
301332 void updateCreatedPools(ListeningExecutorService executor) {
333+ // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if
334+ // we execute the code below we would try to create their pool over and over again.
335+ // It's called explicitly at the end of init(), once isInit has been set to true.
336+ if (!isInit)
337+ return;
338+
302339 try {
303340 // We do 2 iterations, so that we add missing pools first, and them remove all unecessary pool second.
304341 // That way, we'll avoid situation where we'll temporarily lose connectivity
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +2 −0
@@ -83,6 +83,8 @@
8383 * by {@link DataType#asJavaClass}.
8484 */
8585 public SimpleStatement(String query, Object... values) {
86+ if (values.length > 65535)
87+ throw new IllegalArgumentException("Too many values, the maximum allowed is 65535");
8688 this.query = query;
8789 this.values = values;
8890 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +4 −0
@@ -81,6 +81,10 @@
8181 } else {
8282 values = new ArrayList<Object>();
8383 sb = buildQueryString(values);
84+
85+ if (values.size() > 65535)
86+ throw new IllegalArgumentException("Too many values for built statement, the maximum allowed is 65535");
87+
8488 if (values.isEmpty())
8589 values = null;
8690 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +2 −0
@@ -74,6 +74,8 @@
7474
7575 if (values == null)
7676 throw new IllegalArgumentException("Missing values for IN clause");
77+ if (values.size() > 65535)
78+ throw new IllegalArgumentException("Too many values for IN clause, the maximum allowed is 65535");
7779 }
7880
7981 @Override
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +12 −0
@@ -286,6 +286,18 @@
286286 public static Clause in(String name, Object... values) {
287287 return new Clause.InClause(name, Arrays.asList(values));
288288 }
289+
290+ /**
291+ * Create an "in" where clause stating the provided column must be equal
292+ * to one of the provided values.
293+ *
294+ * @param name the column name
295+ * @param values the values
296+ * @return the corresponding where clause.
297+ */
298+ public static Clause in(String name, List<Object> values) {
299+ return new Clause.InClause(name, values);
300+ }
289301
290302 /**
291303 * Creates a "lesser than" where clause stating the provided column must be less than
added driver-core/src/main/resources/com/datastax/driver/core/Driver.properties +1 −0
@@ -0,0 +1,1 @@
1+driver.version=${project.version}
No newline at the end of the file
added driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +116 −0
@@ -0,0 +1,116 @@
1+package com.datastax.driver.core;
2+
3+import java.net.InetAddress;
4+import java.util.List;
5+import java.util.concurrent.TimeUnit;
6+
7+import com.google.common.collect.Lists;
8+import org.mockito.Mockito;
9+import org.slf4j.Logger;
10+import org.slf4j.LoggerFactory;
11+import org.testng.annotations.Test;
12+
13+import static org.assertj.core.api.Assertions.assertThat;
14+import static org.assertj.core.api.Assertions.fail;
15+import static org.mockito.Mockito.atMost;
16+import static org.mockito.Mockito.spy;
17+import static org.mockito.Mockito.times;
18+import static org.mockito.Mockito.verify;
19+
20+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
21+import com.datastax.driver.core.utils.UUIDs;
22+
23+import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS;
24+
25+public class ClusterInitTest {
26+ private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
27+
28+ /**
29+ * Test for JAVA-522: when the cluster and session initialize, if some contact points are behaving badly and
30+ * causing timeouts, we want to ensure that the driver does not wait multiple times on the same host.
31+ */
32+
33+ @Test(groups = "short")
34+ public void should_wait_for_each_contact_point_at_most_once() {
35+ CCMBridge ccm = null;
36+ Cluster cluster = null;
37+ List<FakeHost> fakeHosts = Lists.newArrayList();
38+ try {
39+ // Obtaining connect timeouts is not trivial: we create a 6-host cluster but only start one of them,
40+ // then simulate the other 5.
41+ ccm = CCMBridge.create("test");
42+ ccm.populate(6);
43+ ccm.start(1);
44+
45+ for (int i = 0; i < 5; i++) {
46+ FakeHost fakeHost = new FakeHost(CCMBridge.ipOfNode(i + 2), 9042, THROWING_CONNECT_TIMEOUTS);
47+ fakeHosts.add(fakeHost);
48+ fakeHost.start();
49+ }
50+
51+ // Our real instance has no rows in its system.peers table. That would cause the driver to ignore our fake
52+ // hosts when the control connection refreshes the host list.
53+ // So we also insert fake rows in system.peers:
54+ fakePeerRowsInNode1();
55+
56+ logger.info("Environment is set up, starting test");
57+ long start = System.nanoTime();
58+
59+ // We want to count how many connections were attempted. For that, we rely on the fact that SocketOptions.getKeepAlive is called in Connection.Factory.newBoostrap()
60+ // each time we prepare to open a new connection. This is a bit of a hack, but this is what we have.
61+ SocketOptions socketOptions = spy(new SocketOptions());
62+
63+ // Set an enormous delay so that reconnection attempts don't pollute our observations
64+ ConstantReconnectionPolicy reconnectionPolicy = new ConstantReconnectionPolicy(3600 * 1000);
65+
66+ cluster = Cluster.builder().addContactPoints(
67+ CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2), CCMBridge.ipOfNode(3),
68+ CCMBridge.ipOfNode(4), CCMBridge.ipOfNode(5), CCMBridge.ipOfNode(6))
69+ .withSocketOptions(socketOptions)
70+ .withReconnectionPolicy(reconnectionPolicy)
71+ .build();
72+ cluster.connect();
73+
74+ // For information only:
75+ long initTimeMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
76+ logger.info("Cluster and session initialized in {} ms", initTimeMs);
77+
78+ // We have one live host so 2 successful connections (1 control connection and 1 core connection in the pool).
79+ // The other 5 hosts are unreachable, we should attempt to connect to each of them only once.
80+ verify(socketOptions, times(2 + 5)).getKeepAlive();
81+ } finally {
82+ if (cluster != null)
83+ cluster.close();
84+ for (FakeHost fakeHost : fakeHosts)
85+ fakeHost.stop();
86+ if (ccm != null)
87+ ccm.remove();
88+ }
89+ }
90+
91+ private void fakePeerRowsInNode1() {
92+ Cluster cluster = null;
93+ try {
94+ cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
95+ Session session = cluster.connect("system");
96+
97+ String releaseVersion = session.execute("SELECT release_version FROM local")
98+ .one().getString("release_version");
99+
100+ for (int i = 2; i <= 6; i++)
101+ session.execute("INSERT INTO peers (peer, data_center, host_id, rack, release_version, rpc_address, schema_version) " +
102+ "VALUES (?, 'datacenter1', ?, 'rack1', ?, ?, ?)",
103+ InetAddress.getByName(CCMBridge.ipOfNode(i)),
104+ UUIDs.random(),
105+ releaseVersion,
106+ InetAddress.getByName(CCMBridge.ipOfNode(i)),
107+ UUIDs.random()
108+ );
109+ } catch (Exception e) {
110+ fail("Error while inserting fake peer rows", e);
111+ } finally {
112+ if (cluster != null)
113+ cluster.close();
114+ }
115+ }
116+}
added driver-core/src/test/java/com/datastax/driver/core/FakeHost.java +83 −0
@@ -0,0 +1,83 @@
1+package com.datastax.driver.core;
2+
3+import java.io.IOException;
4+import java.net.InetAddress;
5+import java.net.ServerSocket;
6+import java.net.Socket;
7+import java.util.concurrent.ExecutorService;
8+import java.util.concurrent.Executors;
9+import java.util.concurrent.TimeUnit;
10+
11+import static org.assertj.core.api.Assertions.fail;
12+
13+/**
14+ * Fake Cassandra host that will cause a given error when the driver tries to connect to it.
15+ */
16+public class FakeHost {
17+ public enum Behavior {THROWING_CONNECT_TIMEOUTS, THROWING_OPERATION_TIMEOUTS}
18+
19+ private final String address;
20+ private final int port;
21+ private final Behavior behavior;
22+ private final ExecutorService executor;
23+
24+ FakeHost(String address, int port, Behavior behavior) {
25+ this.address = address;
26+ this.port = port;
27+ this.behavior = behavior;
28+ this.executor = Executors.newSingleThreadExecutor();
29+ }
30+
31+ public void start() {
32+ executor.execute(new AcceptClientAndWait(address, port, behavior));
33+ }
34+
35+ public void stop() {
36+ executor.shutdownNow();
37+ }
38+
39+ private static class AcceptClientAndWait implements Runnable {
40+
41+ private final String address;
42+ private final int port;
43+ private final Behavior behavior;
44+
45+ public AcceptClientAndWait(String address, int port, Behavior behavior) {
46+ this.address = address;
47+ this.port = port;
48+ this.behavior = behavior;
49+ }
50+
51+ @Override public void run() {
52+ ServerSocket server = null;
53+ Socket client = null;
54+ try {
55+ InetAddress bindAddress = InetAddress.getByName(address);
56+ int backlog = (behavior == Behavior.THROWING_CONNECT_TIMEOUTS)
57+ ? 1
58+ : -1; // default
59+ server = new ServerSocket(port, backlog, bindAddress);
60+
61+ if (behavior == Behavior.THROWING_CONNECT_TIMEOUTS) {
62+ // fill backlog queue
63+ client = new Socket();
64+ client.connect(server.getLocalSocketAddress());
65+ }
66+ TimeUnit.MINUTES.sleep(10);
67+ fail("Mock host wasn't expected to live more than 10 minutes");
68+ } catch (IOException e) {
69+ fail("Unexpected I/O exception", e);
70+ } catch (InterruptedException e) {
71+ // interruption is the expected way to stop this runnable, exit
72+ try {
73+ if (client != null)
74+ client.close();
75+ server.close();
76+ } catch (IOException e1) {
77+ fail("Unexpected error while closing sockets", e);
78+ }
79+
80+ }
81+ }
82+ }
83+}
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +10 −1
@@ -17,6 +17,7 @@
1717
1818 import java.io.PrintWriter;
1919 import java.io.StringWriter;
20+import java.util.Collection;
2021
2122 import org.testng.annotations.AfterClass;
2223 import org.testng.annotations.BeforeClass;
@@ -41,7 +42,8 @@
4142
4243 @Test(groups = "short")
4344 public void notificationsTest() throws Exception {
44- assertEquals(policy.adds, 2, "adds\n" + policy.history);
45+ assertEquals(policy.inits, 2, "inits\n" + policy.history);
46+ assertEquals(policy.adds, 0, "adds\n" + policy.history);
4547 assertEquals(policy.suspecteds, 0, "suspecteds\n" + policy.history);
4648 assertEquals(policy.removes, 0, "removes\n" + policy.history);
4749 assertEquals(policy.ups, 0, "ups\n" + policy.history);
@@ -55,6 +57,7 @@
5557
5658 static class CountingPolicy extends DelegatingLoadBalancingPolicy {
5759
60+ int inits;
5861 int adds;
5962 int suspecteds;
6063 int removes;
@@ -68,6 +71,12 @@
6871 super(delegate);
6972 }
7073
74+ @Override
75+ public void init(Cluster cluster, Collection<Host> hosts) {
76+ super.init(cluster, hosts);
77+ inits += hosts.size();
78+ }
79+
7180 public void onAdd(Host host) {
7281 out.printf("add %s%n", host);
7382 adds++;
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +24 −0
@@ -20,6 +20,8 @@
2020 import static org.testng.Assert.assertFalse;
2121
2222 import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
2325 import static org.testng.Assert.assertEquals;
2426 import static org.testng.Assert.assertTrue;
2527
@@ -427,4 +429,26 @@
427429 batch.add(ps.bind("k"));
428430 session.execute(batch);
429431 }
432+
433+ @Test(groups="short")
434+ public void should_set_routing_key_on_case_insensitive_keyspace_and_table() {
435+ session.execute("CREATE TABLE ks.foo (i int PRIMARY KEY)");
436+
437+ PreparedStatement ps = session.prepare("INSERT INTO ks.foo (i) VALUES (?)");
438+ BoundStatement bs = ps.bind(1);
439+ assertThat(bs.getRoutingKey()).isNotNull();
440+ }
441+
442+ @Test(groups="short")
443+ public void should_set_routing_key_on_case_sensitive_keyspace_and_table() {
444+ session.execute("CREATE KEYSPACE \"Test\" WITH replication = { "
445+ + " 'class': 'SimpleStrategy',"
446+ + " 'replication_factor': '1'"
447+ + "}");
448+ session.execute("CREATE TABLE \"Test\".\"Foo\" (i int PRIMARY KEY)");
449+
450+ PreparedStatement ps = session.prepare("INSERT INTO \"Test\".\"Foo\" (i) VALUES (?)");
451+ BoundStatement bs = ps.bind(1);
452+ assertThat(bs.getRoutingKey()).isNotNull();
453+ }
430454 }
added driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +14 −0
@@ -0,0 +1,14 @@
1+package com.datastax.driver.core;
2+
3+import java.util.Collections;
4+import java.util.List;
5+
6+import org.testng.annotations.Test;
7+
8+public class SimpleStatementTest {
9+ @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class })
10+ public void should_fail_if_too_many_variables() {
11+ List<Object> args = Collections.nCopies(1 << 16, (Object)1);
12+ new SimpleStatement("mock query", args.toArray());
13+ }
14+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +20 −0
@@ -698,4 +698,24 @@
698698 select = select().all().from("foo").where(eq("k", 4)).and(lte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
699699 assertEquals(select.toString(), query);
700700 }
701+
702+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
703+ public void should_fail_if_in_clause_has_too_many_values() {
704+ List<Object> values = Collections.<Object>nCopies(65536, "a");
705+ select().all().from("foo").where(in("bar", values.toArray()));
706+ }
707+
708+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
709+ public void should_fail_if_built_statement_has_too_many_values() {
710+ List<Object> values = Collections.<Object>nCopies(65535, "a");
711+
712+ // If the excessive count results from successive DSL calls, we don't check it on the fly so this statement works:
713+ BuiltStatement statement = select().all().from("foo")
714+ .where(eq("bar", "a"))
715+ .and(in("baz", values.toArray()));
716+
717+ // But we still want to check it client-side, to fail fast instead of sending a bad query to Cassandra.
718+ // getValues() is called on any RegularStatement before we send it (see SessionManager.makeRequestMessage).
719+ statement.getValues(ProtocolVersion.V3);
720+ }
701721 }
modified driver-dist/pom.xml +1 −0
@@ -63,6 +63,7 @@
6363 </goals>
6464 <configuration>
6565 <includeDependencySources>true</includeDependencySources>
66+ <additionalparam>${javadoc.opts}</additionalparam>
6667 </configuration>
6768 </execution>
6869 </executions>
modified pom.xml +15 −0
@@ -57,6 +57,18 @@
5757 </dependency>
5858 </dependencies>
5959
60+ <profiles>
61+ <profile>
62+ <id>doclint-java8-disable</id>
63+ <activation>
64+ <jdk>[1.8,)</jdk>
65+ </activation>
66+ <properties>
67+ <javadoc.opts>-Xdoclint:none</javadoc.opts>
68+ </properties>
69+ </profile>
70+ </profiles>
71+
6072 <build>
6173 <plugins>
6274 <plugin>
@@ -97,6 +109,9 @@
97109 <goals>
98110 <goal>jar</goal>
99111 </goals>
112+ <configuration>
113+ <additionalparam>${javadoc.opts}</additionalparam>
114+ </configuration>
100115 </execution>
101116 </executions>
102117 </plugin>