Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 3.0

Conflicts:
	driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java
	driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java
	driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java
Changeset0ff8ef436fa47306abd2c653e1ad428c3f911ae5b356944d3cfcff6091be6df4
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-01-17 23:44 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-01-17 23:45 +01:00
Parentsa33a06b447d7, f6f0073f252c

Browse the files at this changeset

14 files changed

modified driver-core/src/test/java/com/datastax/driver/core/CCMAccess.java +1 −1
@@ -180,7 +180,7 @@
180180 *
181181 * @param n the node number (starting from 1).
182182 */
183- void decommision(int n);
183+ void decommission(int n);
184184
185185 /**
186186 * Updates the {@code nth} host's config file in the CCM cluster.
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +39 −12
@@ -215,6 +215,8 @@
215215
216216 private boolean keepLogs = false;
217217
218+ private boolean started = false;
219+
218220 private boolean closed = false;
219221
220222 private CCMBridge(String clusterName, boolean isDSE, VersionNumber version, int storagePort, int thriftPort, int binaryPort, String jvmArgs) {
@@ -348,7 +350,7 @@
348350 public synchronized void close() {
349351 if (closed)
350352 return;
351- logger.debug("Closing: " + this);
353+ logger.debug("Closing: {}", this);
352354 if (keepLogs) {
353355 executeNoFail(new Runnable() {
354356 @Override
@@ -372,21 +374,31 @@
372374 }, false);
373375 }
374376 closed = true;
375- logger.debug("Closed: " + this);
377+ logger.debug("Closed: {}", this);
376378 }
377379
378380 @Override
379- public void start() {
380- logger.debug("Starting: " + this);
381+ public synchronized void start() {
382+ if (started)
383+ return;
384+ if (logger.isDebugEnabled())
385+ logger.debug("Starting: {} - free memory: {}", this, TestUtils.getFreeMemoryMB());
381386 execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs);
387+ if (logger.isDebugEnabled())
388+ logger.debug("Started: {} - Free memory: {}", this, TestUtils.getFreeMemoryMB());
389+ started = true;
382390 }
383391
384392 @Override
385393 public synchronized void stop() {
386394 if (closed)
387395 return;
388- logger.debug("Stopping: " + this);
396+ if (logger.isDebugEnabled())
397+ logger.debug("Stopping: {} - free memory: {}", this, TestUtils.getFreeMemoryMB());
389398 execute(CCM_COMMAND + " stop");
399+ System.gc();
400+ if (logger.isDebugEnabled())
401+ logger.debug("Stopped: {} - free memory: {}", this, TestUtils.getFreeMemoryMB());
390402 closed = true;
391403 }
392404
@@ -394,7 +406,7 @@
394406 public synchronized void forceStop() {
395407 if (closed)
396408 return;
397- logger.debug("Force stopping: " + this);
409+ logger.debug("Force stopping: {}", this);
398410 execute(CCM_COMMAND + " stop --not-gently");
399411 closed = true;
400412 }
@@ -420,7 +432,7 @@
420432 @Override
421433 public synchronized void remove() {
422434 stop();
423- logger.debug("Removing: " + this);
435+ logger.debug("Removing: {}", this);
424436 execute(CCM_COMMAND + " remove");
425437 }
426438
@@ -447,7 +459,7 @@
447459 }
448460
449461 @Override
450- public void decommision(int n) {
462+ public void decommission(int n) {
451463 logger.debug(String.format("Decommissioning: node %s (%s%s:%s) from %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
452464 execute(CCM_COMMAND + " node%d decommission", n);
453465 }
@@ -605,6 +617,7 @@
605617
606618 @Override
607619 protected void finalize() throws Throwable {
620+ logger.debug("GC'ing {}", this);
608621 close();
609622 super.finalize();
610623 }
@@ -683,9 +696,7 @@
683696 }
684697
685698 /**
686- * The Cassandra or DSE version to use.
687- * <p/>
688- * Defaults to {@link #getCassandraVersion()}.
699+ * The Cassandra or DSE version to use (defaults to {@link #getCassandraVersion()} if this is never called).
689700 */
690701 public Builder withVersion(String version) {
691702 Iterator<String> it = createOptions.iterator();
@@ -702,7 +713,8 @@
702713 }
703714
704715 /**
705- * Free-form options that will be added at the end of the {@code ccm create} command.
716+ * Free-form options that will be added at the end of the {@code ccm create} command
717+ * (defaults to {@link #getInstallArguments()} if this is never called).
706718 */
707719 public Builder withCreateOptions(String... createOptions) {
708720 Collections.addAll(this.createOptions, createOptions);
@@ -766,6 +778,7 @@
766778 ccm.execute(buildCreateCommand());
767779 updateNodeConf(ccm);
768780 HashMap<String, Object> config = new HashMap<String, Object>(cassandraConfiguration);
781+ config.put("start_rpc", false);
769782 config.put("storage_port", storagePort);
770783 config.put("rpc_port", thriftPort);
771784 config.put("native_transport_port", binaryPort);
@@ -777,6 +790,15 @@
777790 return ccm;
778791 }
779792
793+ public int weight() {
794+ // the weight is simply function of the number of nodes
795+ int totalNodes = 0;
796+ for (int nodesPerDc : this.nodes) {
797+ totalNodes += nodesPerDc;
798+ }
799+ return totalNodes;
800+ }
801+
780802 private String joinJvmArgs() {
781803 StringBuilder allJvmArgs = new StringBuilder("");
782804 for (String jvmArg : jvmArgs) {
@@ -889,6 +911,11 @@
889911 result = 31 * result + version.hashCode();
890912 return result;
891913 }
914+
915+ @Override
916+ public String toString() {
917+ return String.format("%s (weight %s)", clusterName, weight());
918+ }
892919 }
893920
894921 }
added driver-core/src/test/java/com/datastax/driver/core/CCMCache.java +306 −0
@@ -0,0 +1,306 @@
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 com.google.common.base.Throwables;
19+import com.google.common.cache.*;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+
23+import java.io.File;
24+import java.net.InetSocketAddress;
25+import java.util.Map;
26+import java.util.concurrent.ExecutionException;
27+import java.util.concurrent.atomic.AtomicInteger;
28+
29+public class CCMCache {
30+
31+ private static final Logger LOGGER = LoggerFactory.getLogger(CCMCache.class);
32+
33+ private static class CachedCCMAccess implements CCMAccess {
34+
35+ private final CCMAccess ccm;
36+
37+ private final AtomicInteger refCount = new AtomicInteger(1);
38+
39+ private volatile boolean evicted = false;
40+
41+ private CachedCCMAccess(CCMAccess ccm) {
42+ this.ccm = ccm;
43+ }
44+
45+ @Override
46+ public String getClusterName() {
47+ return ccm.getClusterName();
48+ }
49+
50+ @Override
51+ public VersionNumber getVersion() {
52+ return ccm.getVersion();
53+ }
54+
55+ @Override
56+ public File getCcmDir() {
57+ return ccm.getCcmDir();
58+ }
59+
60+ @Override
61+ public File getClusterDir() {
62+ return ccm.getClusterDir();
63+ }
64+
65+ @Override
66+ public File getNodeDir(int n) {
67+ return ccm.getNodeDir(n);
68+ }
69+
70+ @Override
71+ public File getNodeConfDir(int n) {
72+ return ccm.getNodeConfDir(n);
73+ }
74+
75+ @Override
76+ public int getStoragePort() {
77+ return ccm.getStoragePort();
78+ }
79+
80+ @Override
81+ public int getThriftPort() {
82+ return ccm.getThriftPort();
83+ }
84+
85+ @Override
86+ public int getBinaryPort() {
87+ return ccm.getBinaryPort();
88+ }
89+
90+ @Override
91+ public void setKeepLogs(boolean keepLogs) {
92+ ccm.setKeepLogs(keepLogs);
93+ }
94+
95+ @Override
96+ public InetSocketAddress addressOfNode(int n) {
97+ return ccm.addressOfNode(n);
98+ }
99+
100+ @Override
101+ public void start() {
102+ ccm.start();
103+ }
104+
105+ @Override
106+ public void stop() {
107+ ccm.stop();
108+ }
109+
110+ @Override
111+ public void forceStop() {
112+ ccm.forceStop();
113+ }
114+
115+ @Override
116+ public void close() {
117+ refCount.decrementAndGet();
118+ maybeClose();
119+ }
120+
121+ private void maybeClose() {
122+ if (refCount.get() <= 0 && evicted) {
123+ ccm.close();
124+ }
125+ }
126+
127+ @Override
128+ public void remove() {
129+ ccm.remove();
130+ }
131+
132+ @Override
133+ public void updateConfig(Map<String, Object> configs) {
134+ ccm.updateConfig(configs);
135+ }
136+
137+ @Override
138+ public void updateDSEConfig(Map<String, Object> configs) {
139+ ccm.updateDSEConfig(configs);
140+ }
141+
142+ @Override
143+ public void start(int n) {
144+ ccm.start(n);
145+ }
146+
147+ @Override
148+ public void stop(int n) {
149+ ccm.stop(n);
150+ }
151+
152+ @Override
153+ public void forceStop(int n) {
154+ ccm.forceStop(n);
155+ }
156+
157+ @Override
158+ public void remove(int n) {
159+ ccm.remove(n);
160+ }
161+
162+ @Override
163+ public void add(int n) {
164+ ccm.add(n);
165+ }
166+
167+ @Override
168+ public void add(int dc, int n) {
169+ ccm.add(dc, n);
170+ }
171+
172+ @Override
173+ public void decommission(int n) {
174+ ccm.decommission(n);
175+ }
176+
177+ @Override
178+ public void updateNodeConfig(int n, String key, Object value) {
179+ ccm.updateNodeConfig(n, key, value);
180+ }
181+
182+ @Override
183+ public void updateNodeConfig(int n, Map<String, Object> configs) {
184+ ccm.updateNodeConfig(n, configs);
185+ }
186+
187+ @Override
188+ public void setWorkload(int n, String workload) {
189+ ccm.setWorkload(n, workload);
190+ }
191+
192+ @Override
193+ public void waitForUp(int node) {
194+ ccm.waitForUp(node);
195+ }
196+
197+ @Override
198+ public void waitForDown(int node) {
199+ ccm.waitForDown(node);
200+ }
201+
202+ @Override
203+ public String toString() {
204+ return ccm.toString();
205+ }
206+ }
207+
208+ private static class CCMAccessLoader extends CacheLoader<CCMBridge.Builder, CachedCCMAccess> {
209+
210+ @Override
211+ public CachedCCMAccess load(CCMBridge.Builder key) {
212+ return new CachedCCMAccess(key.build());
213+ }
214+
215+ }
216+
217+ private static class CCMAccessWeigher implements Weigher<CCMBridge.Builder, CachedCCMAccess> {
218+
219+ @Override
220+ public int weigh(CCMBridge.Builder key, CachedCCMAccess value) {
221+ return key.weight();
222+ }
223+
224+ }
225+
226+ private static class CCMAccessRemovalListener implements RemovalListener<CCMBridge.Builder, CachedCCMAccess> {
227+
228+ @Override
229+ public void onRemoval(RemovalNotification<CCMBridge.Builder, CachedCCMAccess> notification) {
230+ CachedCCMAccess cached = notification.getValue();
231+ if (cached != null && cached.ccm != null) {
232+ LOGGER.debug("Evicting: {} because of {}", cached.ccm, notification.getCause());
233+ cached.evicted = true;
234+ cached.maybeClose();
235+ }
236+ }
237+
238+ }
239+
240+ /**
241+ * A LoadingCache that stores running CCM clusters.
242+ */
243+ private static final LoadingCache<CCMBridge.Builder, CachedCCMAccess> CACHE;
244+
245+ static {
246+ long maximumWeight;
247+ String numberOfNodes = System.getProperty("ccm.maxNumberOfNodes");
248+ if (numberOfNodes == null) {
249+ long freeMemoryMB = TestUtils.getFreeMemoryMB();
250+ if (freeMemoryMB < 1000)
251+ LOGGER.warn("Available memory below 1GB: {}MB, CCM clusters might fail to start", freeMemoryMB);
252+ // CCM nodes are started with -Xms500M -Xmx500M
253+ // and allocate up to 100MB non-heap memory in the general case,
254+ // to be conservative we treat 1 "slot" as 800Mb.
255+ // We leave 2 slots out to avoid starving system memory,
256+ // and we pick a value with a minimum of 1 slot and a maximum of 8 slots.
257+ // For example, an 8GB VM with ~6.5GB currently available heap will yield 6 slots ((6500/800) - 2 = 6).
258+ long slotsAvailable = (freeMemoryMB / 800) - 2;
259+ maximumWeight = Math.min(8, Math.max(1, slotsAvailable));
260+ } else {
261+ maximumWeight = Integer.parseInt(numberOfNodes);
262+ }
263+ LOGGER.info("Maximum number of running CCM nodes: {}", maximumWeight);
264+ CACHE = CacheBuilder.newBuilder()
265+ .initialCapacity(3)
266+ .softValues()
267+ .maximumWeight(maximumWeight)
268+ .weigher(new CCMAccessWeigher())
269+ .removalListener(new CCMAccessRemovalListener())
270+ .build(new CCMAccessLoader());
271+ }
272+
273+ /**
274+ * Creates or recycles a {@link CCMAccess} instance and returns it.
275+ * <p/>
276+ * Caller MUST call {@link CCMAccess#close()} when done with the cluster,
277+ * to ensure that resources will be properly freed.
278+ */
279+ public static CCMAccess get(CCMBridge.Builder key) {
280+ CachedCCMAccess ccm = CACHE.getIfPresent(key);
281+ if (ccm != null) {
282+ ccm.refCount.incrementAndGet();
283+ } else {
284+ try {
285+ ccm = CACHE.get(key);
286+ } catch (ExecutionException e) {
287+ throw Throwables.propagate(e);
288+ }
289+ }
290+ logCache();
291+ return ccm;
292+ }
293+
294+ /**
295+ * Removes the given key from the cache.
296+ */
297+ public static void remove(CCMBridge.Builder key) {
298+ CACHE.invalidate(key);
299+ }
300+
301+ private static void logCache() {
302+ if (LOGGER.isDebugEnabled())
303+ LOGGER.debug("Free memory: {}, Cache {}", TestUtils.getFreeMemoryMB(), CACHE.asMap().keySet());
304+ }
305+
306+}
modified driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java +21 −182
@@ -17,12 +17,9 @@
1717
1818 import com.datastax.driver.core.CreateCCM.TestMode;
1919 import com.google.common.base.Throwables;
20-import com.google.common.cache.*;
2120 import com.google.common.collect.ImmutableMap;
2221 import com.google.common.collect.Lists;
2322 import com.google.common.io.Closer;
24-import com.google.common.util.concurrent.MoreExecutors;
25-import com.google.common.util.concurrent.ThreadFactoryBuilder;
2623 import org.slf4j.Logger;
2724 import org.slf4j.LoggerFactory;
2825 import org.testng.ITestResult;
@@ -38,7 +35,7 @@
3835 import java.lang.reflect.ParameterizedType;
3936 import java.net.InetSocketAddress;
4037 import java.util.*;
41-import java.util.concurrent.*;
38+import java.util.concurrent.Callable;
4239 import java.util.concurrent.atomic.AtomicInteger;
4340
4441 import static com.datastax.driver.core.CreateCCM.TestMode.PER_CLASS;
@@ -182,7 +179,7 @@
182179 }
183180
184181 @Override
185- public void decommision(int n) {
182+ public void decommission(int n) {
186183 throw new UnsupportedOperationException("This CCM cluster is read-only");
187184 }
188185
@@ -220,6 +217,11 @@
220217 public void waitForDown(int node) {
221218 throw new UnsupportedOperationException("This CCM cluster is read-only");
222219 }
220+
221+ @Override
222+ public String toString() {
223+ return delegate.toString();
224+ }
223225 }
224226
225227 private static class CCMTestConfig {
@@ -279,7 +281,6 @@
279281 @SuppressWarnings("SimplifiableIfStatement")
280282 private Map<String, Object> config() {
281283 Map<String, Object> config = new HashMap<String, Object>();
282- config.put("start_rpc", false);
283284 for (int i = annotations.size() - 1; i == 0; i--) {
284285 CCMConfig ann = annotations.get(i);
285286 addConfigOptions(ann.config(), config);
@@ -388,7 +389,7 @@
388389
389390 private CCMBridge.Builder ccmBuilder() {
390391 if (ccmBuilder == null) {
391- ccmBuilder = CCMBridge.builder().withNodes(numberOfNodes());
392+ ccmBuilder = CCMBridge.builder().withNodes(numberOfNodes()).notStarted();
392393 if (version() != null)
393394 ccmBuilder.withVersion(version());
394395 if (dse())
@@ -468,159 +469,12 @@
468469 }
469470 }
470471
471- private int weight() {
472- int weight = 0;
473- weight += totalNodes() - 1;
474- weight += config().size() - 1;
475- weight += dseConfig().size();
476- weight += dse() ? 1 : 0;
477- weight += jvmArgs().size();
478- weight += startOptions().size();
479- weight += ssl() ? 1 : 0;
480- weight += auth() ? 1 : 0;
481- weight += version() != null ? 1 : 0;
482- return weight;
483- }
484-
485- private int totalNodes() {
486- int nodes = 0;
487- for (int nodesPerDc : numberOfNodes()) {
488- nodes += nodesPerDc;
489- }
490- return nodes;
491- }
492- }
493-
494- private static class CCMTestContextKey {
495-
496- private final CCMBridge.Builder builder;
497-
498- private final int weight;
499-
500- private CCMTestContextKey(CCMBridge.Builder builder, int weight) {
501- this.builder = builder;
502- this.weight = weight;
503- }
504-
505- @Override
506- public boolean equals(Object o) {
507- if (this == o) return true;
508- if (o == null || getClass() != o.getClass()) return false;
509- CCMTestContextKey that = (CCMTestContextKey) o;
510- return builder.equals(that.builder);
511- }
512-
513- @Override
514- public int hashCode() {
515- return builder.hashCode();
516- }
517- }
518-
519- private static class CCMTestContext implements Runnable {
520-
521- private CCMAccess ccm;
522-
523- private final AtomicInteger refCount = new AtomicInteger(1);
524-
525- private volatile boolean evicted = false;
526-
527- private CCMTestContext(CCMAccess ccm) {
528- this(ccm, false);
529- }
530-
531- public CCMTestContext(CCMAccess ccm, boolean evicted) {
532- this.ccm = ccm;
533- this.evicted = evicted;
534- }
535-
536- @Override
537- public void run() {
538- if (ccm != null)
539- ccm.close();
540- ccm = null;
541- }
542-
543- private void markEvicted() {
544- evicted = true;
545- }
546-
547- private void maybeClose() {
548- if (refCount.get() <= 0 && evicted)
549- POOL.execute(this);
550- }
551- }
552-
553- private static class CCMTestContextLoader extends CacheLoader<CCMTestContextKey, CCMTestContext> {
554-
555- @Override
556- public CCMTestContext load(CCMTestContextKey key) {
557- return new CCMTestContext(key.builder.build());
558- }
559-
560- }
561-
562- private static class CCMTestContextWeigher implements Weigher<CCMTestContextKey, CCMTestContext> {
563-
564- @Override
565- public int weigh(CCMTestContextKey key, CCMTestContext value) {
566- return key.weight;
567- }
568-
569- }
570-
571- private static class CCMTestContextRemovalListener implements RemovalListener<CCMTestContextKey, CCMTestContext> {
572-
573- @Override
574- public void onRemoval(RemovalNotification<CCMTestContextKey, CCMTestContext> notification) {
575- CCMTestContext context = notification.getValue();
576- if (context != null && context.ccm != null) {
577- LOGGER.debug("Evicting: {} because of {}", context.ccm, notification.getCause());
578- context.markEvicted();
579- context.maybeClose();
580- }
581- }
582-
583- }
584-
585- /**
586- * A LoadingCache that stores running CCM clusters.
587- */
588- private static final LoadingCache<CCMTestContextKey, CCMTestContext> CACHE;
589-
590- private static final ExecutorService POOL = MoreExecutors.getExitingExecutorService(
591- (ThreadPoolExecutor) Executors.newFixedThreadPool(2,
592- new ThreadFactoryBuilder().setNameFormat("ccm-removal-%d").build()));
593-
594- static {
595- long maximumWeight;
596- String numberOfNodes = System.getProperty("ccm.maxNumberOfNodes");
597- if (numberOfNodes == null) {
598- long freeMemoryMB = TestUtils.getFreeMemoryMB();
599- if (freeMemoryMB < 1000)
600- LOGGER.warn("Available memory below 1GB: {}MB, CCM clusters might fail to start", freeMemoryMB);
601- // CCM nodes are started with -Xms500M -Xmx500M
602- // so 1 "slot" is roughly 500MB
603- // leave at least 2 slots out, with a minimum of 1 slot and a maximum of 6 slots
604- long slotsAvailable = (freeMemoryMB / 500) - 2;
605- maximumWeight = Math.min(6, Math.max(1, slotsAvailable));
606- } else {
607- maximumWeight = Integer.parseInt(numberOfNodes);
608- }
609- LOGGER.info("Maximum number of running CCM nodes: {}", maximumWeight);
610- CACHE = CacheBuilder.newBuilder()
611- .initialCapacity(3)
612- .maximumWeight(maximumWeight)
613- .weigher(new CCMTestContextWeigher())
614- .removalListener(new CCMTestContextRemovalListener())
615- .build(new CCMTestContextLoader());
616472 }
617473
618474 private TestMode testMode;
619475
620476 private CCMTestConfig ccmTestConfig;
621477
622- private CCMTestContext ccmTestContext;
623-
624478 protected CCMAccess ccm;
625479
626480 protected Cluster cluster;
@@ -832,34 +686,15 @@
832686 ccmTestConfig = createCCMTestConfig(testInstance, testMethod);
833687 assert ccmTestConfig != null;
834688 if (ccmTestConfig.createCcm()) {
689+ CCMAccess ccm = CCMCache.get(ccmTestConfig.ccmBuilder());
690+ assert ccm != null;
835691 if (ccmTestConfig.dirtiesContext()) {
836- ccm = ccmTestConfig.ccmBuilder().build();
837- ccmTestContext = new CCMTestContext(ccm, true);
838- LOGGER.debug("Using dedicated {}", ccm);
692+ this.ccm = ccm;
839693 } else {
840- CCMBridge.Builder builder = ccmTestConfig.ccmBuilder();
841- int weight = ccmTestConfig.weight();
842- CCMTestContextKey key = new CCMTestContextKey(builder, weight);
843- CCMAccess ccm;
844- ccmTestContext = CACHE.getIfPresent(key);
845- if (ccmTestContext != null) {
846- ccmTestContext.refCount.incrementAndGet();
847- ccm = ccmTestContext.ccm;
848- LOGGER.debug("Reusing {}", ccm);
849- } else {
850- try {
851- ccmTestContext = CACHE.get(key);
852- ccm = ccmTestContext.ccm;
853- LOGGER.debug("Using newly-created {}", ccm);
854- } catch (ExecutionException e) {
855- throw Throwables.propagate(e);
856- }
857- }
858694 this.ccm = new ReadOnlyCCMBridge(ccm);
859695 }
860- assert ccmTestContext != null;
861- assert ccm != null;
862-
696+ ccm.start();
697+ LOGGER.debug("Using {}", ccm);
863698 }
864699 }
865700
@@ -910,12 +745,16 @@
910745 }
911746
912747 private void closeTestContext() {
913- if (ccmTestContext != null) {
914- ccmTestContext.refCount.decrementAndGet();
915- ccmTestContext.maybeClose();
748+ if (ccmTestConfig != null && ccm != null) {
749+ CCMBridge.Builder key = ccmTestConfig.ccmBuilder();
750+ if (ccmTestConfig.dirtiesContext()) {
751+ CCMCache.remove(key);
752+ ccm.close();
753+ } else {
754+ ((ReadOnlyCCMBridge) ccm).delegate.close();
755+ }
916756 }
917757 ccmTestConfig = null;
918- ccmTestContext = null;
919758 ccm = null;
920759 }
921760
modified driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +16 −9
@@ -70,6 +70,9 @@
7070 fail("executor ran for longer than expected");
7171 } catch (InterruptedException e) {
7272 fail("Interrupted while waiting for executor to shutdown");
73+ } finally {
74+ executorService = null;
75+ System.gc();
7376 }
7477 }
7578
@@ -164,7 +167,7 @@
164167
165168 private class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> {
166169 private final CountDownLatch startSignal;
167- private final Cluster cluster;
170+ private Cluster cluster;
168171 private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
169172
170173 CreateClusterAndCheckConnections(CountDownLatch startSignal) {
@@ -202,6 +205,7 @@
202205 // If an assertion fails, close the cluster now, because it's the last time we
203206 // have a reference to it.
204207 cluster.close();
208+ cluster = null;
205209 throw e;
206210 } finally {
207211 channelMonitor.stop();
@@ -210,8 +214,8 @@
210214 }
211215
212216 private class CloseCluster implements Callable<Void> {
213- private final Cluster cluster;
214- private final SocketChannelMonitor channelMonitor;
217+ private Cluster cluster;
218+ private SocketChannelMonitor channelMonitor;
215219 private final CountDownLatch startSignal;
216220
217221 CloseCluster(Cluster cluster, SocketChannelMonitor channelMonitor, CountDownLatch startSignal) {
@@ -223,12 +227,15 @@
223227 @Override
224228 public Void call() throws Exception {
225229 startSignal.await();
226-
227- cluster.close();
228- assertEquals(cluster.manager.sessions.size(), 0);
229- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
230- channelMonitor.stop();
231-
230+ try {
231+ cluster.close();
232+ assertEquals(cluster.manager.sessions.size(), 0);
233+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
234+ } finally {
235+ channelMonitor.stop();
236+ cluster = null;
237+ channelMonitor = null;
238+ }
232239 return null;
233240 }
234241 }
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +1 −1
@@ -131,7 +131,7 @@
131131 assertThat(controlHost).isEqualTo(firstHost.getAddress());
132132
133133 // Decommission the node.
134- ccm.decommision(1);
134+ ccm.decommission(1);
135135
136136 // Ensure that the new control connection is not null and it's host is not equal to the decommissioned node.
137137 Host newHost = cluster.manager.controlConnection.connectedHost();
modified driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +1 −1
@@ -73,7 +73,7 @@
7373 Host host3 = TestUtils.findHost(cluster, 3);
7474 Token host3Token = tokensForHost.get(host3);
7575
76- ccm.decommision(3);
76+ ccm.decommission(3);
7777 ccm.remove(3);
7878
7979 // Ensure that the token ranges were updated, there should only be 2 ranges now.
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +58 −62
@@ -25,79 +25,75 @@
2525 import io.netty.util.Timer;
2626 import org.mockito.invocation.InvocationOnMock;
2727 import org.mockito.stubbing.Answer;
28-import org.testng.annotations.DataProvider;
2928 import org.testng.annotations.Test;
3029
3130 import java.util.concurrent.ThreadFactory;
3231
32+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
3333 import static org.mockito.Answers.CALLS_REAL_METHODS;
3434 import static org.mockito.Matchers.any;
3535 import static org.mockito.Mockito.*;
3636
37-public class NettyOptionsTest {
37+@CreateCCM(PER_METHOD)
38+@CCMConfig(createCluster = false)
39+public class NettyOptionsTest extends CCMTestsSupport {
3840
39- @DataProvider(name = "NettyOptionsTest")
40- public static Object[][] parameters() {
41- Object[][] params = new Object[][]{{1, 1}, {3, 4}};
42- return params;
41+ @Test(groups = "short")
42+ public void should_invoke_netty_options_hooks_single_node() throws Exception {
43+ should_invoke_netty_options_hooks(1, 1);
4344 }
4445
45- @Test(groups = "short", dataProvider = "NettyOptionsTest")
46- public void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception {
47- //given
48- CCMBridge ccm = CCMBridge.builder().withNodes(hosts).build();
49- Cluster cluster = null;
50- try {
51- NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
52- EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
53- Timer timer = new HashedWheelTimer();
54- doReturn(eventLoopGroup).when(nettyOptions).eventLoopGroup(any(ThreadFactory.class));
55- doReturn(timer).when(nettyOptions).timer(any(ThreadFactory.class));
56- final ChannelHandler handler = mock(ChannelHandler.class);
57- doAnswer(new Answer() {
58- @Override
59- public Object answer(InvocationOnMock invocation) throws Throwable {
60- SocketChannel channel = (SocketChannel) invocation.getArguments()[0];
61- channel.pipeline().addLast("test-handler", handler);
62- return null;
63- }
64- }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
65- cluster = Cluster.builder()
66- .addContactPointsWithPorts(ccm.addressOfNode(1))
67- .withPort(ccm.getBinaryPort())
68- .withPoolingOptions(new PoolingOptions()
69- .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
70- )
71- .withNettyOptions(nettyOptions)
72- .build();
73- // when
74- cluster.connect();// force session creation to populate pools
75-
76- int expectedNumberOfCalls = TestUtils.numberOfLocalCoreConnections(cluster) * hosts + 1;
77- // If the driver supports a more recent protocol version than C*, the negotiation at startup
78- // will open 1 extra connection.
79- if (!ProtocolVersion.NEWEST_SUPPORTED.isSupportedBy(TestUtils.findHost(cluster, 1)))
80- expectedNumberOfCalls += 1;
81-
82- cluster.close();
83- // then
84- verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class));
85- verify(nettyOptions, times(1)).channelClass();
86- verify(nettyOptions, times(1)).timer(any(ThreadFactory.class));
87- // per-connection hooks will be called coreConnections * hosts + 1 times:
88- // the extra call is for the control connection
89- verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class));
90- verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class));
91- verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class));
92- verify(handler, times(expectedNumberOfCalls)).handlerRemoved(any(ChannelHandlerContext.class));
93- verify(nettyOptions, times(1)).onClusterClose(eventLoopGroup);
94- verify(nettyOptions, times(1)).onClusterClose(timer);
95- verifyNoMoreInteractions(nettyOptions);
96- } finally {
97- if (cluster != null)
98- cluster.close();
99- ccm.remove();
100- }
46+ @CCMConfig(numberOfNodes = 3)
47+ @Test(groups = "short")
48+ public void should_invoke_netty_options_hooks_multi_node() throws Exception {
49+ should_invoke_netty_options_hooks(3, 4);
10150 }
10251
52+ private void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception {
53+ NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
54+ EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
55+ Timer timer = new HashedWheelTimer();
56+ doReturn(eventLoopGroup).when(nettyOptions).eventLoopGroup(any(ThreadFactory.class));
57+ doReturn(timer).when(nettyOptions).timer(any(ThreadFactory.class));
58+ final ChannelHandler handler = mock(ChannelHandler.class);
59+ doAnswer(new Answer() {
60+ @Override
61+ public Object answer(InvocationOnMock invocation) throws Throwable {
62+ SocketChannel channel = (SocketChannel) invocation.getArguments()[0];
63+ channel.pipeline().addLast("test-handler", handler);
64+ return null;
65+ }
66+ }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
67+ Cluster cluster = register(Cluster.builder()
68+ .addContactPointsWithPorts(ccm.addressOfNode(1))
69+ .withPort(ccm.getBinaryPort())
70+ .withPoolingOptions(new PoolingOptions()
71+ .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
72+ )
73+ .withNettyOptions(nettyOptions)
74+ .build());
75+ // when
76+ cluster.connect();// force session creation to populate pools
77+
78+ int expectedNumberOfCalls = TestUtils.numberOfLocalCoreConnections(cluster) * hosts + 1;
79+ // If the driver supports a more recent protocol version than C*, the negotiation at startup
80+ // will open 1 extra connection.
81+ if (!ProtocolVersion.NEWEST_SUPPORTED.isSupportedBy(TestUtils.findHost(cluster, 1)))
82+ expectedNumberOfCalls += 1;
83+
84+ cluster.close();
85+ // then
86+ verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class));
87+ verify(nettyOptions, times(1)).channelClass();
88+ verify(nettyOptions, times(1)).timer(any(ThreadFactory.class));
89+ // per-connection hooks will be called coreConnections * hosts + 1 times:
90+ // the extra call is for the control connection
91+ verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class));
92+ verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class));
93+ verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class));
94+ verify(handler, times(expectedNumberOfCalls)).handlerRemoved(any(ChannelHandlerContext.class));
95+ verify(nettyOptions, times(1)).onClusterClose(eventLoopGroup);
96+ verify(nettyOptions, times(1)).onClusterClose(timer);
97+ verifyNoMoreInteractions(nettyOptions);
98+ }
10399 }
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +39 −17
@@ -39,12 +39,16 @@
3939 public class RecommissionedNodeTest {
4040 private static final Logger logger = LoggerFactory.getLogger(RecommissionedNodeTest.class);
4141
42- CCMBridge mainCcm, otherCcm;
42+ CCMBridge.Builder mainCcmBuilder, otherCcmBuilder;
43+ CCMAccess mainCcm, otherCcm;
4344 Cluster mainCluster;
4445
4546 @Test(groups = "long")
4647 public void should_ignore_recommissioned_node_on_reconnection_attempt() throws Exception {
47- mainCcm = CCMBridge.builder().withNodes(3).build();
48+ mainCcmBuilder = CCMBridge.builder().withNodes(3).notStarted();
49+ mainCcm = CCMCache.get(mainCcmBuilder);
50+ mainCcm.start();
51+
4852 // node1 will be our "recommissioned" node, for now we just stop it so that it stays in the peers table.
4953 mainCcm.stop(1);
5054 mainCcm.waitForDown(1);
@@ -59,11 +63,13 @@
5963 // From that point, reconnections to node1 have been scheduled.
6064
6165 // Start another ccm that will reuse node1's address
62- otherCcm = CCMBridge.builder()
66+ otherCcmBuilder = CCMBridge.builder()
6367 .withStoragePort(mainCcm.getStoragePort())
6468 .withThriftPort(mainCcm.getThriftPort())
6569 .withBinaryPort(mainCcm.getBinaryPort())
66- .withNodes(1).build();
70+ .withNodes(1).notStarted();
71+ otherCcm = CCMCache.get(otherCcmBuilder);
72+ otherCcm.start();
6773 otherCcm.waitForUp(1);
6874
6975 // Give the driver the time to notice the node is back up and try to connect to it.
@@ -74,7 +80,9 @@
7480
7581 @Test(groups = "long")
7682 public void should_ignore_recommissioned_node_on_control_connection_reconnect() throws Exception {
77- mainCcm = CCMBridge.builder().withNodes(2).build();
83+ mainCcmBuilder = CCMBridge.builder().withNodes(2).notStarted();
84+ mainCcm = CCMCache.get(mainCcmBuilder);
85+ mainCcm.start();
7886 mainCcm.stop(1);
7987 mainCcm.waitForDown(1);
8088
@@ -87,11 +95,13 @@
8795 waitForCountUpHosts(mainCluster, 1);
8896
8997 // Start another ccm that will reuse node1's address
90- otherCcm = CCMBridge.builder()
98+ otherCcmBuilder = CCMBridge.builder()
9199 .withStoragePort(mainCcm.getStoragePort())
92100 .withThriftPort(mainCcm.getThriftPort())
93101 .withBinaryPort(mainCcm.getBinaryPort())
94- .withNodes(1).build();
102+ .withNodes(1).notStarted();
103+ otherCcm = CCMCache.get(otherCcmBuilder);
104+ otherCcm.start();
95105 otherCcm.waitForUp(1);
96106
97107 // Stop node2, the control connection gets defunct
@@ -105,15 +115,19 @@
105115 @Test(groups = "long")
106116 public void should_ignore_recommissioned_node_on_session_init() throws Exception {
107117 // Simulate the bug before starting the cluster
108- mainCcm = CCMBridge.builder().withNodes(2).build();
118+ mainCcmBuilder = CCMBridge.builder().withNodes(2).notStarted();
119+ mainCcm = CCMCache.get(mainCcmBuilder);
120+ mainCcm.start();
109121 mainCcm.stop(1);
110122 mainCcm.waitForDown(1);
111123
112- otherCcm = CCMBridge.builder()
124+ otherCcmBuilder = CCMBridge.builder()
113125 .withStoragePort(mainCcm.getStoragePort())
114126 .withThriftPort(mainCcm.getThriftPort())
115127 .withBinaryPort(mainCcm.getBinaryPort())
116- .withNodes(1).build();
128+ .withNodes(1).notStarted();
129+ otherCcm = CCMCache.get(otherCcmBuilder);
130+ otherCcm.start();
117131 otherCcm.waitForUp(1);
118132
119133 // Start the driver, it should only connect to node 2
@@ -140,16 +154,19 @@
140154 @CassandraVersion(major = 2.0)
141155 public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception {
142156 // Simulate the bug before starting the cluster
143- mainCcm = CCMBridge.builder().withNodes(2).build();
157+ mainCcmBuilder = CCMBridge.builder().withNodes(2).notStarted();
158+ mainCcm = CCMCache.get(mainCcmBuilder);
159+ mainCcm.start();
144160 mainCcm.stop(1);
145161 mainCcm.waitForDown(1);
146162
147- otherCcm = CCMBridge.builder().withNodes(1)
163+ otherCcmBuilder = CCMBridge.builder().withNodes(1)
148164 .withStoragePort(mainCcm.getStoragePort())
149165 .withThriftPort(mainCcm.getThriftPort())
150166 .withBinaryPort(mainCcm.getBinaryPort())
151- .withVersion("1.2.19")
152- .build();
167+ .withVersion("1.2.19").notStarted();
168+ otherCcm = CCMCache.get(otherCcmBuilder);
169+ otherCcm.start();
153170 otherCcm.waitForUp(1);
154171
155172 // Start the driver, it should only connect to node 2
@@ -172,6 +189,8 @@
172189 public void clearFields() {
173190 // Clear cluster and ccm instances between tests.
174191 mainCluster = null;
192+ mainCcmBuilder = null;
193+ otherCcmBuilder = null;
175194 mainCcm = null;
176195 otherCcm = null;
177196 }
@@ -180,11 +199,14 @@
180199 public void teardown() {
181200 if (mainCluster != null)
182201 mainCluster.close();
183-
202+ if (mainCcmBuilder != null)
203+ CCMCache.remove(mainCcmBuilder);
204+ if (otherCcmBuilder != null)
205+ CCMCache.remove(otherCcmBuilder);
184206 if (mainCcm != null)
185- mainCcm.remove();
207+ mainCcm.close();
186208 if (otherCcm != null)
187- otherCcm.remove();
209+ otherCcm.close();
188210 }
189211
190212 private static int countUpHosts(Cluster cluster) {
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +10 −2
@@ -59,6 +59,9 @@
5959 fail("executor ran for longer than expected");
6060 } catch (InterruptedException e) {
6161 fail("Interrupted while waiting for executor to shutdown");
62+ } finally {
63+ executorService = null;
64+ System.gc();
6265 }
6366 }
6467
@@ -175,6 +178,7 @@
175178 }
176179 } finally {
177180 stressCluster.close();
181+ stressCluster = null;
178182
179183 // Ensure no channels remain open.
180184 assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
@@ -263,7 +267,7 @@
263267 }
264268
265269 private static class CloseSession implements Callable<CloseFuture> {
266- private final Session session;
270+ private Session session;
267271 private final CountDownLatch startSignal;
268272
269273 CloseSession(Session session, CountDownLatch startSignal) {
@@ -274,7 +278,11 @@
274278 @Override
275279 public CloseFuture call() throws Exception {
276280 startSignal.await();
277- return session.closeAsync();
281+ try {
282+ return session.closeAsync();
283+ } finally {
284+ session = null;
285+ }
278286 }
279287 }
280288 }
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +1 −1
@@ -51,7 +51,7 @@
5151 listener.waitForEvent();
5252
5353 listener.setExpectedEvent(REMOVE);
54- ccm.decommision(2);
54+ ccm.decommission(2);
5555 listener.waitForEvent();
5656 }
5757
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +35 −40
@@ -26,9 +26,12 @@
2626 import java.util.List;
2727
2828 import static com.datastax.driver.core.Assertions.assertThat;
29+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2930 import static com.datastax.driver.core.TestUtils.*;
3031
31-public class TokenAwarePolicyTest {
32+@CreateCCM(PER_METHOD)
33+@CCMConfig(createCcm = false)
34+public class TokenAwarePolicyTest extends CCMTestsSupport {
3235
3336 QueryTracker queryTracker;
3437
@@ -316,51 +319,43 @@
316319 * @test_category load_balancing:token_aware
317320 * @jira_ticket JAVA-123 (to ensure routing key buffers are not destroyed).
318321 */
322+ @CCMConfig(createCcm = true, numberOfNodes = 3, createCluster = false)
319323 @Test(groups = "long")
320324 public void should_properly_generate_and_use_routing_key_for_composite_partition_key() {
321325 // given: a 3 node cluster with a keyspace with RF 1.
322- CCMBridge ccm = CCMBridge.builder().withNodes(3).notStarted().build();
323-
324- Cluster cluster = Cluster.builder()
326+ Cluster cluster = register(Cluster.builder()
325327 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
326328 .addContactPointsWithPorts(ccm.addressOfNode(1))
327329 .withPort(ccm.getBinaryPort())
328- .build();
329-
330- try {
331- ccm.start();
332- Session session = cluster.connect();
333-
334- String table = "composite";
335- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, SIMPLE_KEYSPACE, 1));
336- session.execute("USE " + SIMPLE_KEYSPACE);
337- session.execute(String.format("CREATE TABLE %s (k1 int, k2 int, i int, PRIMARY KEY ((k1, k2)))", table));
338-
339- // (1,2) resolves to token '4881097376275569167' which belongs to node 1 so all queries should go to that node.
340- PreparedStatement insertPs = session.prepare("INSERT INTO " + table + "(k1, k2, i) VALUES (?, ?, ?)");
341- BoundStatement insertBs = insertPs.bind(1, 2, 3);
342-
343- PreparedStatement selectPs = session.prepare("SELECT * FROM " + table + " WHERE k1=? and k2=?");
344- BoundStatement selectBs = selectPs.bind(1, 2);
345-
346- // when: executing a prepared statement with a composite partition key.
347- // then: should query the correct node (1) in for both insert and select queries.
348- for (int i = 0; i < 10; i++) {
349- ResultSet rs = session.execute(insertBs);
350- assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
351-
352- rs = session.execute(selectBs);
353- assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
354- assertThat(rs.isExhausted()).isFalse();
355- Row r = rs.one();
356- assertThat(rs.isExhausted()).isTrue();
357-
358- assertThat(r.getInt("i")).isEqualTo(3);
359- }
360-
361- } finally {
362- cluster.close();
363- ccm.remove();
330+ .build());
331+ Session session = cluster.connect();
332+
333+ String table = "composite";
334+ String ks = TestUtils.getAvailableKeyspaceName();
335+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ks, 1));
336+ session.execute("USE " + ks);
337+ session.execute(String.format("CREATE TABLE %s (k1 int, k2 int, i int, PRIMARY KEY ((k1, k2)))", table));
338+
339+ // (1,2) resolves to token '4881097376275569167' which belongs to node 1 so all queries should go to that node.
340+ PreparedStatement insertPs = session.prepare("INSERT INTO " + table + "(k1, k2, i) VALUES (?, ?, ?)");
341+ BoundStatement insertBs = insertPs.bind(1, 2, 3);
342+
343+ PreparedStatement selectPs = session.prepare("SELECT * FROM " + table + " WHERE k1=? and k2=?");
344+ BoundStatement selectBs = selectPs.bind(1, 2);
345+
346+ // when: executing a prepared statement with a composite partition key.
347+ // then: should query the correct node (1) in for both insert and select queries.
348+ for (int i = 0; i < 10; i++) {
349+ ResultSet rs = session.execute(insertBs);
350+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
351+
352+ rs = session.execute(selectBs);
353+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
354+ assertThat(rs.isExhausted()).isFalse();
355+ Row r = rs.one();
356+ assertThat(rs.isExhausted()).isTrue();
357+
358+ assertThat(r.getInt("i")).isEqualTo(3);
364359 }
365360 }
366361 }
modified driver-core/src/test/resources/log4j.properties +1 −0
@@ -41,6 +41,7 @@
4141
4242 # Adjust log levels for CCM tests
4343 #log4j.logger.com.datastax.driver.core.CCMTestsSupport=DEBUG
44+#log4j.logger.com.datastax.driver.core.CCMCache=DEBUG
4445 #log4j.logger.com.datastax.driver.core.CCMBridge=DEBUG
4546
4647 # A1 is set to be a ConsoleAppender.
modified driver-mapping/src/test/java/com/datastax/driver/mapping/UDTFieldMapperTest.java +82 −103
@@ -15,7 +15,8 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMConfig;
19+import com.datastax.driver.core.CCMTestsSupport;
1920 import com.datastax.driver.core.Cluster;
2021 import com.datastax.driver.core.Session;
2122 import com.datastax.driver.core.utils.CassandraVersion;
@@ -27,116 +28,94 @@
2728 import java.util.Map;
2829
2930 @CassandraVersion(major = 2.1)
31+@CCMConfig(createCluster = false)
3032 @SuppressWarnings("unused")
31-public class UDTFieldMapperTest {
33+public class UDTFieldMapperTest extends CCMTestsSupport {
3234
3335 @Test(groups = "short")
3436 public void udt_and_tables_with_ks_created_in_another_session_should_be_mapped() {
35- CCMBridge ccm = null;
36- Cluster cluster = null;
37-
38- try {
39- // Create type and table
40- ccm = CCMBridge.builder().build();
41- cluster = Cluster.builder()
42- .addContactPointsWithPorts(ccm.addressOfNode(1))
43- .withPort(ccm.getBinaryPort())
44- .build();
45- Session session1 = cluster.connect();
46- session1.execute("create schema if not exists java_509 " +
47- "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
48- session1.execute("create type java_509.my_tuple (" +
49- "type text, " +
50- "value text);");
51- session1.execute("create table java_509.my_hash (" +
52- "key int primary key, " +
53- "properties map<text, frozen<java_509.my_tuple>>);");
54- cluster.close();
55-
56- // Create entities with another connection
57- cluster = Cluster.builder()
58- .addContactPointsWithPorts(ccm.addressOfNode(1))
59- .withPort(ccm.getBinaryPort())
60- .build();
61- Session session2 = cluster.newSession();
62- Mapper<MyHashWithKeyspace> hashMapper = new MappingManager(session2).mapper(MyHashWithKeyspace.class);
63- hashMapper.save(new MyHashWithKeyspace(
64- 1,
65- ImmutableMap.of("key-1", new MyTupleWithKeyspace("first-half-1", "second-half-1"))));
66- hashMapper.save(new MyHashWithKeyspace(
67- 2,
68- ImmutableMap.of("key-2", new MyTupleWithKeyspace("first-half-2", null))));
69- hashMapper.save(new MyHashWithKeyspace(
70- 3,
71- ImmutableMap.of("key-3", new MyTupleWithKeyspace(null, "second-half-3"))));
72- hashMapper.save(new MyHashWithKeyspace(
73- 4,
74- new HashMap<String, MyTupleWithKeyspace>()));
75- hashMapper.save(new MyHashWithKeyspace(
76- 5,
77- null));
78- } finally {
79- if (cluster != null)
80- cluster.close();
81- if (ccm != null)
82- ccm.remove();
83- }
37+ Cluster cluster = register(Cluster.builder()
38+ .addContactPointsWithPorts(ccm.addressOfNode(1))
39+ .withPort(ccm.getBinaryPort())
40+ .build());
41+ Session session1 = cluster.connect();
42+ // Create type and table
43+ session1.execute("create schema if not exists java_509 " +
44+ "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
45+ session1.execute("create type java_509.my_tuple (" +
46+ "type text, " +
47+ "value text);");
48+ session1.execute("create table java_509.my_hash (" +
49+ "key int primary key, " +
50+ "properties map<text, frozen<java_509.my_tuple>>);");
51+ cluster.close();
52+
53+ // Create entities with another connection
54+ cluster = register(Cluster.builder()
55+ .addContactPointsWithPorts(ccm.addressOfNode(1))
56+ .withPort(ccm.getBinaryPort())
57+ .build());
58+ Session session2 = cluster.newSession();
59+ Mapper<MyHashWithKeyspace> hashMapper = new MappingManager(session2).mapper(MyHashWithKeyspace.class);
60+ hashMapper.save(new MyHashWithKeyspace(
61+ 1,
62+ ImmutableMap.of("key-1", new MyTupleWithKeyspace("first-half-1", "second-half-1"))));
63+ hashMapper.save(new MyHashWithKeyspace(
64+ 2,
65+ ImmutableMap.of("key-2", new MyTupleWithKeyspace("first-half-2", null))));
66+ hashMapper.save(new MyHashWithKeyspace(
67+ 3,
68+ ImmutableMap.of("key-3", new MyTupleWithKeyspace(null, "second-half-3"))));
69+ hashMapper.save(new MyHashWithKeyspace(
70+ 4,
71+ new HashMap<String, MyTupleWithKeyspace>()));
72+ hashMapper.save(new MyHashWithKeyspace(
73+ 5,
74+ null));
8475 }
8576
8677 @Test(groups = "short")
8778 public void udt_and_tables_without_ks_created_in_another_session_should_be_mapped() {
88- CCMBridge ccm = null;
89- Cluster cluster = null;
90-
91- try {
92- // Create type and table
93- ccm = CCMBridge.builder().build();
94- cluster = Cluster.builder()
95- .addContactPointsWithPorts(ccm.addressOfNode(1))
96- .withPort(ccm.getBinaryPort())
97- .build();
98- Session session1 = cluster.connect();
99- session1.execute("create schema if not exists java_509 " +
100- "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
101- session1.execute("use java_509");
102- session1.execute("create type my_tuple (" +
103- "type text, " +
104- "value text);");
105- session1.execute("create table my_hash (" +
106- "key int primary key, " +
107- "properties map<text, frozen<my_tuple>>);");
108- cluster.close();
109-
110- // Create entities with another connection
111- cluster = Cluster.builder()
112- .addContactPointsWithPorts(ccm.addressOfNode(1))
113- .withPort(ccm.getBinaryPort())
114- .build();
115- Session session2 = cluster.newSession();
116-
117- session2.execute("use java_509");
118- Mapper<MyHash> hashMapper = new MappingManager(session2).mapper(MyHash.class);
119- hashMapper.save(new MyHash(
120- 1,
121- ImmutableMap.of("key-1", new MyTuple("first-half-1", "second-half-1"))));
122- hashMapper.save(new MyHash(
123- 2,
124- ImmutableMap.of("key-2", new MyTuple("first-half-2", null))));
125- hashMapper.save(new MyHash(
126- 3,
127- ImmutableMap.of("key-3", new MyTuple(null, "second-half-3"))));
128- hashMapper.save(new MyHash(
129- 4,
130- new HashMap<String, MyTuple>()));
131- hashMapper.save(new MyHash(
132- 5,
133- null));
134- } finally {
135- if (cluster != null)
136- cluster.close();
137- if (ccm != null)
138- ccm.remove();
139- }
79+ Cluster cluster = register(Cluster.builder()
80+ .addContactPointsWithPorts(ccm.addressOfNode(1))
81+ .withPort(ccm.getBinaryPort())
82+ .build());
83+ Session session1 = cluster.connect();
84+ session1.execute("create schema if not exists java_509b " +
85+ "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
86+ session1.execute("use java_509b");
87+ session1.execute("create type my_tuple (" +
88+ "type text, " +
89+ "value text);");
90+ session1.execute("create table my_hash (" +
91+ "key int primary key, " +
92+ "properties map<text, frozen<my_tuple>>);");
93+ cluster.close();
94+
95+ // Create entities with another connection
96+ cluster = Cluster.builder()
97+ .addContactPointsWithPorts(ccm.addressOfNode(1))
98+ .withPort(ccm.getBinaryPort())
99+ .build();
100+ Session session2 = cluster.newSession();
101+
102+ session2.execute("use java_509b");
103+ Mapper<MyHash> hashMapper = new MappingManager(session2).mapper(MyHash.class);
104+ hashMapper.save(new MyHash(
105+ 1,
106+ ImmutableMap.of("key-1", new MyTuple("first-half-1", "second-half-1"))));
107+ hashMapper.save(new MyHash(
108+ 2,
109+ ImmutableMap.of("key-2", new MyTuple("first-half-2", null))));
110+ hashMapper.save(new MyHash(
111+ 3,
112+ ImmutableMap.of("key-3", new MyTuple(null, "second-half-3"))));
113+ hashMapper.save(new MyHash(
114+ 4,
115+ new HashMap<String, MyTuple>()));
116+ hashMapper.save(new MyHash(
117+ 5,
118+ null));
140119 }
141120
142121 @UDT(name = "my_tuple")