Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changesetefe21da3636406e0e01beda34c74b73df7f078cb0217c15d112b765808a4a3f4
Authorolim7t <omichallat+github@gmail.com> · 2015-03-26 19:40 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-03-26 19:40 +01:00
Parents2358e77d8126, 2e24721d7f5d

Browse the files at this changeset

26 files changed

added .travis.yml +5 −0
@@ -0,0 +1,5 @@
1+language: java
2+jdk:
3+ - openjdk6
4+ - oraclejdk7
5+ - oraclejdk8
modified driver-core/pom.xml +9 −14
@@ -30,23 +30,19 @@
3030 <dependency>
3131 <groupId>io.netty</groupId>
3232 <artifactId>netty</artifactId>
33- <version>3.9.0.Final</version>
33+ <version>${netty.version}</version>
3434 </dependency>
3535
3636 <dependency>
3737 <groupId>com.google.guava</groupId>
3838 <artifactId>guava</artifactId>
39- <!--
40- We use an old version of Guava to be compatible with Spark 1.1.
41- Check with the spark-cassandra-connector team before upgrading this.
42- -->
43- <version>14.0.1</version>
39+ <version>${guava.version}</version>
4440 </dependency>
4541
4642 <dependency>
4743 <groupId>com.codahale.metrics</groupId>
4844 <artifactId>metrics-core</artifactId>
49- <version>3.0.2</version>
45+ <version>${metrics.version}</version>
5046 </dependency>
5147
5248 <!-- Compression libraries for the protocol. -->
@@ -55,14 +51,14 @@
5551 <dependency>
5652 <groupId>org.xerial.snappy</groupId>
5753 <artifactId>snappy-java</artifactId>
58- <version>1.0.5</version>
54+ <version>${snappy.version}</version>
5955 <optional>true</optional>
6056 </dependency>
6157
6258 <dependency>
6359 <groupId>net.jpountz.lz4</groupId>
6460 <artifactId>lz4</artifactId>
65- <version>1.2.0</version>
61+ <version>${lz4.version}</version>
6662 <optional>true</optional>
6763 </dependency>
6864
@@ -71,29 +67,28 @@
7167 <dependency>
7268 <groupId>org.testng</groupId>
7369 <artifactId>testng</artifactId>
74- <version>6.8.8</version>
70+ <version>${testng.version}</version>
7571 <scope>test</scope>
7672 </dependency>
7773
7874 <dependency>
7975 <groupId>org.assertj</groupId>
8076 <artifactId>assertj-core</artifactId>
81- <version>1.7.0</version>
77+ <version>${assertj.version}</version>
8278 <scope>test</scope>
8379 </dependency>
8480
8581 <dependency>
8682 <groupId>org.mockito</groupId>
8783 <artifactId>mockito-all</artifactId>
88- <version>1.10.8</version>
84+ <version>${mockito.version}</version>
8985 <scope>test</scope>
9086 </dependency>
9187
9288 <dependency>
9389 <groupId>org.scassandra</groupId>
9490 <artifactId>java-client</artifactId>
95- <!-- N.B. later versions of scassandra require JDK 7 -->
96- <version>0.4.1</version>
91+ <version>${scassandra.version}</version>
9792 <scope>test</scope>
9893 <exclusions>
9994 <exclusion>
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +0 −2
@@ -141,9 +141,7 @@
141141 currentAttempt.compareAndSet(handlerFuture, null);
142142 }
143143 } catch (InterruptedException e) {
144- // If interrupted, skip this attempt but still skip scheduling reconnections
145144 Thread.currentThread().interrupt();
146- reschedule(schedule.nextDelayMs());
147145 } catch (UnsupportedProtocolVersionException e) {
148146 logger.error(e.getMessage());
149147 long nextDelay = schedule.nextDelayMs();
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +2 −1
@@ -48,7 +48,8 @@
4848 public enum Type {
4949 /**
5050 * A logged batch: Cassandra will first write the batch to its distributed batch log
51- * to ensure the atomicity of the batch.
51+ * to ensure the atomicity of the batch (atomicity meaning that if any statement in
52+ * the batch succeeds, all will eventually succeed).
5253 */
5354 LOGGED,
5455
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +12 −6
@@ -1122,12 +1122,12 @@
11221122 return "cluster" + CLUSTER_ID.incrementAndGet();
11231123 }
11241124
1125- private static ListeningExecutorService makeExecutor(int threads, String name) {
1125+ private static ListeningExecutorService makeExecutor(int threads, String name, LinkedBlockingQueue<Runnable> workQueue) {
11261126 ThreadPoolExecutor executor = new ThreadPoolExecutor(threads,
11271127 threads,
11281128 DEFAULT_THREAD_KEEP_ALIVE,
11291129 TimeUnit.SECONDS,
1130- new LinkedBlockingQueue<Runnable>(),
1130+ workQueue,
11311131 threadFactory(name));
11321132
11331133 executor.allowCoreThreadTimeOut(true);
@@ -1160,17 +1160,23 @@
11601160
11611161 final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.Simple.Factory();
11621162
1163- final ScheduledExecutorService reconnectionExecutor = Executors.newScheduledThreadPool(2, threadFactory("Reconnection-%d"));
1163+ final ScheduledThreadPoolExecutor reconnectionExecutor = new ScheduledThreadPoolExecutor(2, threadFactory("Reconnection-%d"));
11641164 // scheduledTasksExecutor is used to process C* notifications. So having it mono-threaded ensures notifications are
11651165 // applied in the order received.
1166- final ScheduledExecutorService scheduledTasksExecutor = Executors.newScheduledThreadPool(1, threadFactory("Scheduled Tasks-%d"));
1166+ final ScheduledThreadPoolExecutor scheduledTasksExecutor = new ScheduledThreadPoolExecutor(1, threadFactory("Scheduled Tasks-%d"));
11671167
11681168 // Executor used for tasks that shouldn't be executed on an IO thread. Used for short-lived, generally non-blocking tasks
11691169 final ListeningExecutorService executor;
11701170
1171+ // Work Queue used by executor.
1172+ final LinkedBlockingQueue<Runnable> executorQueue = new LinkedBlockingQueue<Runnable>();
1173+
11711174 // An executor for tasks that might block some time, like creating new connection, but are generally not too critical.
11721175 final ListeningExecutorService blockingExecutor;
11731176
1177+ // Work Queue used by blockingExecutor.
1178+ final LinkedBlockingQueue<Runnable> blockingExecutorQueue = new LinkedBlockingQueue<Runnable>();
1179+
11741180 final ConnectionReaper reaper;
11751181
11761182 final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
@@ -1191,8 +1197,8 @@
11911197 this.configuration = configuration;
11921198 this.configuration.register(this);
11931199
1194- this.executor = makeExecutor(NON_BLOCKING_EXECUTOR_SIZE, "Cassandra Java Driver worker-%d");
1195- this.blockingExecutor = makeExecutor(2, "Cassandra Java Driver blocking tasks worker-%d");
1200+ this.executor = makeExecutor(NON_BLOCKING_EXECUTOR_SIZE, "Cassandra Java Driver worker-%d", executorQueue);
1201+ this.blockingExecutor = makeExecutor(2, "Cassandra Java Driver blocking tasks worker-%d", blockingExecutorQueue);
11961202
11971203 this.reaper = new ConnectionReaper();
11981204
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +58 −0
@@ -70,6 +70,34 @@
7070 }
7171 });
7272
73+ private final Gauge<Integer> executorQueueDepth = registry.register("executor-queue-depth", new Gauge<Integer>() {
74+ @Override
75+ public Integer getValue() {
76+ return manager.executorQueue.size();
77+ }
78+ });
79+
80+ private final Gauge<Integer> blockingExecutorQueueDepth = registry.register("blocking-executor-queue-depth", new Gauge<Integer>() {
81+ @Override
82+ public Integer getValue() {
83+ return manager.blockingExecutorQueue.size();
84+ }
85+ });
86+
87+ private final Gauge<Integer> reconnectionSchedulerQueueSize= registry.register("reconnection-scheduler-task-count", new Gauge<Integer>() {
88+ @Override
89+ public Integer getValue() {
90+ return manager.reconnectionExecutor.getQueue().size();
91+ }
92+ });
93+
94+ private final Gauge<Integer> taskSchedulerQueueSize = registry.register("task-scheduler-task-count", new Gauge<Integer>() {
95+ @Override
96+ public Integer getValue() {
97+ return manager.scheduledTasksExecutor.getQueue().size();
98+ }
99+ });
100+
73101 Metrics(Cluster.Manager manager) {
74102 this.manager = manager;
75103 if (manager.configuration.getMetricsOptions().isJMXReportingEnabled()) {
@@ -177,6 +205,36 @@
177205 return openConnections;
178206 }
179207
208+ /**
209+ * @return The number of queued up tasks in the non-blocking executor (Cassandra Java Driver workers).
210+ */
211+ public Gauge<Integer> getExecutorQueueDepth() {
212+ return executorQueueDepth;
213+ }
214+
215+ /**
216+ * @return The number of queued up tasks in the blocking executor (Cassandra Java Driver blocking tasks worker).
217+ */
218+ public Gauge<Integer> getBlockingExecutorQueueDepth() {
219+ return blockingExecutorQueueDepth;
220+ }
221+
222+ /**
223+ * @return The size of the work queue for the reconnection scheduler (Reconnection). A queue size > 0 does not
224+ * necessarily indicate a backlog as some tasks may not have been scheduled to execute yet.
225+ */
226+ public Gauge<Integer> getReconnectionSchedulerQueueSize() {
227+ return reconnectionSchedulerQueueSize;
228+ }
229+
230+ /**
231+ * @return The size of the work queue for the task scheduler (Scheduled Tasks). A queue size > 0 does not
232+ * necessarily indicate a backlog as some tasks may not have been scheduled to execute yet.
233+ */
234+ public Gauge<Integer> getTaskSchedulerQueueSize() {
235+ return taskSchedulerQueueSize;
236+ }
237+
180238 void shutdown() {
181239 if (jmxReporter != null)
182240 jmxReporter.stop();
modified driver-core/src/main/java/com/datastax/driver/core/WriteType.java +4 −1
@@ -26,7 +26,10 @@
2626 {
2727 /** A write to a single partition key. Such writes are guaranteed to be atomic and isolated. */
2828 SIMPLE,
29- /** A write to a multiple partition key that used the distributed batch log to ensure atomicity. */
29+ /**
30+ * A write to a multiple partition key that used the distributed batch log to ensure atomicity
31+ * (atomicity meaning that if any statement in the batch succeeds, all will eventually succeed).
32+ */
3033 BATCH,
3134 /** A write to a multiple partition key that doesn't use the distributed batch log. Atomicity for such writes is not guaranteed */
3235 UNLOGGED_BATCH,
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +219 −73
@@ -15,33 +15,34 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.datastax.driver.core.Cluster.Builder;
19-import com.datastax.driver.core.exceptions.AlreadyExistsException;
20-import com.datastax.driver.core.exceptions.DriverException;
21-import com.datastax.driver.core.exceptions.NoHostAvailableException;
22-
23-import com.google.common.base.Joiner;
24-import com.google.common.io.Files;
25-import org.slf4j.Logger;
26-import org.slf4j.LoggerFactory;
27-import org.testng.annotations.AfterClass;
28-import org.testng.annotations.BeforeClass;
29-
30-import java.io.BufferedReader;
31-import java.io.File;
32-import java.io.IOException;
33-import java.io.InputStreamReader;
18+import java.io.*;
3419 import java.net.InetAddress;
3520 import java.net.InetSocketAddress;
3621 import java.net.Socket;
3722 import java.net.UnknownHostException;
3823 import java.util.Collection;
24+import java.util.Collections;
3925 import java.util.Map;
4026 import java.util.concurrent.TimeUnit;
27+import java.util.concurrent.atomic.AtomicLong;
4128
42-import static org.testng.Assert.fail;
29+import com.google.common.base.Joiner;
30+import com.google.common.collect.ImmutableMap;
31+import com.google.common.io.ByteStreams;
32+import com.google.common.io.Closer;
33+import com.google.common.io.Files;
34+import org.slf4j.Logger;
35+import org.slf4j.LoggerFactory;
36+import org.testng.annotations.AfterClass;
37+import org.testng.annotations.BeforeClass;
4338
4439 import static com.google.common.base.Preconditions.checkArgument;
40+import static org.testng.Assert.fail;
41+
42+import com.datastax.driver.core.Cluster.Builder;
43+import com.datastax.driver.core.exceptions.AlreadyExistsException;
44+import com.datastax.driver.core.exceptions.DriverException;
45+import com.datastax.driver.core.exceptions.NoHostAvailableException;
4546
4647 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
4748 import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE;
@@ -54,8 +55,25 @@
5455
5556 private static final String CASSANDRA_VERSION_REGEXP = "\\d\\.\\d\\.\\d+(-\\w+)?";
5657
58+ public static final String DEFAULT_CLIENT_TRUSTSTORE_PASSWORD = "cassandra1sfun";
59+ public static final String DEFAULT_CLIENT_TRUSTSTORE_PATH = "/client.truststore";
60+
61+ public static final String DEFAULT_CLIENT_KEYSTORE_PASSWORD = "cassandra1sfun";
62+ public static final String DEFAULT_CLIENT_KEYSTORE_PATH = "/client.keystore";
63+
64+ public static final String DEFAULT_SERVER_TRUSTSTORE_PASSWORD = "cassandra1sfun";
65+ public static final String DEFAULT_SERVER_TRUSTSTORE_PATH = "/server.truststore";
66+
67+ private static final File DEFAULT_SERVER_TRUSTSTORE_FILE = createTempStore(DEFAULT_SERVER_TRUSTSTORE_PATH);
68+
69+ public static final String DEFAULT_SERVER_KEYSTORE_PASSWORD = "cassandra1sfun";
70+ public static final String DEFAULT_SERVER_KEYSTORE_PATH = "/server.keystore";
71+
72+ private static final File DEFAULT_SERVER_KEYSTORE_FILE = createTempStore(DEFAULT_SERVER_KEYSTORE_PATH);
73+
5774 static final File CASSANDRA_DIR;
5875 static final String CASSANDRA_VERSION;
76+
5977 static {
6078 String version = System.getProperty("cassandra.version");
6179 if (version.matches(CASSANDRA_VERSION_REGEXP)) {
@@ -80,18 +98,53 @@
8098 this.ccmDir = Files.createTempDir();
8199 }
82100
83- public static CCMBridge create(String name) {
101+ /**
102+ * <p>
103+ * Extracts a keystore from the classpath into a temporary file.
104+ * </p>
105+ *
106+ * <p>
107+ * This is needed as the keystore could be part of a built test jar used by other
108+ * projects, and they need to be extracted to a file system so cassandra may use them.
109+ * </p>
110+ * @param storePath Path in classpath where the keystore exists.
111+ * @return The generated File.
112+ */
113+ private static File createTempStore(String storePath) {
114+ File f = null;
115+ Closer closer = Closer.create();
116+ try {
117+ InputStream trustStoreIs = CCMBridge.class.getResourceAsStream(storePath);
118+ closer.register(trustStoreIs);
119+ f = File.createTempFile("server", ".store");
120+ logger.debug("Created store file {} for {}.", f, storePath);
121+ OutputStream trustStoreOs = new FileOutputStream(f);
122+ closer.register(trustStoreOs);
123+ ByteStreams.copy(trustStoreIs, trustStoreOs);
124+ } catch (IOException e) {
125+ logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e);
126+ } finally {
127+ try {
128+ closer.close();
129+ } catch (IOException e) {
130+ logger.warn("Failure closing streams.", e);
131+ }
132+ }
133+ return f;
134+ }
135+
136+ public static CCMBridge create(String name, String... options) {
84137 // This leads to a confusing CCM error message so check explicitly:
85138 checkArgument(!"current".equals(name.toLowerCase()),
86- "cluster can't be called \"current\"");
139+ "cluster can't be called \"current\"");
87140 CCMBridge bridge = new CCMBridge();
88- bridge.execute("ccm create %s -b -i %s %s", name, IP_PREFIX, CASSANDRA_VERSION);
141+ bridge.execute("ccm create %s -b -i %s %s " + Joiner.on(" ").join(options), name, IP_PREFIX, CASSANDRA_VERSION);
89142 return bridge;
90143 }
91144
92145 public static CCMBridge create(String name, int nbNodes, String... options) {
93146 checkArgument(!"current".equals(name.toLowerCase()),
94- "cluster can't be called \"current\"");
147+ "cluster can't be called \"current\"");
95148 CCMBridge bridge = new CCMBridge();
96149 bridge.execute("ccm create %s -n %d -s -i %s -b %s " + Joiner.on(" ").join(options), name, nbNodes, IP_PREFIX, CASSANDRA_VERSION);
97150 return bridge;
@@ -107,7 +160,7 @@
107160
108161 public static CCMBridge create(String name, int nbNodesDC1, int nbNodesDC2) {
109162 checkArgument(!"current".equals(name.toLowerCase()),
110- "cluster can't be called \"current\"");
163+ "cluster can't be called \"current\"");
111164 CCMBridge bridge = new CCMBridge();
112165 bridge.execute("ccm create %s -n %d:%d -s -i %s -b %s", name, nbNodesDC1, nbNodesDC2, IP_PREFIX, CASSANDRA_VERSION);
113166 return bridge;
@@ -148,6 +201,11 @@
148201 execute("ccm node%d stop", n);
149202 }
150203
204+ public void stop(String clusterName) {
205+ logger.info("Stopping Cluster : "+clusterName);
206+ execute("ccm stop "+clusterName);
207+ }
208+
151209 public void forceStop(int n) {
152210 logger.info("Force stopping: " + IP_PREFIX + n);
153211 execute("ccm node%d stop --not-gently", n);
@@ -158,6 +216,11 @@
158216 execute("ccm remove");
159217 }
160218
219+ public void remove(String clusterName) {
220+ stop(clusterName);
221+ execute("ccm remove " + clusterName);
222+ }
223+
161224 public void remove(int n) {
162225 logger.info("Removing: " + IP_PREFIX + n);
163226 execute("ccm node%d remove", n);
@@ -177,9 +240,19 @@
177240
178241 public void bootstrapNode(int n, String dc) {
179242 if (dc == null)
180- execute("ccm add node%d -i %s%d -j %d -r %d -b -s", n, IP_PREFIX, n, 7000 + 100*n, 8000 + 100*n);
243+ execute("ccm add node%d -i %s%d -j %d -r %d -b -s", n, IP_PREFIX, n, 7000 + 100 * n, 8000 + 100 * n);
181244 else
182- execute("ccm add node%d -i %s%d -j %d -b -d %s -s", n, IP_PREFIX, n, 7000 + 100*n, dc);
245+ execute("ccm add node%d -i %s%d -j %d -b -d %s -s", n, IP_PREFIX, n, 7000 + 100 * n, dc);
246+ execute("ccm node%d start --wait-other-notice --wait-for-binary-proto", n);
247+ }
248+
249+ public void bootstrapNodeWithPorts(int n, int thriftPort, int storagePort, int binaryPort, int jmxPort, int remoteDebugPort) {
250+ String thriftItf = IP_PREFIX + n + ":" + thriftPort;
251+ String storageItf = IP_PREFIX + n + ":" + storagePort;
252+ String binaryItf = IP_PREFIX + n + ":" + binaryPort;
253+ String remoteLogItf = IP_PREFIX + n + ":" + remoteDebugPort;
254+ execute("ccm add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s",
255+ n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf);
183256 execute("ccm node%d start --wait-other-notice --wait-for-binary-proto", n);
184257 }
185258
@@ -188,7 +261,15 @@
188261 }
189262
190263 public void updateConfig(String name, String value) {
191- execute("ccm updateconf %s:%s", name, value);
264+ updateConfig(ImmutableMap.of(name, value));
265+ }
266+
267+ public void updateConfig(Map<String, String> configs) {
268+ StringBuilder confStr = new StringBuilder();
269+ for (Map.Entry<String, String> entry : configs.entrySet()) {
270+ confStr.append(entry.getKey() + ":" + entry.getValue() + " ");
271+ }
272+ execute("ccm updateconf " + confStr);
192273 }
193274
194275 public void populate(int n) {
@@ -269,6 +350,33 @@
269350 }
270351 }
271352
353+ /**
354+ * Enables SSL without client authentication. Does not apply to already started nodes.
355+ */
356+ public void enableSSL() {
357+ enableSSL(false);
358+ }
359+
360+ /**
361+ * Enables SSL. Does not apply to already started nodes.
362+ * @param requireClientAuth Whether or not to require Clients used authentication.
363+ */
364+ public void enableSSL(boolean requireClientAuth) {
365+ ImmutableMap.Builder<String, String> configs = ImmutableMap.builder();
366+
367+ configs.put("client_encryption_options.enabled", "true");
368+ configs.put("client_encryption_options.keystore", DEFAULT_SERVER_KEYSTORE_FILE.getAbsolutePath());
369+ configs.put("client_encryption_options.keystore_password", DEFAULT_SERVER_KEYSTORE_PASSWORD);
370+
371+ if (requireClientAuth) {
372+ configs.put("client_encryption_options.require_client_auth", "true");
373+ configs.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath());
374+ configs.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD);
375+ }
376+
377+ updateConfig(configs.build());
378+ }
379+
272380 private static void busyWaitForPort(InetAddress address, int port, boolean expectedConnectionState) {
273381 long maxAcceptableWaitTime = TimeUnit.SECONDS.toMillis(10);
274382 long waitQuantum = TimeUnit.MILLISECONDS.toMillis(500);
@@ -311,12 +419,37 @@
311419 return IP_PREFIX + Integer.toString(nodeNumber);
312420 }
313421
422+ public static class terminationHook extends Thread {
423+ public void run() {
424+ logger.debug("shut down hook task..");
425+
426+ if (PerClassSingleNodeCluster.cluster != null) {
427+ PerClassSingleNodeCluster.cluster.close();
428+ }
429+ if (PerClassSingleNodeCluster.ccmBridge == null) {
430+ logger.error("No cluster to discard");
431+ } else if (PerClassSingleNodeCluster.erroredOut) {
432+ PerClassSingleNodeCluster.ccmBridge.remove("test-class");
433+ logger.info("Error during tests, kept C* logs in " + PerClassSingleNodeCluster.ccmBridge.ccmDir);
434+ } else {
435+ PerClassSingleNodeCluster.ccmBridge.remove("test-class");
436+ PerClassSingleNodeCluster.ccmBridge.ccmDir.delete();
437+ }
438+
439+ }
440+ }
441+
314442 // One cluster for the whole test class
315443 public static abstract class PerClassSingleNodeCluster {
316444
317- protected static CCMBridge cassandraCluster;
445+ protected static CCMBridge ccmBridge;
318446 private static boolean erroredOut;
319- private static boolean schemaCreated;
447+ private static boolean clusterInitialized=false;
448+ private static AtomicLong ksNumber;
449+ protected String keyspace;
450+
451+ protected static InetSocketAddress hostAddress;
452+ protected static int[] ports;
320453
321454 protected static Cluster cluster;
322455 protected static Session session;
@@ -332,59 +465,57 @@
332465 erroredOut = true;
333466 }
334467
335- public void createCluster() {
336- erroredOut = false;
337- schemaCreated = false;
338- cassandraCluster = CCMBridge.create("test", 1);
339- try {
340- Builder builder = Cluster.builder();
341- builder = configure(builder);
342- cluster = builder.addContactPoints(IP_PREFIX + '1').build();
343- session = cluster.connect();
344- } catch (NoHostAvailableException e) {
345- erroredOut = true;
346- for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
347- logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue());
348- throw new RuntimeException(e);
349- }
468+ @BeforeClass(groups = { "short", "long" })
469+ public void beforeClass() {
470+ maybeInitCluster();
471+ initKeyspace();
350472 }
351473
352- @AfterClass(groups = {"short", "long"})
353- public static void discardCluster() {
354- if (cluster != null)
355- cluster.close();
474+ @AfterClass(groups = { "short", "long" })
475+ public void afterClass() {
476+ clearSimpleKeyspace();
477+ }
356478
357- if (cassandraCluster == null) {
358- logger.error("No cluster to discard");
359- } else if (erroredOut) {
360- cassandraCluster.stop();
361- logger.info("Error during tests, kept C* logs in " + cassandraCluster.ccmDir);
362- } else {
363- cassandraCluster.remove();
364- cassandraCluster.ccmDir.delete();
479+ private void maybeInitCluster(){
480+ if (!clusterInitialized){
481+ try {
482+ //launch ccm cluster
483+ ccmBridge = CCMBridge.create("test-class");
484+
485+ ports = new int[5];
486+ for (int i = 0; i < 5; i++) {
487+ ports[i] = TestUtils.findAvailablePort(10000 + i);
488+ }
489+
490+ ccmBridge.bootstrapNodeWithPorts(1, ports[0], ports[1], ports[2], ports[3], ports[4]);
491+ ksNumber = new AtomicLong(0);
492+ erroredOut = false;
493+ hostAddress = new InetSocketAddress(InetAddress.getByName(IP_PREFIX + 1), ports[2]);
494+
495+ Runtime r = Runtime.getRuntime();
496+ r.addShutdownHook(new terminationHook());
497+ clusterInitialized = true;
498+
499+ } catch (UnknownHostException e) {
500+ throw new RuntimeException(e);
501+ }
365502 }
366- }
367503
368- @BeforeClass(groups = {"short", "long"})
369- public void beforeClass() {
370- createCluster();
371- maybeCreateSchema();
372504 }
373505
374- public void maybeCreateSchema() {
375506
507+ private void initKeyspace() {
376508 try {
377- if (schemaCreated)
378- return;
509+ Builder builder = Cluster.builder();
379510
380- try {
381- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, SIMPLE_KEYSPACE, 1));
382- } catch (AlreadyExistsException e) {
383- // It's ok, ignore
384- }
511+ builder = configure(builder);
385512
386- session.execute("USE " + SIMPLE_KEYSPACE);
513+ cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)).build();
514+ session = cluster.connect();
515+ keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet();
516+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
387517
518+ session.execute("USE " + keyspace);
388519 for (String tableDef : getTableDefinitions()) {
389520 try {
390521 session.execute(tableDef);
@@ -392,13 +523,26 @@
392523 // It's ok, ignore
393524 }
394525 }
395-
396- schemaCreated = true;
526+ } catch (AlreadyExistsException e) {
527+ // It's ok, ignore (not supposed to go there)
528+ } catch (NoHostAvailableException e) {
529+ erroredOut = true;
530+ for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
531+ logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue());
532+ throw new RuntimeException(e);
397533 } catch (DriverException e) {
398534 erroredOut = true;
399535 throw e;
400536 }
401537 }
538+
539+ private void clearSimpleKeyspace() {
540+ session.execute("DROP KEYSPACE " + keyspace);
541+ if (cluster != null) {
542+ cluster.close();
543+ }
544+ }
545+
402546 }
403547
404548 public static class CCMCluster {
@@ -433,10 +577,12 @@
433577 try {
434578 String[] contactPoints = new String[totalNodes];
435579 for (int i = 0; i < totalNodes; i++)
436- contactPoints[i] = IP_PREFIX + (i+1);
437-
438- try { Thread.sleep(1000); } catch (Exception e) {}
580+ contactPoints[i] = IP_PREFIX + (i + 1);
439581
582+ try {
583+ Thread.sleep(1000);
584+ } catch (Exception e) {
585+ }
440586 this.cluster = builder.addContactPoints(contactPoints).build();
441587 this.session = cluster.connect();
442588 } catch (NoHostAvailableException e) {
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +6 −7
@@ -17,12 +17,11 @@
1717
1818 import java.util.*;
1919
20-import static org.testng.Assert.assertFalse;
21-
2220 import org.testng.annotations.Test;
2321
2422 import static org.assertj.core.api.Assertions.assertThat;
2523 import static org.testng.Assert.assertEquals;
24+import static org.testng.Assert.assertFalse;
2625 import static org.testng.Assert.assertTrue;
2726
2827 import com.datastax.driver.core.exceptions.NoHostAvailableException;
@@ -305,10 +304,10 @@
305304
306305 assertEquals(session.execute(ps.bind("123")).one().getInt("i"), 17);
307306
308- cassandraCluster.stop();
307+ ccmBridge.stop();
309308 waitForDown(CCMBridge.IP_PREFIX + '1', cluster);
310309
311- cassandraCluster.start();
310+ ccmBridge.start();
312311 waitFor(CCMBridge.IP_PREFIX + '1', cluster, 120);
313312
314313 try
@@ -332,7 +331,7 @@
332331
333332 // This is the same test than reprepareOnNewlyUpNodeTest, except that the
334333 // prepared statement is prepared while no current keyspace is used
335- reprepareOnNewlyUpNodeTest(TestUtils.SIMPLE_KEYSPACE, cluster.connect());
334+ reprepareOnNewlyUpNodeTest(keyspace, cluster.connect());
336335 }
337336
338337 @Test(groups = "short")
@@ -434,9 +433,9 @@
434433
435434 @Test(groups="short")
436435 public void should_set_routing_key_on_case_insensitive_keyspace_and_table() {
437- session.execute("CREATE TABLE ks.foo (i int PRIMARY KEY)");
436+ session.execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)",keyspace));
438437
439- PreparedStatement ps = session.prepare("INSERT INTO ks.foo (i) VALUES (?)");
438+ PreparedStatement ps = session.prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)",keyspace));
440439 BoundStatement bs = ps.bind(1);
441440 assertThat(bs.getRoutingKey()).isNotNull();
442441 }
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +2 −0
@@ -7,12 +7,14 @@
77 import org.testng.annotations.AfterMethod;
88 import org.testng.annotations.Test;
99
10+
1011 import com.datastax.driver.core.utils.CassandraVersion;
1112
1213 import static com.datastax.driver.core.Assertions.*;
1314 import static com.datastax.driver.core.Host.State.DOWN;
1415 import static com.datastax.driver.core.Host.State.UP;
1516
17+
1618 /**
1719 * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
1820 *
added driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +47 −0
@@ -0,0 +1,47 @@
1+package com.datastax.driver.core;
2+
3+import com.google.common.base.Optional;
4+import org.testng.annotations.Test;
5+
6+import com.datastax.driver.core.exceptions.NoHostAvailableException;
7+
8+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH;
9+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH;
10+
11+public class SSLAuthenticatedEncryptionTest extends SSLTestBase {
12+
13+ public SSLAuthenticatedEncryptionTest() {
14+ super(true);
15+ }
16+
17+ /**
18+ * <p>
19+ * Validates that an SSL connection can be established with client auth if the target
20+ * cassandra cluster is using SSL, requires client auth and would validate with the client's
21+ * certificate.
22+ * </p>
23+ *
24+ * @test_category connection:ssl, authentication
25+ * @expected_result Connection can be established to a cassandra node using SSL that requires client auth.
26+ */
27+ @Test(groups="short")
28+ public void should_connect_with_ssl_with_client_auth_and_node_requires_auth() throws Exception {
29+ connectWithSSLOptions(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
30+ }
31+
32+
33+ /**
34+ * <p>
35+ * Validates that an SSL connection can not be established with if the target
36+ * cassandra cluster is using SSL, requires client auth, but the client does not provide
37+ * sufficient certificate authentication.
38+ * </p>
39+ *
40+ * @test_category connection:ssl, authentication
41+ * @expected_result Connection is not established.
42+ */
43+ @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
44+ public void should_not_connect_without_client_auth_but_node_requires_auth() throws Exception {
45+ connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
46+ }
47+}
added driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +106 −0
@@ -0,0 +1,106 @@
1+package com.datastax.driver.core;
2+
3+import java.util.concurrent.TimeUnit;
4+
5+import com.google.common.base.Optional;
6+import org.testng.annotations.Test;
7+
8+import com.datastax.driver.core.exceptions.NoHostAvailableException;
9+
10+import static com.datastax.driver.core.Assertions.assertThat;
11+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH;
12+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH;
13+
14+public class SSLEncryptionTest extends SSLTestBase {
15+
16+ public SSLEncryptionTest() {
17+ super(false);
18+ }
19+
20+ /**
21+ * <p>
22+ * Validates that an SSL connection can be established without client auth if the target
23+ * cassandra cluster is using SSL and does not require auth.
24+ * </p>
25+ *
26+ * @test_category connection:ssl
27+ * @expected_result Connection can be established to a cassandra node using SSL.
28+ */
29+ @Test(groups="short")
30+ public void should_connect_with_ssl_without_client_auth_and_node_doesnt_require_auth() throws Exception {
31+ connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
32+ }
33+
34+ /**
35+ * <p>
36+ * Validates that an SSL connection can not be established if the client does not trust
37+ * the cassandra node's certificate.
38+ * </p>
39+ *
40+ * @test_category connection:ssl
41+ * @expected_result Connection can not be established to a cassandra node using SSL with an untrusted cert.
42+ */
43+ @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
44+ public void should_not_connect_with_ssl_without_trusting_server_cert() throws Exception {
45+ connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.<String>absent()));
46+ }
47+
48+ /**
49+ * <p>
50+ * Validates that an SSL connection can not be established if the client is not specifying SSL, but
51+ * the cassandra node is using SSL.
52+ * </p>
53+ *
54+ * <p>
55+ * Note that future versions of cassandra may support both SSL-encrypted and non-SSL connections
56+ * simultaneously (CASSANDRA-8803)
57+ * </p>
58+ *
59+ * @test_category connection:ssl
60+ * @expected_result Connection can not be established to a cassandra node using SSL and the client not using SSL.
61+ */
62+ @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
63+ public void should_not_connect_without_ssl_but_node_uses_ssl() throws Exception {
64+ Cluster cluster = null;
65+ try {
66+ cluster = Cluster.builder()
67+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
68+ .build();
69+
70+ cluster.connect();
71+ } finally {
72+ if (cluster != null)
73+ cluster.close();
74+ }
75+ }
76+
77+ /**
78+ * <p>
79+ * Validates that if connection is lost to a node that is using SSL authentication, that connection can be
80+ * re-established when the node becomes available again.
81+ * </p>
82+ *
83+ * @test_category connection:ssl
84+ * @expected_result Connection is re-established within a sufficient amount of time after a node comes back online.
85+ */
86+ @Test(groups="long")
87+ public void should_reconnect_with_ssl_on_node_up() throws Exception {
88+ Cluster cluster = null;
89+ try {
90+ cluster = Cluster.builder()
91+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
92+ .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)))
93+ .build();
94+
95+ cluster.connect();
96+
97+ ccm.stop(1);
98+ ccm.start(1);
99+
100+ assertThat(cluster).host(1).comesUpWithin(TestUtils.TEST_BASE_NODE_WAIT, TimeUnit.SECONDS);
101+ } finally {
102+ if (cluster != null)
103+ cluster.close();
104+ }
105+ }
106+}
added driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +100 −0
@@ -0,0 +1,100 @@
1+package com.datastax.driver.core;
2+
3+import java.security.KeyStore;
4+import java.security.SecureRandom;
5+import java.util.concurrent.TimeUnit;
6+
7+import com.google.common.base.Optional;
8+import javax.net.ssl.KeyManagerFactory;
9+import javax.net.ssl.SSLContext;
10+import javax.net.ssl.TrustManagerFactory;
11+import org.testng.annotations.AfterClass;
12+import org.testng.annotations.BeforeClass;
13+import org.testng.annotations.Test;
14+
15+import com.datastax.driver.core.exceptions.NoHostAvailableException;
16+
17+import static com.datastax.driver.core.Assertions.assertThat;
18+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD;
19+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH;
20+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD;
21+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH;
22+public abstract class SSLTestBase {
23+
24+ private final boolean requireClientAuth;
25+
26+ protected CCMBridge ccm;
27+
28+ public SSLTestBase(boolean requireClientAuth) {
29+ this.requireClientAuth = requireClientAuth;
30+ }
31+
32+ @BeforeClass(groups={"short", "long"})
33+ public void beforeClass() {
34+ ccm = CCMBridge.create("test");
35+ ccm.enableSSL(requireClientAuth);
36+ ccm.bootstrapNode(1);
37+ }
38+
39+ @AfterClass(groups={"short", "long"})
40+ public void afterClass() {
41+ ccm.remove();
42+ }
43+
44+ /**
45+ * <p>
46+ * Attempts to connect to a cassandra cluster with the given SSLOptions and then closes the
47+ * created {@link Cluster} instance.
48+ * </p>
49+ *
50+ * @param sslOptions SSLOptions to use.
51+ * @throws Exception A {@link com.datastax.driver.core.exceptions.NoHostAvailableException} will be
52+ * raised here if connection cannot be established.
53+ */
54+ protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception {
55+ Cluster cluster = null;
56+ try {
57+ cluster = Cluster.builder()
58+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
59+ .withSSL(sslOptions)
60+ .build();
61+
62+ cluster.connect();
63+ } finally {
64+ if (cluster != null)
65+ cluster.close();
66+ }
67+ }
68+
69+ /**
70+ * @param keyStorePath Path to keystore, if absent is not used.
71+ * @param trustStorePath Path to truststore, if absent is not used.
72+ * @return {@link com.datastax.driver.core.SSLOptions} with the given keystore and truststore path's for
73+ * server certificate validation and client certificate authentication.
74+ */
75+ public SSLOptions getSSLOptions(Optional<String> keyStorePath, Optional<String> trustStorePath) throws Exception {
76+
77+ TrustManagerFactory tmf = null;
78+ if(trustStorePath.isPresent()) {
79+ KeyStore ks = KeyStore.getInstance("JKS");
80+ ks.load(this.getClass().getResourceAsStream(trustStorePath.get()), DEFAULT_CLIENT_TRUSTSTORE_PASSWORD.toCharArray());
81+
82+ tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
83+ tmf.init(ks);
84+ }
85+
86+ KeyManagerFactory kmf = null;
87+ if(keyStorePath.isPresent()) {
88+ KeyStore ks = KeyStore.getInstance("JKS");
89+ ks.load(this.getClass().getResourceAsStream(keyStorePath.get()), DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
90+
91+ kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
92+ kmf.init(ks, DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
93+ }
94+
95+ SSLContext sslContext = SSLContext.getInstance("TLS");
96+ sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null, new SecureRandom());
97+
98+ return new SSLOptions(sslContext, SSLOptions.DEFAULT_SSL_CIPHER_SUITES);
99+ }
100+}
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +40 −27
@@ -1,6 +1,5 @@
11 package com.datastax.driver.core;
22
3-import java.util.Collection;
43 import java.util.List;
54
65 import com.google.common.collect.Lists;
@@ -13,27 +12,47 @@
1312
1413 import static com.datastax.driver.core.Assertions.assertThat;
1514
16-public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster {
15+public class SchemaChangesTest {
16+ private static final String CREATE_KEYSPACE =
17+ "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }";
1718
18- // Create a second cluster to check that other clients also get notified
19- Cluster cluster2;
20- // The metadatas of the two clusters should be kept in sync
21- List<Metadata> metadatas;
19+ CCMBridge ccm;
20+ Cluster cluster;
21+ Cluster cluster2; // a second cluster to check that other clients also get notified
2222
23- @Override
24- protected Collection<String> getTableDefinitions() {
25- return Lists.newArrayList("CREATE KEYSPACE \"CaseSensitive\" WITH REPLICATION = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor': '1' }");
26- }
23+ // The metadatas of the two clusters (we'll test that they're kept in sync)
24+ List<Metadata> metadatas;
2725
28- @DataProvider(name = "existingKeyspaceName")
29- public static Object[][] existingKeyspaceName() {
30- return new Object[][]{ { "ks" }, { "\"CaseSensitive\"" } };
31- }
26+ Session session;
3227
3328 @BeforeClass(groups = "short")
3429 public void setup() {
30+ ccm = CCMBridge.create("schemaChangesTest", 1);
31+
32+ cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
3533 cluster2 = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
34+
3635 metadatas = Lists.newArrayList(cluster.getMetadata(), cluster2.getMetadata());
36+
37+ session = cluster.connect();
38+ session.execute(String.format(CREATE_KEYSPACE, "lowercase"));
39+ session.execute(String.format(CREATE_KEYSPACE, "\"CaseSensitive\""));
40+ }
41+
42+ @AfterClass(groups = "short")
43+ public void teardown() {
44+ if (cluster != null)
45+ cluster.close();
46+ if (cluster2 != null)
47+ cluster2.close();
48+ if (ccm != null)
49+ ccm.remove();
50+ }
51+
52+
53+ @DataProvider(name = "existingKeyspaceName")
54+ public static Object[][] existingKeyspaceName() {
55+ return new Object[][]{ { "lowercase" }, { "\"CaseSensitive\"" } };
3756 }
3857
3958 @Test(groups = "short", dataProvider = "existingKeyspaceName")
@@ -99,12 +118,12 @@
99118
100119 @DataProvider(name = "newKeyspaceName")
101120 public static Object[][] newKeyspaceName() {
102- return new Object[][]{ { "ks2" }, { "\"CaseSensitive2\"" } };
121+ return new Object[][]{ { "lowercase2" }, { "\"CaseSensitive2\"" } };
103122 }
104123
105124 @Test(groups = "short", dataProvider = "newKeyspaceName")
106125 public void should_notify_of_keyspace_creation(String keyspace) {
107- session.execute(String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace));
126+ session.execute(String.format(CREATE_KEYSPACE, keyspace));
108127
109128 for (Metadata m : metadatas)
110129 assertThat(m.getKeyspace(keyspace))
@@ -113,7 +132,7 @@
113132
114133 @Test(groups = "short", dataProvider = "newKeyspaceName")
115134 public void should_notify_of_keyspace_update(String keyspace) {
116- session.execute(String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace));
135+ session.execute(String.format(CREATE_KEYSPACE, keyspace));
117136 for (Metadata m : metadatas)
118137 assertThat(m.getKeyspace(keyspace).isDurableWrites())
119138 .isTrue();
@@ -126,7 +145,7 @@
126145
127146 @Test(groups = "short", dataProvider = "newKeyspaceName")
128147 public void should_notify_of_keyspace_drop(String keyspace) {
129- session.execute(String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace));
148+ session.execute(String.format(CREATE_KEYSPACE, keyspace));
130149 for (Metadata m : metadatas)
131150 assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE")))
132151 .isNotEmpty();
@@ -144,19 +163,13 @@
144163 @AfterMethod(groups = "short")
145164 public void cleanup() {
146165 ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList(
147- session.executeAsync("DROP TABLE ks.table1"),
166+ session.executeAsync("DROP TABLE lowercase.table1"),
148167 session.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
149- session.executeAsync("DROP TYPE ks.type1"),
168+ session.executeAsync("DROP TYPE lowercase.type1"),
150169 session.executeAsync("DROP TYPE \"CaseSensitive\".type1"),
151- session.executeAsync("DROP KEYSPACE ks2"),
170+ session.executeAsync("DROP KEYSPACE lowercase2"),
152171 session.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
153172 ));
154173 Futures.getUnchecked(f);
155174 }
156-
157- @AfterClass(groups = "short")
158- public void teardown() {
159- if (cluster2 != null)
160- cluster2.close();
161- }
162175 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +16 −16
@@ -34,52 +34,52 @@
3434 @Override
3535 protected Collection<String> getTableDefinitions() {
3636
37- String sparse = "CREATE TABLE ks.sparse (\n"
37+ String sparse = String.format("CREATE TABLE %s.sparse (\n"
3838 + " k text,\n"
3939 + " c1 int,\n"
4040 + " c2 float,\n"
4141 + " l list<text>,\n"
4242 + " v int,\n"
4343 + " PRIMARY KEY (k, c1, c2)\n"
44- + ");";
44+ + ");", keyspace);
4545
46- String st = "CREATE TABLE ks.static (\n"
46+ String st = String.format("CREATE TABLE %s.static (\n"
4747 + " k text,\n"
4848 + " i int,\n"
4949 + " m map<text, timeuuid>,\n"
5050 + " v int,\n"
5151 + " PRIMARY KEY (k)\n"
52- + ");";
52+ + ");", keyspace);
5353
54- String counters = "CREATE TABLE ks.counters (\n"
54+ String counters = String.format("CREATE TABLE %s.counters (\n"
5555 + " k text,\n"
5656 + " c counter,\n"
5757 + " PRIMARY KEY (k)\n"
58- + ");";
58+ + ");", keyspace);
5959
60- String compactStatic = "CREATE TABLE ks.compact_static (\n"
60+ String compactStatic = String.format("CREATE TABLE %s.compact_static (\n"
6161 + " k text,\n"
6262 + " i int,\n"
6363 + " t timeuuid,\n"
6464 + " v int,\n"
6565 + " PRIMARY KEY (k)\n"
66- + ") WITH COMPACT STORAGE;";
66+ + ") WITH COMPACT STORAGE;", keyspace);
6767
68- String compactDynamic = "CREATE TABLE ks.compact_dynamic (\n"
68+ String compactDynamic = String.format("CREATE TABLE %s.compact_dynamic (\n"
6969 + " k text,\n"
7070 + " c int,\n"
7171 + " v timeuuid,\n"
7272 + " PRIMARY KEY (k, c)\n"
73- + ") WITH COMPACT STORAGE;";
73+ + ") WITH COMPACT STORAGE;", keyspace);
7474
75- String compactComposite = "CREATE TABLE ks.compact_composite (\n"
75+ String compactComposite = String.format("CREATE TABLE %s.compact_composite (\n"
7676 + " k text,\n"
7777 + " c1 int,\n"
7878 + " c2 float,\n"
7979 + " c3 double,\n"
8080 + " v timeuuid,\n"
8181 + " PRIMARY KEY (k, c1, c2, c3)\n"
82- + ") WITH COMPACT STORAGE;";
82+ + ") WITH COMPACT STORAGE;", keyspace);
8383
8484 cql3.put("sparse", sparse);
8585 cql3.put("static", st);
@@ -88,7 +88,7 @@
8888 compact.put("compact_dynamic", compactDynamic);
8989 compact.put("compact_composite", compactComposite);
9090
91- withOptions = "CREATE TABLE ks.with_options (\n"
91+ withOptions = String.format("CREATE TABLE %s.with_options (\n"
9292 + " k text,\n"
9393 + " v1 int,\n"
9494 + " v2 int,\n"
@@ -103,7 +103,7 @@
103103 + " AND caching = 'ALL'\n"
104104 + " AND comment = 'My awesome table'\n"
105105 + " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n"
106- + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 };";
106+ + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 };", keyspace);
107107
108108 List<String> allDefs = new ArrayList<String>();
109109 allDefs.addAll(cql3.values());
@@ -127,7 +127,7 @@
127127 @Test(groups = "short")
128128 public void schemaExportTest() {
129129
130- KeyspaceMetadata metadata = cluster.getMetadata().getKeyspace(TestUtils.SIMPLE_KEYSPACE);
130+ KeyspaceMetadata metadata = cluster.getMetadata().getKeyspace(keyspace);
131131
132132 for (Map.Entry<String, String> tableEntry : cql3.entrySet()) {
133133 String table = tableEntry.getKey();
@@ -145,7 +145,7 @@
145145 // Same remark as the preceding test
146146 @Test(groups = "short")
147147 public void schemaExportOptionsTest() {
148- TableMetadata metadata = cluster.getMetadata().getKeyspace(TestUtils.SIMPLE_KEYSPACE).getTable("with_options");
148+ TableMetadata metadata = cluster.getMetadata().getKeyspace(keyspace).getTable("with_options");
149149
150150 String withOpts = withOptions;
151151 VersionNumber version = cluster.getMetadata()
added driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +66 −0
@@ -0,0 +1,66 @@
1+package com.datastax.driver.core;
2+
3+import org.testng.annotations.Test;
4+
5+import static org.testng.Assert.assertEquals;
6+
7+public class SessionLeakTest {
8+
9+ @Test(groups = "short")
10+ public void connectionLeakTest() throws Exception {
11+ CCMBridge ccm = null;
12+ Cluster cluster = null;
13+
14+ try {
15+ ccm = CCMBridge.create("test", 1);
16+
17+ // create a new cluster object and ensure 0 sessions and connections
18+ cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build();
19+
20+ int corePoolSize = cluster.getConfiguration()
21+ .getPoolingOptions()
22+ .getCoreConnectionsPerHost(HostDistance.LOCAL);
23+
24+ assertEquals(cluster.manager.sessions.size(), 0);
25+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 0);
26+
27+ // ensure sessions.size() returns with 1 control connection + core pool size.
28+ Session session = cluster.connect();
29+ assertEquals(cluster.manager.sessions.size(), 1);
30+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
31+
32+ // ensure sessions.size() returns to 0 with only 1 active connection (the control connection)
33+ session.close();
34+ assertEquals(cluster.manager.sessions.size(), 0);
35+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
36+
37+ Session thisSession;
38+
39+ // ensure bootstrapping a node does not create additional connections
40+
41+ ccm.bootstrapNode(2);
42+ assertEquals(cluster.manager.sessions.size(), 0);
43+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
44+
45+ // ensure a new session gets registered and core connections are established
46+ // there should be corePoolSize more connections to accommodate for the new host.
47+ thisSession = cluster.connect();
48+ assertEquals(cluster.manager.sessions.size(), 1);
49+
50+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + (corePoolSize * 2));
51+
52+ // ensure bootstrapping a node does not create additional connections that won't get cleaned up
53+ thisSession.close();
54+
55+ assertEquals(cluster.manager.sessions.size(), 0);
56+
57+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
58+
59+ } finally {
60+ if (cluster != null)
61+ cluster.close();
62+ if (ccm != null)
63+ ccm.remove();
64+ }
65+ }
66+}
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +6 −58
@@ -19,9 +19,13 @@
1919 import java.util.Collection;
2020 import java.util.List;
2121 import java.util.Locale;
22-import java.util.concurrent.*;
22+import java.util.concurrent.CountDownLatch;
23+import java.util.concurrent.ExecutorService;
24+import java.util.concurrent.Executors;
25+import java.util.concurrent.TimeUnit;
2326
2427 import org.testng.annotations.Test;
28+
2529 import static org.testng.Assert.assertEquals;
2630 import static org.testng.Assert.assertTrue;
2731 import static org.testng.Assert.fail;
@@ -112,7 +116,7 @@
112116
113117 try {
114118
115- Session compressedSession = cluster.connect(TestUtils.SIMPLE_KEYSPACE);
119+ Session compressedSession = cluster.connect(keyspace);
116120
117121 // Simple calls to all versions of the execute/executeAsync methods
118122 String key = "execute_compressed_test";
@@ -152,62 +156,6 @@
152156 assertEquals(state.getSession(), session);
153157 }
154158
155- @Test(groups = "short")
156- public void connectionLeakTest() throws Exception {
157- // Checking for JAVA-342
158-
159- // give the driver time to close other sessions in this class
160- Thread.sleep(10);
161-
162- // create a new cluster object and ensure 0 sessions and connections
163- Cluster cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build();
164-
165- assertEquals(cluster.manager.sessions.size(), 0);
166- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 0);
167-
168- // ensure sessions.size() returns with 1 control connection + core pool size.
169- Session session = cluster.connect();
170- assertEquals(cluster.manager.sessions.size(), 1);
171- int coreConnections = TestUtils.numberOfLocalCoreConnections(cluster);
172- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
173- 1 + coreConnections);
174-
175- // ensure sessions.size() returns to 0 with only 1 active connection (the control connection)
176- session.close();
177- assertEquals(cluster.manager.sessions.size(), 0);
178- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
179-
180- try {
181- Session thisSession;
182-
183- // ensure bootstrapping a node does not create additional connections
184- cassandraCluster.bootstrapNode(2);
185- assertEquals(cluster.manager.sessions.size(), 0);
186- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
187-
188- // ensure a new session gets registered and core connections are established
189- // there should be corePoolSize more connections to accommodate for the new host.
190- thisSession = cluster.connect();
191- assertEquals(cluster.manager.sessions.size(), 1);
192- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
193- 1 + coreConnections * 2);
194-
195- // ensure bootstrapping a node does not create additional connections that won't get cleaned up
196- thisSession.close();
197- assertEquals(cluster.manager.sessions.size(), 0);
198- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
199-
200- } finally {
201- // ensure we decommission node2 for the rest of the tests
202- cassandraCluster.decommissionNode(2);
203-
204- assertEquals(cluster.manager.sessions.size(), 0);
205- assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
206-
207- cluster.close();
208- }
209- }
210-
211159 /**
212160 * Checks for deadlocks when a session shutdown races with the initialization of the cluster (JAVA-418).
213161 */
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +1 −1
@@ -19,7 +19,7 @@
1919
2020 @Test(groups = "short")
2121 public void should_escape_single_quote_table_comment() {
22- TableMetadata table = cluster.getMetadata().getKeyspace("ks").getTable("single_quote");
22+ TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote");
2323 assertThat(table.asCQLQuery()).contains("comment with single quote '' should work");
2424 }
2525 }
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +9 −9
@@ -15,12 +15,12 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-
1918 import java.util.Arrays;
2019 import java.util.Collection;
2120 import java.util.TreeSet;
2221
2322 import org.testng.annotations.Test;
23+
2424 import static org.testng.Assert.*;
2525
2626 import com.datastax.driver.core.*;
@@ -44,10 +44,10 @@
4444 public void remainingDeleteTests() throws Exception {
4545
4646 Statement query;
47- TableMetadata table = cluster.getMetadata().getKeyspace(TestUtils.SIMPLE_KEYSPACE).getTable(TABLE_TEXT);
47+ TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
4848 assertNotNull(table);
4949
50- String expected = "DELETE k FROM ks.test_text;";
50+ String expected = String.format("DELETE k FROM %s.test_text;", keyspace);
5151 query = delete("k").from(table);
5252 assertEquals(query.toString(), expected);
5353 try {
@@ -210,25 +210,25 @@
210210 @Test(groups = "short")
211211 @CassandraVersion(major=2.0, minor=7, description="DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)")
212212 public void conditionalDeletesTest() throws Exception {
213- session.execute("INSERT INTO ks.test_int (k, a, b) VALUES (1, 1, 1)");
213+ session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)",keyspace));
214214
215215 Statement delete;
216216 Row row;
217- delete = delete().from(TestUtils.SIMPLE_KEYSPACE, TABLE_INT).where(eq("k", 2)).ifExists();
217+ delete = delete().from(keyspace, TABLE_INT).where(eq("k", 2)).ifExists();
218218 row = session.execute(delete).one();
219219 assertFalse(row.getBool("[applied]"));
220220
221- delete = delete().from(TestUtils.SIMPLE_KEYSPACE, TABLE_INT).where(eq("k", 1)).ifExists();
221+ delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).ifExists();
222222 row = session.execute(delete).one();
223223 assertTrue(row.getBool("[applied]"));
224224
225- session.execute("INSERT INTO ks.test_int (k, a, b) VALUES (1, 1, 1)");
225+ session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)", keyspace));
226226
227- delete = delete().from(TestUtils.SIMPLE_KEYSPACE, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 2));
227+ delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 2));
228228 row = session.execute(delete).one();
229229 assertFalse(row.getBool("[applied]"));
230230
231- delete = delete().from(TestUtils.SIMPLE_KEYSPACE, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 1));
231+ delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 1));
232232 row = session.execute(delete).one();
233233 assertTrue(row.getBool("[applied]"));
234234 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +8 −6
@@ -20,10 +20,12 @@
2020 import java.util.Collection;
2121
2222 import org.testng.annotations.Test;
23+
2324 import static org.testng.Assert.assertEquals;
2425 import static org.testng.Assert.assertNotNull;
2526
2627 import com.datastax.driver.core.*;
28+
2729 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2830
2931 public class QueryBuilderRoutingKeyTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -41,7 +43,7 @@
4143 public void textRoutingKeyTest() throws Exception {
4244
4345 Statement query;
44- TableMetadata table = cluster.getMetadata().getKeyspace(TestUtils.SIMPLE_KEYSPACE).getTable(TABLE_TEXT);
46+ TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT);
4547 assertNotNull(table);
4648
4749 String txt = "If she weighs the same as a duck... she's made of wood.";
@@ -61,7 +63,7 @@
6163 public void intRoutingKeyTest() throws Exception {
6264
6365 Statement query;
64- TableMetadata table = cluster.getMetadata().getKeyspace(TestUtils.SIMPLE_KEYSPACE).getTable(TABLE_INT);
66+ TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
6567 assertNotNull(table);
6668
6769 query = insertInto(table).values(new String[]{"k", "a", "b"}, new Object[]{42, 1, 2});
@@ -82,7 +84,7 @@
8284 public void intRoutingBatchKeyTest() throws Exception {
8385
8486 RegularStatement query;
85- TableMetadata table = cluster.getMetadata().getKeyspace(TestUtils.SIMPLE_KEYSPACE).getTable(TABLE_INT);
87+ TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable(TABLE_INT);
8688 assertNotNull(table);
8789
8890 ByteBuffer bb = ByteBuffer.allocate(4);
@@ -95,8 +97,8 @@
9597 query = select().from(table).where(eq("k", 42));
9698
9799 batch_query = "BEGIN BATCH ";
98- batch_query += "INSERT INTO ks.test_int(k,a) VALUES (42,1);";
99- batch_query += "UPDATE ks.test_int USING TTL 400;";
100+ batch_query += String.format("INSERT INTO %s.test_int(k,a) VALUES (42,1);", keyspace);
101+ batch_query += String.format("UPDATE %s.test_int USING TTL 400;", keyspace);
100102 batch_query += "APPLY BATCH;";
101103 batch = batch()
102104 .add(insertInto(table).values(new String[]{"k", "a"}, new Object[]{42, 1}))
@@ -106,7 +108,7 @@
106108 // TODO: rs = session.execute(batch); // Not guaranteed to be valid CQL
107109
108110 batch_query = "BEGIN BATCH ";
109- batch_query += "SELECT * FROM ks.test_int WHERE k=42;";
111+ batch_query += String.format("SELECT * FROM %s.test_int WHERE k=42;", keyspace);
110112 batch_query += "APPLY BATCH;";
111113 batch = batch(query);
112114 assertEquals(batch.getRoutingKey(), bb);
added driver-core/src/test/resources/client.keystore +0 −0

Binary content is not shown. View the file.

added driver-core/src/test/resources/client.truststore +0 −0

Binary content is not shown. View the file.

added driver-core/src/test/resources/server.keystore +0 −0

Binary content is not shown. View the file.

added driver-core/src/test/resources/server.truststore +0 −0

Binary content is not shown. View the file.

modified driver-examples/osgi/pom.xml +3 −3
@@ -26,7 +26,7 @@
2626
2727 <properties>
2828 <felix.version>4.6.0</felix.version>
29- <pax-exam.version>4.4.0</pax-exam.version>
29+ <pax-exam.version>3.6.0</pax-exam.version>
3030 </properties>
3131
3232 <dependencies>
@@ -88,14 +88,14 @@
8888 <dependency>
8989 <groupId>log4j</groupId>
9090 <artifactId>log4j</artifactId>
91- <version>1.2.17</version>
91+ <version>${log4j.version}</version>
9292 <scope>test</scope>
9393 </dependency>
9494
9595 <dependency>
9696 <groupId>org.slf4j</groupId>
9797 <artifactId>slf4j-log4j12</artifactId>
98- <version>1.7.6</version>
98+ <version>${slf4j-log4j12.version}</version>
9999 <scope>test</scope>
100100 </dependency>
101101
modified pom.xml +28 −7
@@ -39,20 +39,41 @@
3939 <properties>
4040 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
4141 <cassandra.version>2.1.3</cassandra.version>
42+ <java.version>1.6</java.version>
43+ <log4j.version>1.2.17</log4j.version>
44+ <slf4j-log4j12.version>1.7.6</slf4j-log4j12.version>
45+ <!--
46+ We use an old version of Guava to be compatible with Spark 1.1.
47+ Check with the spark-cassandra-connector team before upgrading this.
48+ -->
49+ <guava.version>14.0.1</guava.version>
50+ <netty.version>3.9.0.Final</netty.version>
51+ <metrics.version>3.0.2</metrics.version>
52+ <snappy.version>1.0.5</snappy.version>
53+ <lz4.version>1.2.0</lz4.version>
54+ <!-- test dependency versions -->
55+ <testng.version>6.8.8</testng.version>
56+ <assertj.version>1.7.0</assertj.version>
57+ <mockito.version>1.10.8</mockito.version>
58+ <!--
59+ There are more recent versions of Scassandra but they require JDK 7,
60+ our build is still using JDK 6.
61+ -->
62+ <scassandra.version>0.4.1</scassandra.version>
4263 </properties>
4364
4465 <dependencies>
4566 <dependency>
4667 <groupId>log4j</groupId>
4768 <artifactId>log4j</artifactId>
48- <version>1.2.17</version>
69+ <version>${log4j.version}</version>
4970 <scope>test</scope>
5071 </dependency>
5172
5273 <dependency>
5374 <groupId>org.slf4j</groupId>
5475 <artifactId>slf4j-log4j12</artifactId>
55- <version>1.7.6</version>
76+ <version>${slf4j-log4j12.version}</version>
5677 <scope>test</scope>
5778 </dependency>
5879 </dependencies>
@@ -75,11 +96,11 @@
7596 <artifactId>maven-compiler-plugin</artifactId>
7697 <version>3.1</version>
7798 <configuration>
78- <source>1.6</source>
79- <target>1.6</target>
80- <optimize>true</optimize>
81- <showDeprecation>true</showDeprecation>
82- <showWarnings>true</showWarnings>
99+ <source>${java.version}</source>
100+ <target>${java.version}</target>
101+ <optimize>true</optimize>
102+ <showDeprecation>true</showDeprecation>
103+ <showWarnings>true</showWarnings>
83104 </configuration>
84105 </plugin>
85106 <plugin>