Elffuss BraidHub

kikocis/java-driver public

Merge branch '3.0.x' into 3.0
Changeset909018904d3ca347db2f8aea844362d51af8eab92883a857351b0e64aca83de9
Authorolim7t <omichallat+github@gmail.com> · 2016-07-13 15:25 -07:00
Committerolim7t <omichallat+github@gmail.com> · 2016-07-13 15:25 -07:00
Parentsf0747dbb178c, 6c9b5d299f55

Browse the files at this changeset

63 files changed

modified changelog/README.md +24 −0
@@ -57,6 +57,30 @@
5757 - [improvement] JAVA-444: Add Java process information to UUIDs.makeNode() hash.
5858
5959
60+### 3.0.3
61+
62+- [improvement] JAVA-1147: Upgrade Netty to 4.0.37.
63+- [bug] JAVA-1213: Allow updates and inserts to BLOB column using read-only ByteBuffer.
64+- [bug] JAVA-1209: ProtocolOptions.getProtocolVersion() should return null instead of throwing NPE if Cluster has not
65+ been init'd.
66+- [improvement] JAVA-1204: Update documentation to indicate tcnative version requirement.
67+- [bug] JAVA-1186: Fix duplicated hosts in DCAwarePolicy warn message.
68+- [bug] JAVA-1187: Fix warning message when local CL used with RoundRobinPolicy.
69+- [improvement] JAVA-1175: Warn if DCAwarePolicy configuration is inconsistent.
70+- [bug] JAVA-1139: ConnectionException.getMessage() throws NPE if address is null.
71+- [bug] JAVA-1202: Handle null rpc_address when checking schema agreement.
72+- [improvement] JAVA-1198: Document that BoundStatement is not thread-safe.
73+- [improvement] JAVA-1200: Upgrade LZ4 to 1.3.0.
74+- [bug] JAVA-1232: Fix NPE in IdempotenceAwareRetryPolicy.isIdempotent.
75+- [improvement] JAVA-1227: Document "SELECT *" issue with prepared statement.
76+- [bug] JAVA-1160: Fix NPE in VersionNumber.getPreReleaseLabels().
77+- [improvement] JAVA-1126: Handle schema changes in Mapper.
78+- [bug] JAVA-1193: Refresh token and replica metadata synchronously when schema is altered.
79+- [bug] JAVA-1120: Skip schema refresh debouncer when checking for agreement as a result of schema change made by client.
80+- [improvement] JAVA-1242: Fix driver-core dependency in driver-stress
81+- [improvement] JAVA-1235: Move the query to the end of "re-preparing .." log message as a key value.
82+
83+
6084 ### 3.0.2
6185
6286 Merged from 2.1 branch:
added ci/appveyor.ps1 +129 −0
@@ -0,0 +1,129 @@
1+Add-Type -AssemblyName System.IO.Compression.FileSystem
2+
3+$dep_dir="C:\Users\appveyor\deps"
4+If (!(Test-Path $dep_dir)) {
5+ Write-Host "Creating $($dep_dir)"
6+ New-Item -Path $dep_dir -ItemType Directory -Force
7+}
8+
9+$apr_platform = "Win32"
10+$openssl_platform = "Win32"
11+$vc_platform = "x86"
12+$env:PYTHON="C:\Python27"
13+$env:OPENSSL_PATH="C:\OpenSSL-Win32"
14+If ($env:PLATFORM -eq "X64") {
15+ $apr_platform = "x64"
16+ $vc_platform = "x64"
17+ $env:PYTHON="C:\Python27-x64"
18+ $env:OPENSSL_PATH="C:\OpenSSL-Win64"
19+}
20+
21+$env:JAVA_HOME="C:\Program Files\Java\jdk$($env:java_version)"
22+$env:JAVA_8_HOME="C:\Program Files\Java\jdk1.8.0"
23+$env:PATH="$($env:PYTHON);$($env:PYTHON)\Scripts;$($env:JAVA_HOME)\bin;$($env:OPENSSL_PATH)\bin;$($env:PATH)"
24+$env:CCM_PATH="$($dep_dir)\ccm"
25+
26+$apr_dist_path = "$($dep_dir)\apr"
27+# Build APR if it hasn't been previously built.
28+If (!(Test-Path $apr_dist_path)) {
29+ Write-Host "Cloning APR"
30+ $apr_path = "C:\Users\appveyor\apr"
31+ Start-Process git -ArgumentList "clone --branch=1.5.2 --depth=1 https://github.com/apache/apr.git $($apr_path)" -Wait -nnw
32+ Write-Host "Setting Visual Studio Environment to VS 2015"
33+ Push-Location "$($env:VS140COMNTOOLS)\..\..\VC"
34+ cmd /c "vcvarsall.bat $vc_platform & set" |
35+ foreach {
36+ if ($_ -match "=") {
37+ $v = $_.split("="); Set-Item -force -path "ENV:\$($v[0])" -value "$($v[1])"
38+ }
39+ }
40+ Pop-Location
41+ Write-Host "Building APR (an error may be printed, but it will still build)"
42+ Push-Location $($apr_path)
43+ cmd /c nmake -f Makefile.win ARCH="$apr_platform Release" PREFIX=$($apr_dist_path) buildall install
44+ Pop-Location
45+ Write-Host "Done Building APR"
46+}
47+$env:PATH="$($apr_dist_path)\bin;$($env:PATH)"
48+
49+# Install Ant and Maven
50+$ant_base = "$($dep_dir)\ant"
51+$ant_path = "$($ant_base)\apache-ant-1.9.7"
52+If (!(Test-Path $ant_path)) {
53+ Write-Host "Installing Ant"
54+ $ant_url = "https://www.dropbox.com/s/lgx95x1jr6s787l/apache-ant-1.9.7-bin.zip?dl=1"
55+ $ant_zip = "C:\Users\appveyor\apache-ant-1.9.7-bin.zip"
56+ (new-object System.Net.WebClient).DownloadFile($ant_url, $ant_zip)
57+ [System.IO.Compression.ZipFile]::ExtractToDirectory($ant_zip, $ant_base)
58+}
59+$env:PATH="$($ant_path)\bin;$($env:PATH)"
60+
61+$maven_base = "$($dep_dir)\maven"
62+$maven_path = "$($maven_base)\apache-maven-3.2.5"
63+If (!(Test-Path $maven_path)) {
64+ Write-Host "Installing Maven"
65+ $maven_url = "https://www.dropbox.com/s/fh9kffmexprsmha/apache-maven-3.2.5-bin.zip?dl=1"
66+ $maven_zip = "C:\Users\appveyor\apache-maven-3.2.5-bin.zip"
67+ (new-object System.Net.WebClient).DownloadFile($maven_url, $maven_zip)
68+ [System.IO.Compression.ZipFile]::ExtractToDirectory($maven_zip, $maven_base)
69+}
70+$env:PATH="$($maven_path)\bin;$($env:PATH)"
71+
72+$jdks = @("1.6.0", "1.7.0", "1.8.0")
73+foreach ($jdk in $jdks) {
74+ $java_dir = "C:\Program Files\Java\jdk$jdk"
75+ $jce_target = "$java_dir\jre\lib\security"
76+ $jce_indicator = "$jce_target\README.txt"
77+ # Install Java Cryptographic Extensions, needed for SSL.
78+ # If this file doesn't exist we know JCE hasn't been installed.
79+ If (!(Test-Path $jce_indicator)) {
80+ Write-Host "Installing JCE for $jdk"
81+ $zip = "$dep_dir\jce_policy-$jdk.zip"
82+ $url = "https://www.dropbox.com/s/po4308hlwulpvep/UnlimitedJCEPolicyJDK7.zip?dl=1"
83+ $extract_folder = "UnlimitedJCEPolicy"
84+ If ($jdk -eq "1.8.0") {
85+ $url = "https://www.dropbox.com/s/al1e6e92cjdv7m7/jce_policy-8.zip?dl=1"
86+ $extract_folder = "UnlimitedJCEPolicyJDK8"
87+ }
88+ ElseIf ($jdk -eq "1.6.0") {
89+ $url = "https://www.dropbox.com/s/dhrtucxcif4n11k/jce_policy-6.zip?dl=1"
90+ $extract_folder = "jce"
91+ }
92+ # Download zip to staging area if it doesn't exist, we do this because
93+ # we extract it to the directory based on the platform and we want to cache
94+ # this file so it can apply to all platforms.
95+ if(!(Test-Path $zip)) {
96+ (new-object System.Net.WebClient).DownloadFile($url, $zip)
97+ }
98+
99+ [System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $jce_target)
100+
101+ $jcePolicyDir = "$jce_target\$extract_folder"
102+ Move-Item $jcePolicyDir\* $jce_target\ -force
103+ Remove-Item $jcePolicyDir
104+ }
105+}
106+
107+# Install Python Dependencies for CCM.
108+Write-Host "Installing Python Dependencies for CCM"
109+Start-Process python -ArgumentList "-m pip install psutil pyYaml six" -Wait -nnw
110+
111+# Clone ccm from git and use master.
112+If (!(Test-Path $env:CCM_PATH)) {
113+ Write-Host "Cloning CCM"
114+ Start-Process git -ArgumentList "clone https://github.com/pcmanus/ccm.git $($env:CCM_PATH)" -Wait -nnw
115+}
116+
117+# Copy ccm -> ccm.py so windows knows to run it.
118+If (!(Test-Path $env:CCM_PATH\ccm.py)) {
119+ Copy-Item "$env:CCM_PATH\ccm" "$env:CCM_PATH\ccm.py"
120+}
121+$env:PYTHONPATH="$($env:CCM_PATH);$($env:PYTHONPATH)"
122+$env:PATH="$($env:CCM_PATH);$($env:PATH)"
123+
124+# Predownload cassandra version for CCM if it isn't already downloaded.
125+If (!(Test-Path C:\Users\appveyor\.ccm\repository\$env:cassandra_version)) {
126+ Write-Host "Preinstalling C* $($env:cassandra_version)"
127+ Start-Process python -ArgumentList "$($env:CCM_PATH)\ccm.py create -v $($env:cassandra_version) -n 1 predownload" -Wait -nnw
128+ Start-Process python -ArgumentList "$($env:CCM_PATH)\ccm.py remove predownload" -Wait -nnw
129+}
added ci/appveyor.yml +21 −0
@@ -0,0 +1,21 @@
1+environment:
2+ test_profile: default
3+ cassandra_version: 3.5
4+ matrix:
5+ - java_version: 1.6.0
6+ - java_version: 1.7.0
7+ - java_version: 1.8.0
8+ test_profile: short
9+platform: x64
10+install:
11+ - ps: .\ci\appveyor.ps1
12+build_script:
13+ - mvn -B install -DskipTests=true
14+test_script:
15+ - "mvn -B -Dccm.java.home=\"%JAVA_8_HOME%\" -Dccm.maxNumberOfNodes=1 -Dcassandra.version=%cassandra_version% verify -P%test_profile%"
16+on_finish:
17+ - ps: .\ci\uploadtests.ps1
18+cache:
19+ - C:\Users\appveyor\.m2
20+ - C:\Users\appveyor\.ccm\repository
21+ - C:\Users\appveyor\deps -> .\ci\appveyor.ps1
added ci/uploadtests.ps1 +17 −0
@@ -0,0 +1,17 @@
1+$testResults=Get-ChildItem TEST-TestSuite.xml -Recurse
2+
3+Write-Host "Uploading test results."
4+
5+$url = "https://ci.appveyor.com/api/testresults/junit/$($env:APPVEYOR_JOB_ID)"
6+$wc = New-Object 'System.Net.WebClient'
7+
8+foreach ($testResult in $testResults) {
9+ try {
10+ Write-Host -ForegroundColor Green "Uploading $testResult -> $url."
11+ $wc.UploadFile($url, $testResult)
12+ } catch [Net.WebException] {
13+ Write-Host -ForegroundColor Red "Failed Uploading $testResult -> $url. $_"
14+ }
15+}
16+
17+Write-Host "Done uploading test results."
modified driver-core/pom.xml +1 −1
@@ -143,7 +143,7 @@
143143 <dependency>
144144 <groupId>io.netty</groupId>
145145 <artifactId>netty-tcnative</artifactId>
146- <version>1.1.33.Fork10</version>
146+ <version>1.1.33.Fork18</version>
147147 <classifier>${os.detected.classifier}</classifier>
148148 <scope>test</scope>
149149 </dependency>
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +5 −0
@@ -46,6 +46,11 @@
4646 * will be ignored server side (no tombstones will be generated). If you're reusing
4747 * a bound statement, you can {@link #unset(int) unset} variables that were previously
4848 * set.
49+ * <p/>
50+ * This class is <b>not thread-safe</b>. Do not share instances among requests that will
51+ * execute concurrently (e.g. requests run from separate application threads, but also
52+ * separate {@link Session#executeAsync(Statement) executeAsync} calls, even if they're
53+ * triggered from the same thread).
4954 */
5055 public class BoundStatement extends Statement implements SettableData<BoundStatement>, GettableData {
5156 static final ByteBuffer UNSET = ByteBuffer.allocate(0);
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +20 −9
@@ -1857,9 +1857,10 @@
18571857 if (controlConnection.refreshNodeInfo(host)) {
18581858 logger.debug("Successful reconnection to {}, setting host UP", host);
18591859 try {
1860- if (isHostAddition)
1860+ if (isHostAddition) {
18611861 onAdd(host, connection);
1862- else
1862+ submitNodeListRefresh();
1863+ } else
18631864 onUp(host, connection);
18641865 } catch (InterruptedException e) {
18651866 Thread.currentThread().interrupt();
@@ -2134,8 +2135,8 @@
21342135 public PreparedStatement addPrepared(PreparedStatement stmt) {
21352136 PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().id, stmt);
21362137 if (previous != null) {
2137- logger.warn("Re-preparing already prepared query {}. Please note that preparing the same query more than once is "
2138- + "generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.", stmt.getQueryString());
2138+ logger.warn("Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. "
2139+ + "Consider preparing the statement only once. Query='{}'", stmt.getQueryString());
21392140
21402141 // The one object in the cache will get GCed once it's not referenced by the client anymore since we use a weak reference.
21412142 // So we need to make sure that the instance we do return to the user is the one that is in the cache.
@@ -2232,15 +2233,15 @@
22322233 return schemaRefreshRequestDebouncer.eventReceived(request);
22332234 }
22342235
2235- void submitNodeListRefresh() {
2236+ ListenableFuture<Void> submitNodeListRefresh() {
22362237 logger.trace("Submitting node list and token map refresh");
2237- nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest());
2238+ return nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest());
22382239 }
22392240
2240- void submitNodeRefresh(InetSocketAddress address, HostEvent eventType) {
2241+ ListenableFuture<Void> submitNodeRefresh(InetSocketAddress address, HostEvent eventType) {
22412242 NodeRefreshRequest request = new NodeRefreshRequest(address, eventType);
22422243 logger.trace("Submitting node refresh: {}", request);
2243- nodeRefreshRequestDebouncer.eventReceived(request);
2244+ return nodeRefreshRequestDebouncer.eventReceived(request);
22442245 }
22452246
22462247 // refresh the schema using the provided connection, and notice the future with the provided resultset once done
@@ -2271,7 +2272,15 @@
22712272 if (!schemaInAgreement)
22722273 logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds());
22732274
2274- ListenableFuture<Void> schemaReady = refreshSchema ? submitSchemaRefresh(targetType, targetKeyspace, targetName, targetSignature) : MoreFutures.VOID_SUCCESS;
2275+ ListenableFuture<Void> schemaReady;
2276+ if (refreshSchema) {
2277+ schemaReady = submitSchemaRefresh(targetType, targetKeyspace, targetName, targetSignature);
2278+ // JAVA-1120: skip debouncing delay and force immediate delivery
2279+ if (!schemaReady.isDone())
2280+ schemaRefreshRequestDebouncer.scheduleImmediateDelivery();
2281+ } else {
2282+ schemaReady = MoreFutures.VOID_SUCCESS;
2283+ }
22752284 final boolean finalSchemaInAgreement = schemaInAgreement;
22762285 schemaReady.addListener(new Runnable() {
22772286 @Override
@@ -2715,6 +2724,7 @@
27152724 public void runMayThrow() throws Exception {
27162725 if (controlConnection.refreshNodeInfo(host)) {
27172726 onAdd(host, null);
2727+ submitNodeListRefresh();
27182728 } else {
27192729 logger.debug("Not enough info for {}, ignoring host", host);
27202730 }
@@ -2751,6 +2761,7 @@
27512761 if (metadata.remove(host)) {
27522762 logger.info("Cassandra host {} removed", host);
27532763 onRemove(host);
2764+ submitNodeListRefresh();
27542765 }
27552766 }
27562767 };
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +40 −30
@@ -267,16 +267,15 @@
267267
268268 // We need to refresh the node list first so we know about the cassandra version of
269269 // the node we're connecting to.
270+ // This will create the token map for the first time, but it will be incomplete
271+ // due to the lack of keyspace information
270272 refreshNodeListAndTokenMap(connection, cluster, isInitialConnection, true);
271273
274+ // refresh schema will also update the token map again,
275+ // this time with information about keyspaces
272276 logger.debug("[Control connection] Refreshing schema");
273277 refreshSchema(connection, null, null, null, null, cluster);
274278
275- // We need to refresh the node list again;
276- // We want that because the token map was not properly initialized by the first call above,
277- // since it requires the list of keyspaces to be loaded.
278- refreshNodeListAndTokenMap(connection, cluster, false, false);
279-
280279 return connection;
281280 } catch (BusyConnectionException e) {
282281 connection.closeAsync().force();
@@ -306,11 +305,6 @@
306305 if (c == null || c.isClosed())
307306 return;
308307 refreshSchema(c, targetType, targetKeyspace, targetName, signature, cluster);
309- // If we rebuild all from scratch or have an updated keyspace, rebuild the token map
310- // since some replication on some keyspace may have changed
311- if ((targetType == null || targetType == KEYSPACE)) {
312- cluster.submitNodeListRefresh();
313- }
314308 } catch (ConnectionException e) {
315309 logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage());
316310 signalError();
@@ -383,11 +377,13 @@
383377
384378 if (broadcastAddress == null) {
385379 return null;
386- } else if (broadcastAddress.equals(connectedHost.getAddress()) || rpcAddress.equals(connectedHost.getAddress())) {
380+ } else if (broadcastAddress.equals(connectedHost.getAddress()) || (rpcAddress != null && rpcAddress.equals(connectedHost.getAddress()))) {
387381 // Some DSE versions were inserting a line for the local node in peers (with mostly null values). This has been fixed, but if we
388382 // detect that's the case, ignore it as it's not really a big deal.
389383 logger.debug("System.peers on node {} has a line for itself. This is not normal but is a known problem of some DSE version. Ignoring the entry.", connectedHost);
390384 return null;
385+ } else if (rpcAddress == null) {
386+ return null;
391387 } else if (rpcAddress.equals(bindAllAddress)) {
392388 logger.warn("Found host with 0.0.0.0 as rpc_address, using broadcast_address ({}) to contact it instead. If this is incorrect you should avoid the use of 0.0.0.0 server side.", broadcastAddress);
393389 rpcAddress = broadcastAddress;
@@ -550,7 +546,8 @@
550546 connection.write(peersFuture);
551547
552548 String partitioner = null;
553- Map<Host, Collection<String>> tokenMap = new HashMap<Host, Collection<String>>();
549+ Token.Factory factory = null;
550+ Map<Host, Set<Token>> tokenMap = new HashMap<Host, Set<Token>>();
554551
555552 // Update cluster name, DC and rack for the one node we are connected to
556553 Row localRow = localFuture.get().one();
@@ -560,8 +557,10 @@
560557 cluster.metadata.clusterName = clusterName;
561558
562559 partitioner = localRow.getString("partitioner");
563- if (partitioner != null)
560+ if (partitioner != null) {
564561 cluster.metadata.partitioner = partitioner;
562+ factory = Token.getFactory(partitioner);
563+ }
565564
566565 Host host = cluster.metadata.getHost(connection.address);
567566 // In theory host can't be null. However there is no point in risking a NPE in case we
@@ -570,10 +569,12 @@
570569 logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address);
571570 } else {
572571 updateInfo(host, localRow, cluster, isInitialConnection);
573- if (metadataEnabled) {
574- Set<String> tokens = localRow.getSet("tokens", String.class);
575- if (partitioner != null && !tokens.isEmpty())
572+ if (metadataEnabled && factory != null) {
573+ Set<String> tokensStr = localRow.getSet("tokens", String.class);
574+ if (!tokensStr.isEmpty()) {
575+ Set<Token> tokens = toTokens(factory, tokensStr);
576576 tokenMap.put(host, tokens);
577+ }
577578 }
578579 }
579580 }
@@ -584,7 +585,7 @@
584585 List<String> cassandraVersions = new ArrayList<String>();
585586 List<InetAddress> broadcastAddresses = new ArrayList<InetAddress>();
586587 List<InetAddress> listenAddresses = new ArrayList<InetAddress>();
587- List<Set<String>> allTokens = new ArrayList<Set<String>>();
588+ List<Set<Token>> allTokens = new ArrayList<Set<Token>>();
588589 List<String> dseVersions = new ArrayList<String>();
589590 List<Boolean> dseGraphEnabled = new ArrayList<Boolean>();
590591 List<String> dseWorkloads = new ArrayList<String>();
@@ -601,8 +602,14 @@
601602 racks.add(row.getString("rack"));
602603 cassandraVersions.add(row.getString("release_version"));
603604 broadcastAddresses.add(row.getInet("peer"));
604- if (metadataEnabled)
605- allTokens.add(row.getSet("tokens", String.class));
605+ if (metadataEnabled && factory != null) {
606+ Set<String> tokensStr = row.getSet("tokens", String.class);
607+ Set<Token> tokens = null;
608+ if (!tokensStr.isEmpty()) {
609+ tokens = toTokens(factory, tokensStr);
610+ }
611+ allTokens.add(tokens);
612+ }
606613 InetAddress listenAddress = row.getColumnDefinitions().contains("listen_address") ? row.getInet("listen_address") : null;
607614 listenAddresses.add(listenAddress);
608615 String dseWorkload = row.getColumnDefinitions().contains("workload") ? row.getString("workload") : null;
@@ -645,7 +652,7 @@
645652 if (dseGraphEnabled.get(i) != null)
646653 host.setDseGraphEnabled(dseGraphEnabled.get(i));
647654
648- if (metadataEnabled && partitioner != null && !allTokens.get(i).isEmpty())
655+ if (metadataEnabled && factory != null && allTokens.get(i) != null)
649656 tokenMap.put(host, allTokens.get(i));
650657
651658 if (isNew && !isInitialConnection)
@@ -658,8 +665,16 @@
658665 if (!host.getSocketAddress().equals(connection.address) && !foundHostsSet.contains(host.getSocketAddress()))
659666 cluster.removeHost(host, isInitialConnection);
660667
661- if (metadataEnabled)
662- cluster.metadata.rebuildTokenMap(partitioner, tokenMap);
668+ if (metadataEnabled && factory != null && !tokenMap.isEmpty())
669+ cluster.metadata.rebuildTokenMap(factory, tokenMap);
670+ }
671+
672+ private static Set<Token> toTokens(Token.Factory factory, Set<String> tokensStr) {
673+ Set<Token> tokens = new LinkedHashSet<Token>(tokensStr.size());
674+ for (String tokenStr : tokensStr) {
675+ tokens.add(factory.fromString(tokenStr));
676+ }
677+ return tokens;
663678 }
664679
665680 private static boolean isValidPeer(Row peerRow, boolean logIfInvalid) {
@@ -761,13 +776,15 @@
761776 public void onUp(Host host) {
762777 }
763778
779+ public void onAdd(Host host) {
780+ }
781+
764782 public void onDown(Host host) {
765783 onHostGone(host);
766784 }
767785
768786 public void onRemove(Host host) {
769787 onHostGone(host);
770- cluster.submitNodeListRefresh();
771788 }
772789
773790 private void onHostGone(Host host) {
@@ -788,11 +805,4 @@
788805 backgroundReconnect(0);
789806 }
790807
791- public void onAdd(Host host) {
792- // Refresh infos and token map if we didn't knew about that host, i.e. if we either don't have basic infos on it,
793- // or it's not part of our computed token map
794- Metadata.TokenMap tkmap = cluster.metadata.tokenMap;
795- if (host.getCassandraVersion() == null || tkmap == null || !tkmap.hosts.contains(host))
796- cluster.submitNodeListRefresh();
797- }
798808 }
modified driver-core/src/main/java/com/datastax/driver/core/EventDebouncer.java +1 −1
@@ -164,7 +164,7 @@
164164 return entry.future;
165165 }
166166
167- private void scheduleImmediateDelivery() {
167+ void scheduleImmediateDelivery() {
168168 cancelDelayedDelivery();
169169
170170 while (state == State.RUNNING) {
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +47 −41
@@ -41,7 +41,7 @@
4141 volatile String partitioner;
4242 private final ConcurrentMap<InetSocketAddress, Host> hosts = new ConcurrentHashMap<InetSocketAddress, Host>();
4343 final ConcurrentMap<String, KeyspaceMetadata> keyspaces = new ConcurrentHashMap<String, KeyspaceMetadata>();
44- volatile TokenMap tokenMap;
44+ private volatile TokenMap tokenMap;
4545
4646 final ReentrantLock lock = new ReentrantLock();
4747
@@ -62,18 +62,28 @@
6262 this.cluster = cluster;
6363 }
6464
65- void rebuildTokenMap(String partitioner, Map<Host, Collection<String>> allTokens) {
65+ // rebuilds the token map with the current hosts, typically when refreshing schema metadata
66+ void rebuildTokenMap() {
6667 lock.lock();
6768 try {
68- if (allTokens.isEmpty())
69- return;
70-
71- Token.Factory factory = partitioner == null
72- ? (tokenMap == null ? null : tokenMap.factory)
73- : Token.getFactory(partitioner);
74- if (factory == null)
69+ if (tokenMap == null)
7570 return;
71+ this.tokenMap = TokenMap.build(
72+ tokenMap.factory,
73+ tokenMap.primaryToTokens,
74+ keyspaces.values(),
75+ tokenMap.ring,
76+ tokenMap.tokenRanges,
77+ tokenMap.tokenToPrimary);
78+ } finally {
79+ lock.unlock();
80+ }
81+ }
7682
83+ // rebuilds the token map for a new set of hosts, typically when refreshing nodes list
84+ void rebuildTokenMap(Token.Factory factory, Map<Host, Set<Token>> allTokens) {
85+ lock.lock();
86+ try {
7787 this.tokenMap = TokenMap.build(factory, allTokens, keyspaces.values());
7888 } finally {
7989 lock.unlock();
@@ -264,7 +274,7 @@
264274 if (current == null) {
265275 return Collections.emptySet();
266276 } else {
267- Map<Host, Set<TokenRange>> dcRanges = current.hostsToRanges.get(keyspace);
277+ Map<Host, Set<TokenRange>> dcRanges = current.hostsToRangesByKeyspace.get(keyspace);
268278 if (dcRanges == null) {
269279 return Collections.emptySet();
270280 } else {
@@ -384,7 +394,7 @@
384394 KeyspaceMetadata removeKeyspace(String keyspace) {
385395 KeyspaceMetadata removed = keyspaces.remove(keyspace);
386396 if (tokenMap != null)
387- tokenMap.tokenToHosts.remove(keyspace);
397+ tokenMap.tokenToHostsByKeyspace.remove(keyspace);
388398 return removed;
389399 }
390400
@@ -609,61 +619,57 @@
609619 }
610620 }
611621
612- static class TokenMap {
622+ private static class TokenMap {
613623
614624 private final Token.Factory factory;
615- private final Map<String, Map<Token, Set<Host>>> tokenToHosts;
616- private final Map<String, Map<Host, Set<TokenRange>>> hostsToRanges;
625+ private final Map<Host, Set<Token>> primaryToTokens;
626+ private final Map<String, Map<Token, Set<Host>>> tokenToHostsByKeyspace;
627+ private final Map<String, Map<Host, Set<TokenRange>>> hostsToRangesByKeyspace;
617628 private final List<Token> ring;
618629 private final Set<TokenRange> tokenRanges;
619- final Set<Host> hosts;
630+ private final Map<Token, Host> tokenToPrimary;
620631
621632 private TokenMap(Token.Factory factory,
633+ List<Token> ring,
634+ Set<TokenRange> tokenRanges,
635+ Map<Token, Host> tokenToPrimary,
622636 Map<Host, Set<Token>> primaryToTokens,
623- Map<String, Map<Token, Set<Host>>> tokenToHosts,
624- Map<String, Map<Host, Set<TokenRange>>> hostsToRanges,
625- List<Token> ring, Set<TokenRange> tokenRanges, Set<Host> hosts) {
637+ Map<String, Map<Token, Set<Host>>> tokenToHostsByKeyspace,
638+ Map<String, Map<Host, Set<TokenRange>>> hostsToRangesByKeyspace) {
626639 this.factory = factory;
627- this.tokenToHosts = tokenToHosts;
628- this.hostsToRanges = hostsToRanges;
629640 this.ring = ring;
630641 this.tokenRanges = tokenRanges;
631- this.hosts = hosts;
642+ this.tokenToPrimary = tokenToPrimary;
643+ this.primaryToTokens = primaryToTokens;
644+ this.tokenToHostsByKeyspace = tokenToHostsByKeyspace;
645+ this.hostsToRangesByKeyspace = hostsToRangesByKeyspace;
632646 for (Map.Entry<Host, Set<Token>> entry : primaryToTokens.entrySet()) {
633647 Host host = entry.getKey();
634648 host.setTokens(ImmutableSet.copyOf(entry.getValue()));
635649 }
636650 }
637651
638- public static TokenMap build(Token.Factory factory, Map<Host, Collection<String>> allTokens, Collection<KeyspaceMetadata> keyspaces) {
639-
640- Set<Host> hosts = allTokens.keySet();
652+ private static TokenMap build(Token.Factory factory, Map<Host, Set<Token>> allTokens, Collection<KeyspaceMetadata> keyspaces) {
641653 Map<Token, Host> tokenToPrimary = new HashMap<Token, Host>();
642- Map<Host, Set<Token>> primaryToTokens = new HashMap<Host, Set<Token>>();
643654 Set<Token> allSorted = new TreeSet<Token>();
644-
645- for (Map.Entry<Host, Collection<String>> entry : allTokens.entrySet()) {
655+ for (Map.Entry<Host, ? extends Collection<Token>> entry : allTokens.entrySet()) {
646656 Host host = entry.getKey();
647- for (String tokenStr : entry.getValue()) {
657+ for (Token t : entry.getValue()) {
648658 try {
649- Token t = factory.fromString(tokenStr);
650659 allSorted.add(t);
651660 tokenToPrimary.put(t, host);
652- Set<Token> hostTokens = primaryToTokens.get(host);
653- if (hostTokens == null) {
654- hostTokens = new HashSet<Token>();
655- primaryToTokens.put(host, hostTokens);
656- }
657- hostTokens.add(t);
658661 } catch (IllegalArgumentException e) {
659662 // If we failed parsing that token, skip it
660663 }
661664 }
662665 }
663-
664666 List<Token> ring = new ArrayList<Token>(allSorted);
665667 Set<TokenRange> tokenRanges = makeTokenRanges(ring, factory);
668+ return build(factory, allTokens, keyspaces, ring, tokenRanges, tokenToPrimary);
669+ }
666670
671+ private static TokenMap build(Token.Factory factory, Map<Host, Set<Token>> allTokens, Collection<KeyspaceMetadata> keyspaces, List<Token> ring, Set<TokenRange> tokenRanges, Map<Token, Host> tokenToPrimary) {
672+ Set<Host> hosts = allTokens.keySet();
667673 Map<String, Map<Token, Set<Host>>> tokenToHosts = new HashMap<String, Map<Token, Set<Host>>>();
668674 Map<ReplicationStrategy, Map<Token, Set<Host>>> replStrategyToHosts = new HashMap<ReplicationStrategy, Map<Token, Set<Host>>>();
669675 Map<String, Map<Host, Set<TokenRange>>> hostsToRanges = new HashMap<String, Map<Host, Set<TokenRange>>>();
@@ -691,17 +697,17 @@
691697 }
692698 hostsToRanges.put(keyspace.getName(), ksRanges);
693699 }
694- return new TokenMap(factory, primaryToTokens, tokenToHosts, hostsToRanges, ring, tokenRanges, hosts);
700+ return new TokenMap(factory, ring, tokenRanges, tokenToPrimary, allTokens, tokenToHosts, hostsToRanges);
695701 }
696702
697703 private Set<Host> getReplicas(String keyspace, Token token) {
698704
699- Map<Token, Set<Host>> keyspaceHosts = tokenToHosts.get(keyspace);
700- if (keyspaceHosts == null)
705+ Map<Token, Set<Host>> tokenToHosts = tokenToHostsByKeyspace.get(keyspace);
706+ if (tokenToHosts == null)
701707 return Collections.emptySet();
702708
703709 // If the token happens to be one of the "primary" tokens, get result directly
704- Set<Host> hosts = keyspaceHosts.get(token);
710+ Set<Host> hosts = tokenToHosts.get(token);
705711 if (hosts != null)
706712 return hosts;
707713
@@ -713,7 +719,7 @@
713719 i = 0;
714720 }
715721
716- return keyspaceHosts.get(ring.get(i));
722+ return tokenToHosts.get(ring.get(i));
717723 }
718724
719725 private static Map<Token, Set<Host>> makeNonReplicatedMap(Map<Token, Host> input) {
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +1 −1
@@ -165,7 +165,7 @@
165165 * nodes that do not support this protocol version will be ignored.
166166 */
167167 public ProtocolVersion getProtocolVersion() {
168- return manager.connectionFactory.protocolVersion;
168+ return manager == null || manager.connectionFactory == null ? null : manager.connectionFactory.protocolVersion;
169169 }
170170
171171 /**
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +15 −1
@@ -16,6 +16,8 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
19+import com.datastax.driver.core.utils.MoreFutures;
20+import com.google.common.util.concurrent.Futures;
1921
2022 /**
2123 * Options related to defaults for individual queries.
@@ -299,7 +301,19 @@
299301 boolean wasEnabled = this.metadataEnabled;
300302 this.metadataEnabled = enabled;
301303 if (!wasEnabled && enabled && manager != null) {
302- manager.submitSchemaRefresh(null, null, null, null); // will also refresh token map
304+ // This is roughly the same as what we do in ControlConnection.tryConnect():
305+ // 1. call submitNodeListRefresh() first to
306+ // be able to compute the token map for the first time,
307+ // which will be incomplete due to the lack of keyspace metadata
308+ Futures.addCallback(manager.submitNodeListRefresh(), new MoreFutures.SuccessCallback<Void>() {
309+ @Override
310+ public void onSuccess(Void result) {
311+ // 2. then call submitSchemaRefresh() to
312+ // refresh schema metadata and re-compute the token map
313+ // this time with information about keyspaces
314+ manager.submitSchemaRefresh(null, null, null, null);
315+ }
316+ });
303317 }
304318 return this;
305319 }
added driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListenerBase.java +122 −0
@@ -0,0 +1,122 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+/**
19+ * Base implementation for {@link SchemaChangeListener}.
20+ */
21+public abstract class SchemaChangeListenerBase implements SchemaChangeListener {
22+
23+ @Override
24+ public void onKeyspaceAdded(KeyspaceMetadata keyspace) {
25+
26+ }
27+
28+ @Override
29+ public void onKeyspaceRemoved(KeyspaceMetadata keyspace) {
30+
31+ }
32+
33+ @Override
34+ public void onKeyspaceChanged(KeyspaceMetadata current, KeyspaceMetadata previous) {
35+
36+ }
37+
38+ @Override
39+ public void onTableAdded(TableMetadata table) {
40+
41+ }
42+
43+ @Override
44+ public void onTableRemoved(TableMetadata table) {
45+
46+ }
47+
48+ @Override
49+ public void onTableChanged(TableMetadata current, TableMetadata previous) {
50+
51+ }
52+
53+ @Override
54+ public void onUserTypeAdded(UserType type) {
55+
56+ }
57+
58+ @Override
59+ public void onUserTypeRemoved(UserType type) {
60+
61+ }
62+
63+ @Override
64+ public void onUserTypeChanged(UserType current, UserType previous) {
65+
66+ }
67+
68+ @Override
69+ public void onFunctionAdded(FunctionMetadata function) {
70+
71+ }
72+
73+ @Override
74+ public void onFunctionRemoved(FunctionMetadata function) {
75+
76+ }
77+
78+ @Override
79+ public void onFunctionChanged(FunctionMetadata current, FunctionMetadata previous) {
80+
81+ }
82+
83+ @Override
84+ public void onAggregateAdded(AggregateMetadata aggregate) {
85+
86+ }
87+
88+ @Override
89+ public void onAggregateRemoved(AggregateMetadata aggregate) {
90+
91+ }
92+
93+ @Override
94+ public void onAggregateChanged(AggregateMetadata current, AggregateMetadata previous) {
95+
96+ }
97+
98+ @Override
99+ public void onMaterializedViewAdded(MaterializedViewMetadata view) {
100+
101+ }
102+
103+ @Override
104+ public void onMaterializedViewRemoved(MaterializedViewMetadata view) {
105+
106+ }
107+
108+ @Override
109+ public void onMaterializedViewChanged(MaterializedViewMetadata current, MaterializedViewMetadata previous) {
110+
111+ }
112+
113+ @Override
114+ public void onRegister(Cluster cluster) {
115+
116+ }
117+
118+ @Override
119+ public void onUnregister(Cluster cluster) {
120+
121+ }
122+}
modified driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +3 −0
@@ -63,6 +63,9 @@
6363 assert rows.keyspaces != null;
6464 Map<String, KeyspaceMetadata> keyspaces = buildKeyspaces(rows, cassandraVersion, cluster);
6565 updateKeyspaces(metadata, metadata.keyspaces, keyspaces, targetKeyspace);
66+ // If we rebuild all from scratch or have an updated keyspace, rebuild the token map
67+ // since some replication on some keyspace may have changed
68+ metadata.rebuildTokenMap();
6669 } else {
6770 assert targetKeyspace != null;
6871 KeyspaceMetadata keyspace = metadata.keyspaces.get(targetKeyspace);
modified driver-core/src/main/java/com/datastax/driver/core/VersionNumber.java +14 −15
@@ -60,7 +60,7 @@
6060 * The version string should have primarily the form X.Y.Z to which can be appended
6161 * one or more pre-release label after dashes (2.0.1-beta1, 2.1.4-rc1-SNAPSHOT)
6262 * and an optional build label (2.1.0-beta1+a20ba.sha). Out of convenience, the
63- * "patch" version number, Z, can be ommitted, in which case it is assumed to be 0.
63+ * "patch" version number, Z, can be omitted, in which case it is assumed to be 0.
6464 *
6565 * @param version the string to parse
6666 * @return the parsed version number.
@@ -139,13 +139,13 @@
139139 }
140140
141141 /**
142- * The pre-release labels if relevants, i.e. label1 and label2 in X.Y.Z-label1-lable2.
142+ * The pre-release labels if relevant, i.e. label1 and label2 in X.Y.Z-label1-lable2.
143143 *
144144 * @return the pre-releases labels. The return list will be {@code null} if the version number
145145 * doesn't have one.
146146 */
147147 public List<String> getPreReleaseLabels() {
148- return Collections.unmodifiableList(Arrays.asList(preReleases));
148+ return preReleases == null ? null : Collections.unmodifiableList(Arrays.asList(preReleases));
149149 }
150150
151151 /**
@@ -217,19 +217,18 @@
217217 }
218218
219219 @Override
220- public boolean equals(Object o) {
221- if (!(o instanceof VersionNumber))
220+ public boolean equals(Object other) {
221+ if (other == this)
222+ return true;
223+ if (!(other instanceof VersionNumber))
222224 return false;
223- VersionNumber that = (VersionNumber) o;
224- if (major != that.major || minor != that.minor || patch != that.patch)
225- return false;
226-
227- return major == that.major
228- && minor == that.minor
229- && patch == that.patch
230- && dsePatch == that.dsePatch
231- && (preReleases == null ? that.preReleases == null : Arrays.equals(preReleases, that.preReleases))
232- && Objects.equal(build, that.build);
225+ VersionNumber that = (VersionNumber) other;
226+ return this.major == that.major
227+ && this.minor == that.minor
228+ && this.patch == that.patch
229+ && this.dsePatch == that.dsePatch
230+ && (this.preReleases == null ? that.preReleases == null : Arrays.equals(this.preReleases, that.preReleases))
231+ && Objects.equal(this.build, that.build);
233232 }
234233
235234 @Override
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ConnectionException.java +2 −2
@@ -40,7 +40,7 @@
4040
4141 @Override
4242 public InetAddress getHost() {
43- return address.getAddress();
43+ return address == null ? null : address.getAddress();
4444 }
4545
4646 @Override
@@ -50,7 +50,7 @@
5050
5151 @Override
5252 public String getMessage() {
53- return String.format("[%s] %s", getHost(), getRawMessage());
53+ return address == null ? getRawMessage() : String.format("[%s] %s", address, getRawMessage());
5454 }
5555
5656 @Override
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +4 −2
@@ -97,8 +97,6 @@
9797 } else if (!dc.equals(localDc))
9898 notInLocalDC.add(String.format("%s (%s)", host.toString(), dc));
9999
100- if (!dc.equals(localDc)) notInLocalDC.add(String.format("%s (%s)", host.toString(), host.getDatacenter()));
101-
102100 CopyOnWriteArrayList<Host> prev = perDcLiveHosts.get(dc);
103101 if (prev == null)
104102 perDcLiveHosts.put(dc, new CopyOnWriteArrayList<Host>(Collections.singletonList(host)));
@@ -358,6 +356,10 @@
358356 * @return the policy.
359357 */
360358 public DCAwareRoundRobinPolicy build() {
359+ if (usedHostsPerRemoteDc == 0 && allowRemoteDCsForLocalConsistencyLevel) {
360+ logger.warn("Setting allowRemoteDCsForLocalConsistencyLevel has no effect if usedHostsPerRemoteDc = 0. "
361+ + "This setting will be ignored");
362+ }
361363 return new DCAwareRoundRobinPolicy(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, true);
362364 }
363365 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java +1 −0
@@ -69,6 +69,7 @@
6969
7070 @Override
7171 public void init(Cluster cluster) {
72+ childPolicy.init(cluster);
7273 queryOptions = cluster.getConfiguration().getQueryOptions();
7374 }
7475
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java +1 −1
@@ -150,7 +150,7 @@
150150
151151 @Override
152152 public void init(Cluster cluster) {
153- // nothing to do
153+ policy.init(cluster);
154154 }
155155
156156 @Override
modified driver-core/src/main/java/com/datastax/driver/core/policies/RoundRobinPolicy.java +1 −1
@@ -102,7 +102,7 @@
102102 hasLoggedLocalCLUse = true;
103103 logger.warn("Detected request at Consistency Level {} but the non-DC aware RoundRobinPolicy is in use. "
104104 + "It is strongly advised to use DCAwareRoundRobinPolicy if you have multiple DCs/use DC-aware consistency levels "
105- + "(note: this message will only be logged once)", statement.getConsistencyLevel());
105+ + "(note: this message will only be logged once)", cl);
106106 }
107107 }
108108
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +3 −0
@@ -84,4 +84,7 @@
8484 return new MaterializedViewMetadataAssert(view);
8585 }
8686
87+ public static VersionNumberAssert assertThat(VersionNumber actual) {
88+ return new VersionNumberAssert(actual);
89+ }
8790 }
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +18 −5
@@ -167,7 +167,7 @@
167167 }
168168
169169 if (isWindows()) {
170- CCM_COMMAND = "cmd /c ccm.py";
170+ CCM_COMMAND = "powershell.exe -ExecutionPolicy Unrestricted ccm.py";
171171 } else {
172172 CCM_COMMAND = "ccm";
173173 }
@@ -193,7 +193,7 @@
193193 *
194194 * @return <code>true</code> if the operating system is a Windows one, <code>false</code> otherwise.
195195 */
196- private static boolean isWindows() {
196+ public static boolean isWindows() {
197197
198198 String osName = System.getProperty("os.name");
199199 return osName != null && osName.startsWith("Windows");
@@ -386,7 +386,11 @@
386386 if (logger.isDebugEnabled())
387387 logger.debug("Starting: {} - free memory: {} MB", this, TestUtils.getFreeMemoryMB());
388388 try {
389- execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs);
389+ String cmd = CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs;
390+ if (isWindows() && this.version.compareTo(VersionNumber.parse("2.2.4")) >= 0) {
391+ cmd += " --quiet-windows";
392+ }
393+ execute(cmd);
390394 } catch (CCMException e) {
391395 logger.error("Could not start " + this, e);
392396 logger.error("CCM output:\n{}", e.getOut());
@@ -444,7 +448,11 @@
444448 public void start(int n) {
445449 logger.debug(String.format("Starting: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
446450 try {
447- execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs, n);
451+ String cmd = CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs;
452+ if (isWindows() && this.version.compareTo(VersionNumber.parse("2.2.4")) >= 0) {
453+ cmd += " --quiet-windows";
454+ }
455+ execute(cmd, n);
448456 } catch (CCMException e) {
449457 logger.error(String.format("Could not start node %s in %s", n, this), e);
450458 logger.error("CCM output:\n{}", e.getOut());
@@ -875,9 +883,14 @@
875883
876884 private String joinJvmArgs() {
877885 StringBuilder allJvmArgs = new StringBuilder("");
886+ String quote = isWindows() ? "\"" : "";
878887 for (String jvmArg : jvmArgs) {
879- allJvmArgs.append(" --jvm_arg=");
888+ // Windows requires jvm arguments to be quoted, while *nix requires unquoted.
889+ allJvmArgs.append(" ");
890+ allJvmArgs.append(quote);
891+ allJvmArgs.append("--jvm_arg=");
880892 allJvmArgs.append(randomizePorts(jvmArg));
893+ allJvmArgs.append(quote);
881894 }
882895 return allJvmArgs.toString();
883896 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +4 −4
@@ -42,7 +42,8 @@
4242 import static com.datastax.driver.core.Assertions.fail;
4343 import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS;
4444 import static com.datastax.driver.core.HostDistance.LOCAL;
45-import static com.datastax.driver.core.TestUtils.*;
45+import static com.datastax.driver.core.TestUtils.ipOfNode;
46+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
4647 import static org.mockito.Mockito.*;
4748
4849 public class ClusterInitTest {
@@ -107,7 +108,6 @@
107108 .withReconnectionPolicy(reconnectionPolicy)
108109 .withPoolingOptions(poolingOptions)
109110 .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
110- .withQueryOptions(nonDebouncingQueryOptions())
111111 .build();
112112 cluster.connect();
113113
@@ -228,7 +228,7 @@
228228 ScassandraCluster scassandraCluster = ScassandraCluster.builder()
229229 .withIpPrefix(TestUtils.IP_PREFIX)
230230 .withNodes(5)
231- // For node 2, report an older version which uses protocol v1.
231+ // For node 2, report an older version which uses protocol v1.
232232 .forcePeerInfo(1, 2, "release_version", "1.2.19")
233233 .build();
234234 Cluster cluster = Cluster.builder()
@@ -262,7 +262,7 @@
262262 PrimingClient.builder()
263263 .withHost(ipOfNode(1))
264264 .withPort(scassandra.getAdminPort())
265- .build();
265+ .build();
266266
267267 List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(5);
268268
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +39 −19
@@ -19,6 +19,7 @@
1919 import com.datastax.driver.core.exceptions.BusyConnectionException;
2020 import com.datastax.driver.core.exceptions.ConnectionException;
2121 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
22+import com.google.common.base.Predicate;
2223 import com.google.common.util.concurrent.*;
2324 import org.scassandra.cql.PrimitiveType;
2425 import org.scassandra.http.client.PrimingRequest;
@@ -33,6 +34,7 @@
3334 import java.util.concurrent.atomic.AtomicReference;
3435
3536 import static com.datastax.driver.core.Assertions.assertThat;
37+import static com.datastax.driver.core.ConditionChecker.check;
3638 import static com.google.common.collect.Lists.newArrayList;
3739 import static java.util.Collections.singletonList;
3840 import static java.util.concurrent.TimeUnit.SECONDS;
@@ -49,6 +51,22 @@
4951 cluster.close();
5052 }
5153
54+ /**
55+ * Ensure the given pool has the given size within 5 seconds.
56+ *
57+ * @param pool Pool to check.
58+ * @param expectedSize Expected size of pool.
59+ */
60+ private void assertPoolSize(HostConnectionPool pool, final int expectedSize) {
61+ check().before(5, TimeUnit.SECONDS)
62+ .that(pool, new Predicate<HostConnectionPool>() {
63+ @Override
64+ public boolean apply(HostConnectionPool input) {
65+ return input.connections.size() == expectedSize;
66+ }
67+ }).becomesTrue();
68+ }
69+
5270 /**
5371 * Sends 101 requests on pool, asserting that the connection used is in expectedConnections, except for the last request.
5472 */
@@ -157,7 +175,8 @@
157175 requests.addAll(fillConnectionToThreshold(pool, coreConnections));
158176
159177 // Allow time for new connection to be spawned.
160- verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
178+ verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
179+ assertPoolSize(pool, 2);
161180
162181 // Borrow more and ensure the connection returned is a non-core connection.
163182 for (int i = 0; i < 100; i++) {
@@ -203,8 +222,8 @@
203222 requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
204223
205224 // Reaching the threshold should have triggered the creation of an extra one
206- verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
207- assertThat(pool.connections).hasSize(2);
225+ verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
226+ assertPoolSize(pool, 2);
208227 } finally {
209228 completeRequests(requests);
210229 cluster.close();
@@ -231,8 +250,8 @@
231250
232251 requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
233252
234- verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
235- assertThat(pool.connections).hasSize(2);
253+ verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
254+ assertPoolSize(pool, 2);
236255 Connection connection2 = pool.connections.get(1);
237256
238257 assertThat(connection1.inFlight.get()).isEqualTo(101);
@@ -259,7 +278,8 @@
259278
260279 // Borrowing one more time should resurrect the trashed connection
261280 requests.addAll(sendRequests(1, pool));
262- verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
281+ verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
282+ assertPoolSize(pool, 2);
263283
264284 assertThat(pool.connections).containsExactly(connection2, connection1);
265285 assertThat(pool.trash).isEmpty();
@@ -291,9 +311,9 @@
291311
292312 requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
293313
294- verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
314+ verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
315+ assertPoolSize(pool, 2);
295316 reset(factory);
296- assertThat(pool.connections).hasSize(2);
297317 Connection connection2 = pool.connections.get(1);
298318
299319 assertThat(connection1.inFlight.get()).isEqualTo(101);
@@ -323,7 +343,8 @@
323343 // Fill the live connection to go over the threshold where a second one is needed
324344 requests.addAll(fillConnectionToThreshold(pool, singletonList(connection2)));
325345 assertThat(connection2.inFlight.get()).isEqualTo(101);
326- verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
346+ verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
347+ assertPoolSize(pool, 2);
327348
328349 // Borrow again to get the new connection
329350 MockRequest request = MockRequest.send(pool);
@@ -358,7 +379,7 @@
358379 // Fill core connection enough to trigger creation of another one
359380 requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
360381
361- verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
382+ verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
362383 assertThat(pool.connections).hasSize(2);
363384
364385 // Return enough times to get back under the threshold where one connection is enough
@@ -408,7 +429,7 @@
408429
409430 requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
410431
411- verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
432+ verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
412433 assertThat(pool.connections).hasSize(2);
413434
414435 // Grab the new non-core connection and replace it with a spy.
@@ -675,7 +696,7 @@
675696 }
676697
677698 // Pool should grow by 1.
678- verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
699+ verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
679700 assertThat(pool.connections).hasSize(2);
680701
681702 // Reset factory mock as we'll be checking for new open() invokes later.
@@ -710,12 +731,13 @@
710731
711732 // After some time the a connection should attempt to be opened (but will fail).
712733 verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
734+ assertPoolSize(pool, 1);
713735 assertThat(pool.connections).hasSize(1);
714736
715737 // Wait some reasonable amount of time for connection to reestablish then check pool size.
716738 Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
717739 // Reconnecting failed since listening was enabled.
718- assertThat(pool.connections).hasSize(1);
740+ assertPoolSize(pool, 1);
719741
720742 // Re enable listening then wait for reconnect.
721743 currentClient.enableListener();
@@ -792,8 +814,7 @@
792814 requests.add(MockRequest.send(pool));
793815 verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
794816 reset(factory);
795- Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
796- assertThat(pool.connections).hasSize(i);
817+ assertPoolSize(pool, i);
797818 }
798819 } finally {
799820 completeRequests(requests);
@@ -896,8 +917,7 @@
896917
897918 // Should create up to core connections.
898919 verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class));
899- Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
900- assertThat(pool.connections).hasSize(8);
920+ assertPoolSize(pool, 8);
901921 } finally {
902922 cluster.close();
903923 }
@@ -959,10 +979,10 @@
959979 }
960980
961981 /**
962- * <p/>
982+ * <p>
963983 * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
964984 * insertions are being executed, the number of opened connection is monitored.
965- * <p/>
985+ * <p>
966986 * If at anytime, the number of opened connections is negative, this test will fail.
967987 *
968988 * @jira_ticket JAVA-349
modified driver-core/src/test/java/com/datastax/driver/core/HostMetadataIntegrationTest.java +0 −2
@@ -24,7 +24,6 @@
2424 import static com.datastax.driver.core.Assertions.assertThat;
2525 import static com.datastax.driver.core.CCMAccess.Workload.solr;
2626 import static com.datastax.driver.core.CCMAccess.Workload.spark;
27-import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
2827 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
2928
3029 public class HostMetadataIntegrationTest {
@@ -58,7 +57,6 @@
5857 Cluster cluster = Cluster.builder()
5958 .addContactPoints(ccm.addressOfNode(1).getAddress())
6059 .withPort(ccm.getBinaryPort())
61- .withQueryOptions(nonDebouncingQueryOptions())
6260 .build();
6361 try {
6462 cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +7 −39
@@ -18,11 +18,7 @@
1818 import org.testng.annotations.BeforeMethod;
1919 import org.testng.annotations.Test;
2020
21-import java.util.Collection;
22-
2321 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
24-import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
25-import static com.google.common.collect.Lists.newArrayList;
2622 import static org.mockito.Mockito.*;
2723
2824 @CreateCCM(PER_METHOD)
@@ -31,21 +27,14 @@
3127
3228 private static final int DEBOUNCE_TIME = 2000;
3329
34- QueryOptions queryOptions;
35-
36- Cluster cluster2;
37-
38- Session session2;
30+ private Cluster cluster2;
3931
4032 // Control Connection to be spied.
4133 private ControlConnection controlConnection;
4234
43- // Keyspaces to drop after test completes.
44- private Collection<String> keyspaces = newArrayList();
45-
4635 @BeforeMethod(groups = "short")
4736 public void setup() {
48- queryOptions = new QueryOptions();
37+ QueryOptions queryOptions = new QueryOptions();
4938 queryOptions.setRefreshNodeListIntervalMillis(DEBOUNCE_TIME);
5039 queryOptions.setMaxPendingRefreshNodeListRequests(5);
5140 queryOptions.setRefreshSchemaIntervalMillis(0);
@@ -55,7 +44,8 @@
5544 .withPort(ccm().getBinaryPort())
5645 .withQueryOptions(queryOptions)
5746 .build());
58- session2 = cluster2.connect();
47+
48+ cluster2.init();
5949
6050 // Create a spy of the Cluster's control connection and replace it with the spy.
6151 controlConnection = spy(cluster2.manager.controlConnection);
@@ -63,23 +53,6 @@
6353 reset(controlConnection);
6454 }
6555
66- /**
67- * Ensures that when a keyspace is created that refresh node list request
68- * is debounced and processed within {@link QueryOptions#getRefreshSchemaIntervalMillis()}
69- * + {@link QueryOptions#getRefreshNodeListIntervalMillis()}.
70- *
71- * @jira_ticket JAVA-657
72- * @since 2.0.11
73- */
74- @Test(groups = "short")
75- public void should_debounce_refresh_when_keyspace_created() {
76- String keyspace = "sdrwkc";
77- session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
78- keyspaces.add(keyspace);
79-
80- verify(controlConnection, timeout(DEBOUNCE_TIME + queryOptions.getRefreshSchemaIntervalMillis())).refreshNodeListAndTokenMap();
81- }
82-
8356 /**
8457 * Ensures that when enough refreshNodeList requests have been received
8558 * to reach {@link QueryOptions#getMaxPendingRefreshNodeListRequests()} that a
@@ -90,16 +63,11 @@
9063 */
9164 @Test(groups = "short")
9265 public void should_refresh_when_max_pending_requests_reached() {
93- // Create keyspaces 5 times to cause
94- // refreshNodeListAndTokenMap to be called.
95- String prefix = "srwmprr";
9666 for (int i = 0; i < 5; i++) {
97- String keyspace = prefix + i;
98- session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
99- keyspaces.add(keyspace);
67+ cluster2.manager.submitNodeListRefresh();
10068 }
10169
102- // add a 1 second delay to account for executor submit.
103- verify(controlConnection, timeout(1000)).refreshNodeListAndTokenMap();
70+ // add delay to account for executor submit.
71+ verify(controlConnection, timeout(DEBOUNCE_TIME)).refreshNodeListAndTokenMap();
10472 }
10573 }
added driver-core/src/test/java/com/datastax/driver/core/ProtocolOptionsTest.java +41 −0
@@ -0,0 +1,41 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import org.testng.annotations.Test;
19+
20+import static com.datastax.driver.core.Assertions.assertThat;
21+
22+public class ProtocolOptionsTest extends CCMTestsSupport {
23+
24+ /**
25+ * @jira_ticket JAVA-1209
26+ */
27+ @Test(groups = "unit")
28+ public void getProtocolVersion_should_return_null_if_not_connected() {
29+ Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
30+ assertThat(cluster.getConfiguration().getProtocolOptions().getProtocolVersion()).isNull();
31+ }
32+
33+ /**
34+ * @jira_ticket JAVA-1209
35+ */
36+ @Test(groups = "short")
37+ public void getProtocolVersion_should_return_version() throws InterruptedException {
38+ ProtocolVersion version = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
39+ assertThat(version).isNotNull();
40+ }
41+}
modified driver-core/src/test/java/com/datastax/driver/core/ProtocolV1Test.java +8 −0
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
19+import org.testng.SkipException;
1920 import org.testng.annotations.Test;
2021
2122 import static com.datastax.driver.core.ProtocolVersion.V1;
@@ -33,6 +34,13 @@
3334 .withProtocolVersion(V1);
3435 }
3536
37+ @Override
38+ public void beforeTestClass(Object testInstance) throws Exception {
39+ if (CCMBridge.isWindows())
40+ throw new SkipException("C* 1.2 is not supported on Windows.");
41+ super.beforeTestClass(testInstance);
42+ }
43+
3644 /**
3745 * Validates that a simple query with no variables is correctly executed.
3846 * @jira_ticket JAVA-1132
modified driver-core/src/test/java/com/datastax/driver/core/ReadTimeoutTest.java +1 −1
@@ -55,7 +55,7 @@
5555
5656 @Test(groups = "short")
5757 public void should_use_statement_timeout_if_overridden() {
58- Statement statement = new SimpleStatement(query).setReadTimeoutMillis(200);
58+ Statement statement = new SimpleStatement(query).setReadTimeoutMillis(10000);
5959 session.execute(statement);
6060 }
6161
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +59 −67
@@ -44,7 +44,9 @@
4444 private static final String DROP_TABLE = "DROP TABLE %s.table1";
4545
4646 /**
47- * The maximum time that the test will wait to check that listeners have been notified
47+ * The maximum time that the test will wait to check that listeners have been notified.
48+ * This threshold is intentionally set to a very high value to allow CI tests
49+ * to pass.
4850 */
4951 private static final long NOTIF_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(1);
5052
@@ -89,7 +91,7 @@
8991 cluster2.init();
9092
9193 cluster1.register(listener1 = mock(SchemaChangeListener.class));
92- cluster1.register(listener2 = mock(SchemaChangeListener.class));
94+ cluster2.register(listener2 = mock(SchemaChangeListener.class));
9395 listeners = Lists.newArrayList(listener1, listener2);
9496
9597 schemaDisabledCluster.register(schemaDisabledListener = mock(SchemaChangeListener.class));
@@ -150,7 +152,6 @@
150152 .isInKeyspace(handleId(keyspace))
151153 .hasName("table1");
152154 }
153- refreshSchema();
154155 for (Metadata m : metadatas())
155156 assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull();
156157 }
@@ -166,7 +167,6 @@
166167 .isInKeyspace(handleId(keyspace))
167168 .hasName("table1");
168169 }
169- refreshSchema();
170170 for (Metadata m : metadatas())
171171 assertThat(m.getKeyspace(keyspace).getTable("table1")).hasNoColumn("j");
172172 assert added != null;
@@ -183,7 +183,6 @@
183183 .hasName("table1")
184184 .hasColumn("j");
185185 }
186- refreshSchema();
187186 for (Metadata m : metadatas())
188187 assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j");
189188 }
@@ -198,14 +197,12 @@
198197 .hasName("table1")
199198 .isInKeyspace(handleId(keyspace));
200199 }
201- refreshSchema();
202200 execute(DROP_TABLE, keyspace);
203201 for (SchemaChangeListener listener : listeners) {
204202 ArgumentCaptor<TableMetadata> removed = ArgumentCaptor.forClass(TableMetadata.class);
205203 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(removed.capture());
206204 assertThat(removed.getValue()).hasName("table1");
207205 }
208- refreshSchema();
209206 for (Metadata m : metadatas())
210207 assertThat(m.getKeyspace(keyspace).getTable("table1")).isNull();
211208 }
@@ -221,7 +218,6 @@
221218 assertThat((DataType) added.getValue())
222219 .isUserType(handleId(keyspace), "type1");
223220 }
224- refreshSchema();
225221 for (Metadata m : metadatas())
226222 assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNotNull();
227223 }
@@ -238,7 +234,6 @@
238234 assertThat(previous.getValue().getFieldNames()).doesNotContain("j");
239235 assertThat(current.getValue().getFieldNames()).contains("j");
240236 }
241- refreshSchema();
242237 for (Metadata m : metadatas())
243238 assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j")).isNotNull();
244239 }
@@ -254,7 +249,6 @@
254249 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeRemoved(removed.capture());
255250 assertThat((DataType) removed.getValue()).isUserType(handleId(keyspace), "type1");
256251 }
257- refreshSchema();
258252 for (Metadata m : metadatas())
259253 assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNull();
260254 }
@@ -263,7 +257,6 @@
263257 @CassandraVersion(major = 2.2)
264258 public void should_notify_of_function_creation(String keyspace) {
265259 session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
266-
267260 for (SchemaChangeListener listener : listeners) {
268261 ArgumentCaptor<FunctionMetadata> added = ArgumentCaptor.forClass(FunctionMetadata.class);
269262 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionAdded(added.capture());
@@ -271,7 +264,6 @@
271264 .isInKeyspace(handleId(keyspace))
272265 .hasSignature("\"ID\"(int)");
273266 }
274- refreshSchema();
275267 for (Metadata m : metadatas())
276268 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()))
277269 .isNotNull();
@@ -280,47 +272,44 @@
280272 @Test(groups = "short", dataProvider = "existingKeyspaceName")
281273 @CassandraVersion(major = 2.2)
282274 public void should_notify_of_function_update(String keyspace) {
283- session1.execute(String.format("CREATE TYPE IF NOT EXISTS %s.user (\"ID\" int, name text)", keyspace));
284- session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return user.getInt(\"ID\");'", keyspace));
285- refreshSchema();
286-
275+ session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
276+ for (SchemaChangeListener listener : listeners) {
277+ ArgumentCaptor<FunctionMetadata> added = ArgumentCaptor.forClass(FunctionMetadata.class);
278+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionAdded(added.capture());
279+ assertThat(added.getValue())
280+ .isInKeyspace(handleId(keyspace))
281+ .hasSignature("\"ID\"(int)");
282+ }
287283 for (Metadata m : metadatas())
288- assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")).getBody())
289- .isEqualTo("return user.getInt(\"ID\");");
290-
291- session1.execute(String.format("CREATE OR REPLACE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java "
292- + "AS 'return 1 + user.getInt(\"ID\");'", keyspace));
293-
284+ assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()))
285+ .isNotNull();
286+ session1.execute(String.format("CREATE OR REPLACE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i + 1;'", keyspace));
294287 for (SchemaChangeListener listener : listeners) {
295288 ArgumentCaptor<FunctionMetadata> current = ArgumentCaptor.forClass(FunctionMetadata.class);
296289 ArgumentCaptor<FunctionMetadata> previous = ArgumentCaptor.forClass(FunctionMetadata.class);
297290 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionChanged(current.capture(), previous.capture());
298- assertThat(previous.getValue()).hasBody("return user.getInt(\"ID\");");
299- assertThat(current.getValue()).hasBody("return 1 + user.getInt(\"ID\");");
291+ assertThat(previous.getValue()).hasBody("return i;");
292+ assertThat(current.getValue()).hasBody("return i + 1;");
300293 }
301- refreshSchema();
302294 for (Metadata m : metadatas())
303- assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")).getBody())
304- .isEqualTo("return 1 + user.getInt(\"ID\");");
295+ assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()).getBody())
296+ .isEqualTo("return i + 1;");
305297 }
306298
307299 @Test(groups = "short", dataProvider = "existingKeyspaceName")
308300 @CassandraVersion(major = 2.2)
309301 public void should_notify_of_function_drop(String keyspace) {
310- session1.execute(String.format("CREATE TYPE IF NOT EXISTS %s.user (\"ID\" int, name text)", keyspace));
311- session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return user.getInt(\"ID\");'", keyspace));
302+ session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
312303 session1.execute(String.format("DROP FUNCTION %s.\"ID\"", keyspace));
313-
314304 for (SchemaChangeListener listener : listeners) {
315305 ArgumentCaptor<FunctionMetadata> removed = ArgumentCaptor.forClass(FunctionMetadata.class);
316306 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionRemoved(removed.capture());
317307 assertThat(removed.getValue())
318308 .isInKeyspace(handleId(keyspace))
319- .hasSignature("\"ID\"(user)");
309+ .hasSignature("\"ID\"(int)");
320310 }
321- refreshSchema();
322311 for (Metadata m : metadatas())
323- assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")))
312+ assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()))
324313 .isNull();
325314 }
326315
@@ -330,7 +319,6 @@
330319 session1.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
331320 + " AS 'return s+v;'", keyspace));
332321 session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0;", keyspace));
333-
334322 for (SchemaChangeListener listener : listeners) {
335323 ArgumentCaptor<AggregateMetadata> added = ArgumentCaptor.forClass(AggregateMetadata.class);
336324 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateAdded(added.capture());
@@ -338,7 +326,6 @@
338326 .isInKeyspace(handleId(keyspace))
339327 .hasSignature("\"SUM\"(int)");
340328 }
341- refreshSchema();
342329 for (Metadata m : metadatas())
343330 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()))
344331 .isNotNull();
@@ -350,13 +337,17 @@
350337 session1.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
351338 + " AS 'return s+v;'", keyspace));
352339 session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
353- refreshSchema();
340+ for (SchemaChangeListener listener : listeners) {
341+ ArgumentCaptor<AggregateMetadata> added = ArgumentCaptor.forClass(AggregateMetadata.class);
342+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateAdded(added.capture());
343+ assertThat(added.getValue())
344+ .isInKeyspace(handleId(keyspace))
345+ .hasSignature("\"SUM\"(int)");
346+ }
354347 for (Metadata m : metadatas())
355348 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond())
356349 .isEqualTo(0);
357-
358350 session1.execute(String.format("CREATE OR REPLACE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 1", keyspace));
359-
360351 for (SchemaChangeListener listener : listeners) {
361352 ArgumentCaptor<AggregateMetadata> current = ArgumentCaptor.forClass(AggregateMetadata.class);
362353 ArgumentCaptor<AggregateMetadata> previous = ArgumentCaptor.forClass(AggregateMetadata.class);
@@ -364,7 +355,6 @@
364355 assertThat(previous.getValue()).hasInitCond(0);
365356 assertThat(current.getValue()).hasInitCond(1);
366357 }
367- refreshSchema();
368358 for (Metadata m : metadatas())
369359 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond())
370360 .isEqualTo(1);
@@ -377,7 +367,6 @@
377367 + " AS 'return s+v;'", keyspace));
378368 session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
379369 session1.execute(String.format("DROP AGGREGATE %s.\"SUM\"", keyspace));
380-
381370 for (SchemaChangeListener listener : listeners) {
382371 ArgumentCaptor<AggregateMetadata> removed = ArgumentCaptor.forClass(AggregateMetadata.class);
383372 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateRemoved(removed.capture());
@@ -385,8 +374,6 @@
385374 .isInKeyspace(handleId(keyspace))
386375 .hasSignature("\"SUM\"(int)");
387376 }
388-
389- refreshSchema();
390377 for (Metadata m : metadatas())
391378 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()))
392379 .isNull();
@@ -397,7 +384,12 @@
397384 public void should_notify_of_view_creation(String keyspace) {
398385 session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
399386 session1.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace));
400- refreshSchema();
387+ for (SchemaChangeListener listener : listeners) {
388+ ArgumentCaptor<MaterializedViewMetadata> removed = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
389+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onMaterializedViewAdded(removed.capture());
390+ assertThat(removed.getValue())
391+ .hasName("mv1");
392+ }
401393 for (Metadata m : metadatas())
402394 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1")).isNotNull();
403395 }
@@ -407,12 +399,26 @@
407399 public void should_notify_of_view_update(String keyspace) {
408400 session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
409401 session1.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c) WITH compaction = { 'class' : 'SizeTieredCompactionStrategy' }", keyspace, keyspace));
410- refreshSchema();
402+ for (SchemaChangeListener listener : listeners) {
403+ ArgumentCaptor<MaterializedViewMetadata> removed = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
404+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onMaterializedViewAdded(removed.capture());
405+ assertThat(removed.getValue())
406+ .hasName("mv1");
407+ assertThat(removed.getValue().getOptions().getCompaction().get("class"))
408+ .contains("SizeTieredCompactionStrategy");
409+ }
411410 for (Metadata m : metadatas())
412411 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1").getOptions().getCompaction().get("class")).contains("SizeTieredCompactionStrategy");
413-
414412 session1.execute(String.format("ALTER MATERIALIZED VIEW %s.mv1 WITH compaction = { 'class' : 'LeveledCompactionStrategy' }", keyspace));
415- refreshSchema();
413+ for (SchemaChangeListener listener : listeners) {
414+ ArgumentCaptor<MaterializedViewMetadata> current = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
415+ ArgumentCaptor<MaterializedViewMetadata> previous = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
416+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onMaterializedViewChanged(current.capture(), previous.capture());
417+ assertThat(previous.getValue().getOptions().getCompaction().get("class"))
418+ .contains("SizeTieredCompactionStrategy");
419+ assertThat(current.getValue().getOptions().getCompaction().get("class"))
420+ .contains("LeveledCompactionStrategy");
421+ }
416422 for (Metadata m : metadatas())
417423 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1").getOptions().getCompaction().get("class")).contains("LeveledCompactionStrategy");
418424 }
@@ -423,7 +429,12 @@
423429 session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
424430 session1.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace));
425431 session1.execute(String.format("DROP MATERIALIZED VIEW %s.mv1", keyspace));
426- refreshSchema();
432+ for (SchemaChangeListener listener : listeners) {
433+ ArgumentCaptor<MaterializedViewMetadata> removed = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
434+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onMaterializedViewRemoved(removed.capture());
435+ assertThat(removed.getValue())
436+ .hasName("mv1");
437+ }
427438 for (Metadata m : metadatas())
428439 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1")).isNull();
429440 }
@@ -436,7 +447,6 @@
436447 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
437448 assertThat(added.getValue()).hasName(handleId(keyspace));
438449 }
439- refreshSchema();
440450 for (Metadata m : metadatas())
441451 assertThat(m.getKeyspace(keyspace)).isNotNull();
442452 }
@@ -451,7 +461,6 @@
451461 assertThat(added.getValue()).hasName(handleId(keyspace));
452462 }
453463 assert added != null;
454- refreshSchema();
455464 for (Metadata m : metadatas())
456465 assertThat(m.getKeyspace(keyspace).isDurableWrites()).isTrue();
457466 execute(ALTER_KEYSPACE, keyspace);
@@ -466,7 +475,6 @@
466475 .hasName(handleId(keyspace))
467476 .isNotDurableWrites();
468477 }
469- refreshSchema();
470478 for (Metadata m : metadatas())
471479 assertThat(m.getKeyspace(keyspace)).isNotDurableWrites();
472480 }
@@ -474,14 +482,11 @@
474482 @Test(groups = "short", dataProvider = "newKeyspaceName")
475483 public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedException {
476484 execute(CREATE_KEYSPACE, keyspace);
477- ArgumentCaptor<KeyspaceMetadata> added = null;
478485 for (SchemaChangeListener listener : listeners) {
479- added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
486+ ArgumentCaptor<KeyspaceMetadata> added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
480487 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
481488 assertThat(added.getValue()).hasName(handleId(keyspace));
482489 }
483- assert added != null;
484- refreshSchema();
485490 for (Metadata m : metadatas())
486491 assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isNotEmpty();
487492 execute(CREATE_TABLE, keyspace); // to test table drop notifications
@@ -497,14 +502,12 @@
497502 assertThat(ks.getValue())
498503 .hasName(handleId(keyspace));
499504 }
500- refreshSchema();
501505 for (Metadata m : metadatas()) {
502506 assertThat(m.getKeyspace(keyspace)).isNull();
503507 assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isEmpty();
504508 }
505509 }
506510
507-
508511 /**
509512 * Ensures that calling {@link Metadata#newToken(String)} on a Cluster that has schema
510513 * metadata disabled will throw a {@link IllegalStateException}.
@@ -588,7 +591,6 @@
588591 schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
589592
590593 verify(schemaDisabledControlConnection, after(1000)).refreshSchema(null, null, null, null);
591- verify(schemaDisabledControlConnection).refreshNodeListAndTokenMap();
592594
593595 // Ensure that there is schema metadata.
594596 assertThat(schemaDisabledCluster.getMetadata().getKeyspace(keyspace)).isNotNull();
@@ -604,7 +606,6 @@
604606 reset(schemaDisabledControlConnection);
605607 schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
606608 verify(schemaDisabledControlConnection, after(1000).never()).refreshSchema(null, null, null, null);
607- verify(schemaDisabledControlConnection, never()).refreshNodeListAndTokenMap();
608609 } finally {
609610 // Reset listener mock to not count it's interactions in this test.
610611 reset(schemaDisabledListener);
@@ -643,13 +644,4 @@
643644 return Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata());
644645 }
645646
646- @SuppressWarnings("unchecked")
647- private void refreshSchema() {
648- Futures.getUnchecked(
649- Futures.successfulAsList(
650- cluster1.manager.submitSchemaRefresh(null, null, null, null),
651- cluster2.manager.submitSchemaRefresh(null, null, null, null)));
652- }
653-
654-
655647 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +4 −1
@@ -17,7 +17,6 @@
1717
1818 import org.mockito.ArgumentCaptor;
1919 import org.testng.SkipException;
20-import org.testng.annotations.AfterMethod;
2120 import org.testng.annotations.BeforeMethod;
2221 import org.testng.annotations.Test;
2322
@@ -249,6 +248,8 @@
249248 String prefix = TestUtils.generateIdentifier("ks_");
250249 for (int i = 0; i < 3; i++) {
251250 session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
251+ // check that the metadata is immediately up-to-date for the client that issued the DDL statement
252+ assertThat(cluster().getMetadata().getKeyspace(prefix + i)).isNotNull();
252253 }
253254
254255 verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class));
@@ -275,6 +276,8 @@
275276 String prefix = TestUtils.generateIdentifier("ks_");
276277 for (int i = 0; i < 5; i++) {
277278 session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
279+ // check that the metadata is immediately up-to-date for the client that issued the DDL statement
280+ assertThat(cluster().getMetadata().getKeyspace(prefix + i)).isNotNull();
278281 }
279282
280283 // Event should be processed immediately as we hit our threshold.
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +1 −1
@@ -34,7 +34,7 @@
3434
3535 SocketChannelMonitor channelMonitor;
3636
37- @Test(groups = "short")
37+ @Test(groups = "long")
3838 public void connectionLeakTest() throws Exception {
3939 // Checking for JAVA-342
4040 channelMonitor = new SocketChannelMonitor();
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +25 −12
@@ -20,7 +20,7 @@
2020 import org.mockito.Mockito;
2121 import org.testng.annotations.Test;
2222
23-import static org.assertj.core.api.Assertions.assertThat;
23+import static org.assertj.core.api.Assertions.fail;
2424 import static org.mockito.Mockito.times;
2525
2626 /**
@@ -41,8 +41,7 @@
4141 timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE);
4242 return Cluster.builder()
4343 .withTimestampGenerator(timestampGenerator)
44- .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
45- // Set an artificially low timeout to force speculative execution
44+ // Set an artificially low timeout to force speculative execution
4645 .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2));
4746 }
4847
@@ -58,16 +57,30 @@
5857 public void should_use_same_default_timestamp_for_all_executions() {
5958 Metrics.Errors errors = cluster().getMetrics().getErrorMetrics();
6059
61- Mockito.reset(timestampGenerator);
62- long execStartCount = errors.getSpeculativeExecutions().getCount();
63-
64- BatchStatement batch = new BatchStatement();
65- for (int k = 0; k < 1000; k++) {
66- batch.add(new SimpleStatement("insert into foo(k,v) values (?,1)", k));
60+ // The check is attempted up to 10 times to account for the small possibility that a
61+ // scheduled execution is not needed/exercised. Even though the policy is set up
62+ // to schedule an execution after 1ms, the timeout might not fire before the response is received.
63+ int tryCount = 0;
64+ int maxTries = 10;
65+ while (tryCount++ < maxTries) {
66+ Mockito.reset(timestampGenerator);
67+ long execStartCount = errors.getSpeculativeExecutions().getCount();
68+
69+ BatchStatement batch = new BatchStatement();
70+ for (int k = 0; k < 1000; k++) {
71+ batch.add(new SimpleStatement("insert into foo(k,v) values (?,1)", k).setIdempotent(true));
72+ }
73+ batch.setIdempotent(true);
74+ session().execute(batch);
75+
76+ if (errors.getSpeculativeExecutions().getCount() == execStartCount + 1) {
77+ Mockito.verify(timestampGenerator, times(1)).next();
78+ break;
79+ }
6780 }
68- session().execute(batch);
6981
70- assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount + 1);
71- Mockito.verify(timestampGenerator, times(1)).next();
82+ if (tryCount == maxTries) {
83+ fail("Observed no speculative executions in 10 attempts");
84+ }
7285 }
7386 }
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +1 −0
@@ -123,6 +123,7 @@
123123 ResultSet rs = session.execute(statement);
124124 Row row = rs.one();
125125
126+ assertThat(row).isNotNull();
126127 assertThat(row.getString("result")).isEqualTo("result1");
127128 assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount);
128129 assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(retriesStartCount + 1);
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +1 −2
@@ -61,8 +61,7 @@
6161 return Cluster.builder()
6262 .addContactPoints(getContactPoints().get(0))
6363 .withPort(ccm().getBinaryPort())
64- .withLoadBalancingPolicy(lbp)
65- .withQueryOptions(TestUtils.nonDebouncingQueryOptions());
64+ .withLoadBalancingPolicy(lbp);
6665 }
6766
6867 @Override
added driver-core/src/test/java/com/datastax/driver/core/VersionNumberAssert.java +64 −0
@@ -0,0 +1,64 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import org.assertj.core.api.AbstractComparableAssert;
19+
20+import static com.datastax.driver.core.Assertions.assertThat;
21+
22+public class VersionNumberAssert extends AbstractComparableAssert<VersionNumberAssert, VersionNumber> {
23+
24+ public VersionNumberAssert(VersionNumber actual) {
25+ super(actual, VersionNumberAssert.class);
26+ }
27+
28+ public VersionNumberAssert hasMajorMinorPatch(int major, int minor, int patch) {
29+ assertThat(actual.getMajor()).isEqualTo(major);
30+ assertThat(actual.getMinor()).isEqualTo(minor);
31+ assertThat(actual.getPatch()).isEqualTo(patch);
32+ return this;
33+ }
34+
35+ public VersionNumberAssert hasDsePatch(int dsePatch) {
36+ assertThat(actual.getDSEPatch()).isEqualTo(dsePatch);
37+ return this;
38+ }
39+
40+ public VersionNumberAssert hasPreReleaseLabels(String... labels) {
41+ assertThat(actual.getPreReleaseLabels()).containsExactly(labels);
42+ return this;
43+ }
44+
45+ public VersionNumberAssert hasNoPreReleaseLabels() {
46+ assertThat(actual.getPreReleaseLabels()).isNull();
47+ return this;
48+ }
49+
50+ public VersionNumberAssert hasBuildLabel(String label) {
51+ assertThat(actual.getBuildLabel()).isEqualTo(label);
52+ return this;
53+ }
54+
55+ public VersionNumberAssert hasNextStable(String version) {
56+ assertThat(actual.nextStable()).isEqualTo(VersionNumber.parse(version));
57+ return this;
58+ }
59+
60+ public VersionNumberAssert hasToString(String string) {
61+ assertThat(actual.toString()).isEqualTo(string);
62+ return this;
63+ }
64+}
modified driver-core/src/test/java/com/datastax/driver/core/VersionNumberTest.java +79 −30
@@ -17,39 +17,88 @@
1717
1818 import org.testng.annotations.Test;
1919
20-import static org.testng.Assert.assertEquals;
20+import static com.datastax.driver.core.Assertions.assertThat;
2121
2222 public class VersionNumberTest {
2323
2424 @Test(groups = "unit")
25- public void versionNumberTest() {
26-
27- String[] versions = new String[]{
28- "1.2.0",
29- "2.0.0",
30- "2.0.0-beta1",
31- "2.0.0-beta1-SNAPSHOT",
32- "2.0.0-beta1-SNAPSHOT+abc01",
33- "2.0.0.22" // DSE
34- };
35-
36- VersionNumber[] numbers = new VersionNumber[versions.length];
37- for (int i = 0; i < versions.length; i++)
38- numbers[i] = VersionNumber.parse(versions[i]);
39-
40- for (int i = 0; i < versions.length; i++)
41- assertEquals(numbers[i].toString(), versions[i]);
42-
43- assertEquals(numbers[0].compareTo(numbers[1]), -1);
44- assertEquals(numbers[1].compareTo(numbers[2]), 1);
45- assertEquals(numbers[2].compareTo(numbers[3]), -1);
46- assertEquals(numbers[3].compareTo(numbers[4]), 0);
47- assertEquals(numbers[1].compareTo(numbers[5]), -1);
48-
49- VersionNumber deb = VersionNumber.parse("2.0.0~beta1");
50- assertEquals(deb, numbers[2]);
51-
52- VersionNumber shorter = VersionNumber.parse("2.0");
53- assertEquals(shorter, numbers[1]);
25+ public void should_parse_release_version() {
26+ assertThat(VersionNumber.parse("1.2.19"))
27+ .hasMajorMinorPatch(1, 2, 19)
28+ .hasDsePatch(-1)
29+ .hasNoPreReleaseLabels()
30+ .hasBuildLabel(null)
31+ .hasNextStable("1.2.19")
32+ .hasToString("1.2.19");
33+ }
34+
35+ @Test(groups = "unit")
36+ public void should_parse_release_without_patch() {
37+ assertThat(VersionNumber.parse("1.2"))
38+ .hasMajorMinorPatch(1, 2, 0);
39+ }
40+
41+ @Test(groups = "unit")
42+ public void should_parse_pre_release_version() {
43+ assertThat(VersionNumber.parse("1.2.0-beta1-SNAPSHOT"))
44+ .hasMajorMinorPatch(1, 2, 0)
45+ .hasDsePatch(-1)
46+ .hasPreReleaseLabels("beta1", "SNAPSHOT")
47+ .hasBuildLabel(null)
48+ .hasToString("1.2.0-beta1-SNAPSHOT")
49+ .hasNextStable("1.2.0");
50+ }
51+
52+ @Test(groups = "unit")
53+ public void should_allow_tilde_as_first_pre_release_delimiter() {
54+ assertThat(VersionNumber.parse("1.2.0~beta1-SNAPSHOT"))
55+ .hasMajorMinorPatch(1, 2, 0)
56+ .hasDsePatch(-1)
57+ .hasPreReleaseLabels("beta1", "SNAPSHOT")
58+ .hasBuildLabel(null)
59+ .hasToString("1.2.0-beta1-SNAPSHOT")
60+ .hasNextStable("1.2.0");
61+ }
62+
63+ @Test(groups = "unit")
64+ public void should_parse_dse_patch() {
65+ assertThat(VersionNumber.parse("1.2.19.2-SNAPSHOT"))
66+ .hasMajorMinorPatch(1, 2, 19)
67+ .hasDsePatch(2)
68+ .hasToString("1.2.19.2-SNAPSHOT")
69+ .hasNextStable("1.2.19.2");
70+ }
71+
72+ @Test(groups = "unit")
73+ public void should_order_versions() {
74+ // by component
75+ assertOrder("1.2.0", "2.0.0", -1);
76+ assertOrder("2.0.0", "2.1.0", -1);
77+ assertOrder("2.0.1", "2.0.2", -1);
78+ assertOrder("2.0.1.1", "2.0.1.2", -1);
79+
80+ // shortened vs. longer version
81+ assertOrder("2.0", "2.0.0", 0);
82+ assertOrder("2.0", "2.0.1", -1);
83+
84+ // any DSE version is higher than no DSE version
85+ assertOrder("2.0.0", "2.0.0.0", -1);
86+ assertOrder("2.0.0", "2.0.0.1", -1);
87+
88+ // pre-release vs. release
89+ assertOrder("2.0.0-beta1", "2.0.0", -1);
90+ assertOrder("2.0.0-SNAPSHOT", "2.0.0", -1);
91+ assertOrder("2.0.0-beta1-SNAPSHOT", "2.0.0", -1);
92+
93+ // pre-release vs. pre-release
94+ assertOrder("2.0.0-a-b-c", "2.0.0-a-b-d", -1);
95+ assertOrder("2.0.0-a-b-c", "2.0.0-a-b-c-d", -1);
96+
97+ // build number ignored
98+ assertOrder("2.0.0+build01", "2.0.0+build02", 0);
99+ }
100+
101+ private void assertOrder(String version1, String version2, int expected) {
102+ assertThat(VersionNumber.parse(version1).compareTo(VersionNumber.parse(version2))).isEqualTo(expected);
54103 }
55104 }
added driver-core/src/test/java/com/datastax/driver/core/exceptions/ConnectionExceptionTest.java +58 −0
@@ -0,0 +1,58 @@
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.exceptions;
17+
18+import org.testng.annotations.Test;
19+
20+import java.net.InetSocketAddress;
21+
22+import static org.testng.Assert.assertEquals;
23+import static org.testng.Assert.assertNull;
24+
25+public class ConnectionExceptionTest {
26+
27+ /**
28+ * @jira_ticket JAVA-1139
29+ */
30+ @Test(groups = "unit")
31+ public void getHost_should_return_null_if_address_is_null() {
32+ assertNull(new ConnectionException(null, "Test message").getHost());
33+ }
34+
35+ /**
36+ * @jira_ticket JAVA-1139
37+ */
38+ @Test(groups = "unit")
39+ public void getMessage_should_return_message_if_address_is_null() {
40+ assertEquals(new ConnectionException(null, "Test message").getMessage(), "Test message");
41+ }
42+
43+ /**
44+ * @jira_ticket JAVA-1139
45+ */
46+ @Test(groups = "unit")
47+ public void getMessage_should_return_message_if_address_is_unresolved() {
48+ assertEquals(new ConnectionException(InetSocketAddress.createUnresolved("127.0.0.1", 9042), "Test message").getMessage(), "[127.0.0.1:9042] Test message");
49+ }
50+
51+ /**
52+ * @jira_ticket JAVA-1139
53+ */
54+ @Test(groups = "unit")
55+ public void getMessage_should_return_message_if_address_is_resolved() {
56+ assertEquals(new ConnectionException(new InetSocketAddress("127.0.0.1", 9042), "Test message").getMessage(), "[/127.0.0.1:9042] Test message");
57+ }
58+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +2 −2
@@ -88,7 +88,7 @@
8888 fail("expected an OperationTimedOutException");
8989 } catch (OperationTimedOutException e) {
9090 assertThat(e.getMessage()).isEqualTo(
91- String.format("[%s] Timed out waiting for server response", host1.getAddress())
91+ String.format("[%s] Timed out waiting for server response", host1.getSocketAddress())
9292 );
9393 }
9494 assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
@@ -131,7 +131,7 @@
131131 fail("expected a TransportException");
132132 } catch (TransportException e) {
133133 assertThat(e.getMessage()).isEqualTo(
134- String.format("[%s] Connection has been closed", host1.getAddress())
134+ String.format("[%s] Connection has been closed", host1.getSocketAddress())
135135 );
136136 }
137137 assertOnRequestErrorWasCalled(1, TransportException.class);
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +3 −3
@@ -187,9 +187,9 @@
187187 .hasOnlyElementsOfType(OperationTimedOutException.class)
188188 .extractingResultOf("getMessage")
189189 .containsOnlyOnce(
190- String.format("[%s] Timed out waiting for server response", host1.getAddress()),
191- String.format("[%s] Timed out waiting for server response", host2.getAddress()),
192- String.format("[%s] Timed out waiting for server response", host3.getAddress())
190+ String.format("[%s] Timed out waiting for server response", host1.getSocketAddress()),
191+ String.format("[%s] Timed out waiting for server response", host2.getSocketAddress()),
192+ String.format("[%s] Timed out waiting for server response", host3.getSocketAddress())
193193 );
194194 }
195195 assertOnRequestErrorWasCalled(3, OperationTimedOutException.class);
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +3 −3
@@ -383,9 +383,9 @@
383383 .hasOnlyElementsOfType(OperationTimedOutException.class)
384384 .extractingResultOf("getMessage")
385385 .containsOnlyOnce(
386- String.format("[%s] Timed out waiting for server response", host1.getAddress()),
387- String.format("[%s] Timed out waiting for server response", host2.getAddress()),
388- String.format("[%s] Timed out waiting for server response", host3.getAddress())
386+ String.format("[%s] Timed out waiting for server response", host1.getSocketAddress()),
387+ String.format("[%s] Timed out waiting for server response", host2.getSocketAddress()),
388+ String.format("[%s] Timed out waiting for server response", host3.getSocketAddress())
389389 );
390390 }
391391 assertOnRequestErrorWasCalled(3, OperationTimedOutException.class);
modified driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +2 −2
@@ -96,7 +96,7 @@
9696 Fail.fail("expected an OperationTimedOutException");
9797 } catch (OperationTimedOutException e) {
9898 assertThat(e.getMessage()).isEqualTo(
99- String.format("[%s] Timed out waiting for server response", host1.getAddress())
99+ String.format("[%s] Timed out waiting for server response", host1.getSocketAddress())
100100 );
101101 }
102102 assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
@@ -139,7 +139,7 @@
139139 Fail.fail("expected a TransportException");
140140 } catch (TransportException e) {
141141 assertThat(e.getMessage()).isEqualTo(
142- String.format("[%s] Connection has been closed", host1.getAddress())
142+ String.format("[%s] Connection has been closed", host1.getSocketAddress())
143143 );
144144 }
145145 assertOnRequestErrorWasCalled(1, TransportException.class);
modified driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java +21 −2
@@ -18,6 +18,7 @@
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.*;
2020 import org.assertj.core.api.Fail;
21+import org.mockito.Mockito;
2122 import org.scassandra.http.client.ClosedConnectionConfig;
2223 import org.scassandra.http.client.PrimingRequest;
2324 import org.scassandra.http.client.Result;
@@ -87,7 +88,7 @@
8788 fail("expected an OperationTimedOutException");
8889 } catch (OperationTimedOutException e) {
8990 assertThat(e.getMessage()).isEqualTo(
90- String.format("[%s] Timed out waiting for server response", host1.getAddress())
91+ String.format("[%s] Timed out waiting for server response", host1.getSocketAddress())
9192 );
9293 }
9394 assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
@@ -179,7 +180,7 @@
179180 Fail.fail("expected a TransportException");
180181 } catch (TransportException e) {
181182 assertThat(e.getMessage()).isEqualTo(
182- String.format("[%s] Connection has been closed", host1.getAddress())
183+ String.format("[%s] Connection has been closed", host1.getSocketAddress())
183184 );
184185 }
185186 assertOnRequestErrorWasCalled(1, TransportException.class);
@@ -218,6 +219,24 @@
218219 assertQueried(3, 1);
219220 }
220221
222+ @Test(groups = "short")
223+ public void should_call_init_method_on_inner_policy() {
224+ RetryPolicy innerPolicyMock = Mockito.mock(RetryPolicy.class);
225+
226+ new IdempotenceAwareRetryPolicy(innerPolicyMock).init(cluster);
227+
228+ Mockito.verify(innerPolicyMock).init(cluster);
229+ }
230+
231+ @Test(groups = "unit")
232+ public void should_call_close_method_on_inner_policy() {
233+ RetryPolicy innerPolicyMock = Mockito.mock(RetryPolicy.class);
234+
235+ new IdempotenceAwareRetryPolicy(innerPolicyMock).close();
236+
237+ Mockito.verify(innerPolicyMock).close();
238+ }
239+
221240
222241 /**
223242 * Retries everything on the next host.
modified driver-core/src/test/java/com/datastax/driver/core/policies/LoggingRetryPolicyIntegrationTest.java +20 −1
@@ -20,6 +20,7 @@
2020 import com.datastax.driver.core.exceptions.ServerError;
2121 import org.apache.log4j.Level;
2222 import org.apache.log4j.Logger;
23+import org.mockito.Mockito;
2324 import org.slf4j.helpers.MessageFormatter;
2425 import org.testng.annotations.AfterMethod;
2526 import org.testng.annotations.BeforeClass;
@@ -54,7 +55,7 @@
5455 setRetryPolicy(new LoggingRetryPolicy(new CustomRetryPolicy()));
5556 }
5657
57- @BeforeMethod(groups = {"short", "unit"})
58+ @BeforeMethod(groups = {"short"})
5859 public void storeDefaultCL() {
5960 defaultCL = cluster.getConfiguration().getQueryOptions().getConsistencyLevel();
6061 }
@@ -144,6 +145,24 @@
144145 assertThat(line.trim()).isEqualTo(expectedMessage(RETRYING_ON_REQUEST_ERROR, "next host", LOCAL_ONE, defaultCL, 0, new ServerError(host1.getSocketAddress(), "Server Error")));
145146 }
146147
148+ @Test(groups = "short")
149+ public void should_call_init_method_on_inner_policy() {
150+ RetryPolicy innerPolicyMock = Mockito.mock(RetryPolicy.class);
151+
152+ new LoggingRetryPolicy(innerPolicyMock).init(cluster);
153+
154+ Mockito.verify(innerPolicyMock).init(cluster);
155+ }
156+
157+ @Test(groups = "unit")
158+ public void should_call_close_method_on_inner_policy() {
159+ RetryPolicy innerPolicyMock = Mockito.mock(RetryPolicy.class);
160+
161+ new LoggingRetryPolicy(innerPolicyMock).close();
162+
163+ Mockito.verify(innerPolicyMock).close();
164+ }
165+
147166 private String expectedMessage(String template, Object... args) {
148167 return MessageFormatter.arrayFormat(template, args).getMessage();
149168 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +29 −11
@@ -16,7 +16,7 @@
1616 package com.datastax.driver.mapping;
1717
1818 import com.datastax.driver.core.ConsistencyLevel;
19-import com.datastax.driver.core.Metadata;
19+import com.datastax.driver.core.TableMetadata;
2020 import com.datastax.driver.core.TypeCodec;
2121 import com.datastax.driver.core.UserType;
2222 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
@@ -31,6 +31,8 @@
3131 import java.util.*;
3232 import java.util.concurrent.atomic.AtomicInteger;
3333
34+import static com.datastax.driver.core.Metadata.quote;
35+
3436 /**
3537 * Static metods that facilitates parsing class annotations into the corresponding {@link EntityMapper}.
3638 */
@@ -66,6 +68,10 @@
6668 }
6769
6870 EntityMapper<T> mapper = factory.create(entityClass, ksName, tableName, writeConsistency, readConsistency);
71+ TableMetadata tableMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getTable(tableName);
72+
73+ if (tableMetadata == null)
74+ throw new IllegalArgumentException(String.format("Table %s does not exist in keyspace %s", tableName, ksName));
6975
7076 List<Field> pks = new ArrayList<Field>();
7177 List<Field> ccs = new ArrayList<Field>();
@@ -106,18 +112,24 @@
106112 validateOrder(pks, "@PartitionKey");
107113 validateOrder(ccs, "@ClusteringColumn");
108114
109- mapper.addColumns(createColumnMappers(pks, factory, mapper.entityClass, mappingManager, columnCounter),
110- createColumnMappers(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
111- createColumnMappers(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
115+ mapper.addColumns(
116+ createColumnMappers(pks, factory, mapper.entityClass, mappingManager, columnCounter, tableMetadata, ksName, tableName),
117+ createColumnMappers(ccs, factory, mapper.entityClass, mappingManager, columnCounter, tableMetadata, ksName, tableName),
118+ createColumnMappers(rgs, factory, mapper.entityClass, mappingManager, columnCounter, tableMetadata, ksName, tableName));
112119 return mapper;
113120 }
114121
115- private static <T> List<ColumnMapper<T>> createColumnMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
122+ private static <T> List<ColumnMapper<T>> createColumnMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter, TableMetadata tableMetadata, String ksName, String tableName) {
116123 List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
117124 for (int i = 0; i < fields.size(); i++) {
118125 Field field = fields.get(i);
119126 int pos = position(field);
120- mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter));
127+ ColumnMapper<T> columnMapper = factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter);
128+ if (columnMapper.kind == ColumnMapper.Kind.COMPUTED || tableMetadata.getColumn(columnMapper.getColumnName()) != null)
129+ mappers.add(columnMapper);
130+ else
131+ throw new IllegalArgumentException(String.format("Column %s does not exist in table %s.%s",
132+ columnMapper.getColumnName(), ksName, tableName));
121133 }
122134 return mappers;
123135 }
@@ -126,7 +138,7 @@
126138 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
127139
128140 String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase();
129- String udtName = udt.caseSensitiveType() ? Metadata.quote(udt.name()) : udt.name().toLowerCase();
141+ String udtName = udt.caseSensitiveType() ? quote(udt.name()) : udt.name().toLowerCase();
130142
131143 if (Strings.isNullOrEmpty(udt.keyspace())) {
132144 ksName = mappingManager.getSession().getLoggedKeyspace();
@@ -139,6 +151,8 @@
139151 }
140152
141153 UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName);
154+ if (userType == null)
155+ throw new IllegalArgumentException(String.format("User type %s does not exist in keyspace %s", udtName, ksName));
142156
143157 List<Field> columns = new ArrayList<Field>();
144158
@@ -163,17 +177,21 @@
163177 break;
164178 }
165179 }
166- Map<String, ColumnMapper<T>> columnMappers = createFieldMappers(columns, factory, udtClass, mappingManager, null);
180+ Map<String, ColumnMapper<T>> columnMappers = createFieldMappers(columns, factory, udtClass, mappingManager, userType, ksName);
167181 return new MappedUDTCodec<T>(userType, udtClass, columnMappers, mappingManager);
168182 }
169183
170- private static <T> Map<String, ColumnMapper<T>> createFieldMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
184+ private static <T> Map<String, ColumnMapper<T>> createFieldMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, UserType userType, String ksName) {
171185 Map<String, ColumnMapper<T>> mappers = Maps.newHashMapWithExpectedSize(fields.size());
172186 for (int i = 0; i < fields.size(); i++) {
173187 Field field = fields.get(i);
174188 int pos = position(field);
175- ColumnMapper<T> mapper = factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter);
176- mappers.put(mapper.getColumnName(), mapper);
189+ ColumnMapper<T> mapper = factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, null);
190+ if (userType.contains(mapper.getColumnName()))
191+ mappers.put(mapper.getColumnName(), mapper);
192+ else
193+ throw new IllegalArgumentException(String.format("Field %s does not exist in type %s.%s",
194+ mapper.getColumnName(), ksName, userType.getTypeName()));
177195 }
178196 return mappers;
179197 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +4 −0
@@ -46,6 +46,10 @@
4646 }
4747 }
4848
49+ Class<T> getUdtClass() {
50+ return udtClass;
51+ }
52+
4953 @Override
5054 protected ByteBuffer serializeField(T source, String fieldName, ProtocolVersion protocolVersion) {
5155 // The parent class passes lowercase names unquoted, but in our internal map of mappers they are always quoted
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +9 −5
@@ -141,6 +141,10 @@
141141 return getPreparedQueryAsync(type, Collections.<ColumnMapper<?>>emptySet(), options);
142142 }
143143
144+ Class<T> getMappedClass() {
145+ return klass;
146+ }
147+
144148 /**
145149 * The {@code TableMetadata} for this mapper.
146150 *
@@ -921,7 +925,7 @@
921925
922926 static class Ttl extends Option {
923927
924- private int ttlValue;
928+ private final int ttlValue;
925929
926930 Ttl(int value) {
927931 super(Type.TTL);
@@ -957,7 +961,7 @@
957961
958962 static class Timestamp extends Option {
959963
960- private long tsValue;
964+ private final long tsValue;
961965
962966 Timestamp(long value) {
963967 super(Type.TIMESTAMP);
@@ -993,7 +997,7 @@
993997
994998 static class ConsistencyLevelOption extends Option {
995999
996- private ConsistencyLevel cl;
1000+ private final ConsistencyLevel cl;
9971001
9981002 ConsistencyLevelOption(ConsistencyLevel cl) {
9991003 super(Type.CL);
@@ -1029,7 +1033,7 @@
10291033
10301034 static class Tracing extends Option {
10311035
1032- private boolean tracing;
1036+ private final boolean tracing;
10331037
10341038 Tracing(boolean tracing) {
10351039 super(Type.TRACING);
@@ -1066,7 +1070,7 @@
10661070
10671071 static class SaveNullFields extends Option {
10681072
1069- private boolean saveNullFields;
1073+ private final boolean saveNullFields;
10701074
10711075 SaveNullFields(boolean saveNullFields) {
10721076 super(SAVE_NULL_FIELDS);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +78 −6
@@ -15,22 +15,22 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.ProtocolVersion;
19-import com.datastax.driver.core.Session;
20-import com.datastax.driver.core.TypeCodec;
18+import com.datastax.driver.core.*;
2119 import com.datastax.driver.mapping.annotations.Accessor;
2220 import com.datastax.driver.mapping.annotations.Table;
2321 import com.datastax.driver.mapping.annotations.UDT;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
2424
25-import java.util.Collections;
26-import java.util.HashMap;
27-import java.util.Map;
25+import java.util.*;
2826
2927 /**
3028 * Mapping manager from which to obtain entity mappers.
3129 */
3230 public class MappingManager {
3331
32+ private static final Logger LOGGER = LoggerFactory.getLogger(MappingManager.class);
33+
3434 private final Session session;
3535 final boolean isCassandraV1;
3636
@@ -74,6 +74,78 @@
7474 // which nodes might join the cluster later.
7575 // At least if protocol >=2 we know there won't be any 1.2 nodes ever.
7676 this.isCassandraV1 = (protocolVersion == ProtocolVersion.V1);
77+ session.getCluster().register(new SchemaChangeListenerBase() {
78+
79+ @Override
80+ public void onTableRemoved(TableMetadata table) {
81+ synchronized (mappers) {
82+ Iterator<Mapper<?>> it = mappers.values().iterator();
83+ while (it.hasNext()) {
84+ Mapper<?> mapper = it.next();
85+ if (mapper.getTableMetadata().equals(table)) {
86+ LOGGER.error("Table {} has been removed; existing mappers for @Entity annotated {} will not work anymore", table.getName(), mapper.getMappedClass());
87+ it.remove();
88+ }
89+ }
90+ }
91+ }
92+
93+ @Override
94+ public void onTableChanged(TableMetadata current, TableMetadata previous) {
95+ synchronized (mappers) {
96+ Iterator<Mapper<?>> it = mappers.values().iterator();
97+ while (it.hasNext()) {
98+ Mapper<?> mapper = it.next();
99+ if (mapper.getTableMetadata().equals(previous)) {
100+ LOGGER.warn("Table {} has been altered; existing mappers for @Entity annotated {} might not work properly anymore",
101+ previous.getName(), mapper.getMappedClass());
102+ it.remove();
103+ }
104+ }
105+ }
106+ }
107+
108+ @Override
109+ public void onUserTypeRemoved(UserType type) {
110+ synchronized (udtCodecs) {
111+ Iterator<MappedUDTCodec<?>> it = udtCodecs.values().iterator();
112+ while (it.hasNext()) {
113+ MappedUDTCodec<?> codec = it.next();
114+ if (type.equals(codec.getCqlType())) {
115+ LOGGER.error("User type {} has been removed; existing mappers for @UDT annotated {} will not work anymore",
116+ type, codec.getUdtClass());
117+ it.remove();
118+ }
119+ }
120+ }
121+ }
122+
123+ @Override
124+ public void onUserTypeChanged(UserType current, UserType previous) {
125+ synchronized (udtCodecs) {
126+ Set<Class<?>> udtClasses = new HashSet<Class<?>>();
127+ Iterator<MappedUDTCodec<?>> it = udtCodecs.values().iterator();
128+ while (it.hasNext()) {
129+ MappedUDTCodec<?> codec = it.next();
130+ if (previous.equals(codec.getCqlType())) {
131+ LOGGER.warn("User type {} has been altered; existing mappers for @UDT annotated {} might not work properly anymore",
132+ previous, codec.getUdtClass());
133+ udtClasses.add(codec.getUdtClass());
134+ it.remove();
135+ }
136+ }
137+ for (Class<?> udtClass : udtClasses) {
138+ // try to register an updated version of the previous codec
139+ try {
140+ getUDTCodec(udtClass);
141+ } catch (Exception e) {
142+ LOGGER.error("Could not update mapping for @UDT annotated " + udtClass, e);
143+ }
144+ }
145+ }
146+ }
147+
148+ });
77149 }
78150
79151 /**
deleted driver-mapping/src/test/java/com/datastax/driver/core/CoreHooks.java +0 −25
@@ -1,25 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.util.Collections;
19-
20-/**
21- * Provides access to package-private members of the core module.
22- */
23-public class CoreHooks {
24- public static UserType MOCK_USER_TYPE = new UserType("mockKs", "mockUDT", Collections.<UserType.Field>emptyList(), TestUtils.getDesiredProtocolVersion(), new CodecRegistry());
25-}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAsyncTest.java +1 −1
@@ -71,7 +71,7 @@
7171 // create a second cluster to perform everything asynchronously,
7272 // including session initialization
7373 Cluster cluster2 = register(
74- createClusterBuilderNoDebouncing()
74+ createClusterBuilder()
7575 .addContactPoints(getContactPoints())
7676 .withPort(ccm().getBinaryPort())
7777 .build());
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCompositeKeyTest.java +1 −1
@@ -32,7 +32,7 @@
3232 }
3333
3434 @SuppressWarnings("unused")
35- @Table(keyspace = "ks", name = "test_table")
35+ @Table(name = "test_table")
3636 public static class TestTable {
3737 @PartitionKey(0)
3838 private int pk1;
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +3 −14
@@ -17,7 +17,6 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.CodecNotFoundException;
20-import com.datastax.driver.core.exceptions.InvalidQueryException;
2120 import com.datastax.driver.core.utils.CassandraVersion;
2221 import com.datastax.driver.mapping.annotations.*;
2322 import org.testng.SkipException;
@@ -26,7 +25,6 @@
2625
2726 import static com.datastax.driver.core.Assertions.assertThat;
2827 import static com.datastax.driver.core.ProtocolVersion.V1;
29-import static org.assertj.core.api.Assertions.fail;
3028
3129 /**
3230 * Tests to ensure validity of {@link com.datastax.driver.mapping.annotations.Computed}
@@ -54,7 +52,7 @@
5452 userMapper = mappingManager.mapper(User.class);
5553 }
5654
57- @Test(groups = "short", expectedExceptions = {UnsupportedOperationException.class})
55+ @Test(groups = "short", expectedExceptions = UnsupportedOperationException.class)
5856 void should_get_unsupported_operation_exception_on_v1() {
5957 if (protocolVersion.compareTo(V1) > 0)
6058 throw new SkipException("Skipped when protocol version > V1");
@@ -129,19 +127,10 @@
129127 User_WrongComputedType user = mapper.get("testlogin");
130128 }
131129
132- @Test(groups = "short")
130+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
133131 @CassandraVersion(major = 2.0)
134132 void should_fail_if_computed_field_marked_with_column_annotation() {
135- Mapper<User_WrongAnnotationForComputed> mapper = mappingManager.mapper(User_WrongAnnotationForComputed.class);
136- try {
137- mapper.save(new User_WrongAnnotationForComputed("test", "foo"));
138- fail("Expected an InvalidQueryException");
139- } catch (InvalidQueryException e) {/*expected*/}
140-
141- try {
142- User_WrongAnnotationForComputed saved = mapper.get(42);
143- fail("Expected an InvalidQueryException");
144- } catch (InvalidQueryException e) {/*expected*/}
133+ mappingManager.mapper(User_WrongAnnotationForComputed.class);
145134 }
146135
147136 @Table(name = "user")
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +69 −0
@@ -503,4 +503,73 @@
503503 assertThat(saveQuery.isIdempotent()).isTrue();
504504 }
505505
506+
507+ @Table(name = "users")
508+ public static class UserUnknownColumn {
509+
510+ @PartitionKey
511+ @Column(name = "user_id")
512+ private UUID userId;
513+
514+ @Column(name = "middle_name")
515+ private String middleName;
516+
517+ public UserUnknownColumn() {
518+ }
519+
520+ public UUID getUserId() {
521+ return userId;
522+ }
523+
524+ public void setUserId(UUID userId) {
525+ this.userId = userId;
526+ }
527+
528+ public String getMiddleName() {
529+ return middleName;
530+ }
531+
532+ public void setMiddleName(String middleName) {
533+ this.middleName = middleName;
534+ }
535+ }
536+
537+ /**
538+ * Ensures that when attempting to create a {@link Mapper} from a class that has a field for a
539+ * column that doesn't exist that an {@link IllegalArgumentException} is thrown.
540+ *
541+ * @jira_ticket JAVA-1126
542+ * @test_category object_mapper
543+ */
544+ @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
545+ public void should_fail_to_create_mapper_if_class_has_column_not_in_table() {
546+ MappingManager manager = new MappingManager(session());
547+ manager.mapper(UserUnknownColumn.class);
548+ }
549+
550+ @Table(name = "nonexistent")
551+ public static class NonExistentTable {
552+ public String name;
553+
554+ public void setName(String name) {
555+ this.name = name;
556+ }
557+
558+ public String getName() {
559+ return this.name;
560+ }
561+ }
562+
563+ /**
564+ * Ensures that when attempting to create a {@link Mapper} from a class that has a {@link Table} annotation with
565+ * a name that doesn't exist in the current keyspace that an {@link IllegalArgumentException} is thrown.
566+ *
567+ * @jira_ticket JAVA-1126
568+ * @test_category object_mapper
569+ */
570+ @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
571+ public void should_fail_to_create_mapper_if_table_does_not_exist() {
572+ MappingManager manager = new MappingManager(session());
573+ manager.mapper(NonExistentTable.class);
574+ }
506575 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +363 −6
@@ -17,34 +17,39 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.CodecNotFoundException;
20+import com.datastax.driver.core.exceptions.InvalidQueryException;
2021 import com.datastax.driver.core.utils.CassandraVersion;
2122 import com.datastax.driver.core.utils.UUIDs;
2223 import com.datastax.driver.mapping.annotations.*;
2324 import com.google.common.base.Objects;
2425 import com.google.common.collect.Maps;
2526 import org.assertj.core.data.MapEntry;
27+import org.testng.annotations.AfterMethod;
2628 import org.testng.annotations.BeforeMethod;
2729 import org.testng.annotations.Test;
2830
2931 import java.util.*;
3032
33+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
3134 import static org.assertj.core.api.Assertions.assertThat;
3235 import static org.assertj.core.api.Assertions.fail;
3336 import static org.testng.Assert.*;
3437
35-@SuppressWarnings("unused")
38+@SuppressWarnings({"unused", "WeakerAccess"})
3639 @CassandraVersion(major = 2.1)
40+@CreateCCM(PER_METHOD)
3741 public class MapperUDTTest extends CCMTestsSupport {
3842
39- @Override
40- public void onTestContextInitialized() {
43+ @BeforeMethod(groups = "short")
44+ public void createObjects() {
4145 execute("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)",
4246 "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
4347 }
4448
45- @BeforeMethod(groups = "short")
46- public void clean() {
47- session().execute("TRUNCATE users");
49+ @AfterMethod(groups = "short")
50+ public void deleteObjects() {
51+ execute("DROP TABLE IF EXISTS users",
52+ "DROP TYPE IF EXISTS address");
4853 }
4954
5055 @Table(name = "users",
@@ -371,4 +376,356 @@
371376 Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class);
372377 assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress));
373378 }
379+
380+ /**
381+ * Ensures that if a table is altered after a {@link Mapper} is created that it continues to work as long as
382+ * the change is compatible. A new column is added to the table in this case, which is a compatible change.
383+ * <p>
384+ * It also ensures that after the change is made that requesting a new {@link Mapper} returns a different instance
385+ * instead of the existing one.
386+ *
387+ * @jira_ticket JAVA-1126
388+ * @test_category object_mapper
389+ */
390+ @Test(groups = "short")
391+ public void should_work_normally_when_when_table_is_altered_but_remains_compatible() {
392+ MappingManager manager = new MappingManager(session());
393+ User expected = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
394+ Mapper<User> m = manager.mapper(User.class);
395+ Mapper<User> m1 = manager.mapper(User.class);
396+ assertThat(m1).isSameAs(m);
397+ session().execute("ALTER TABLE users ADD foo text");
398+ m.save(expected);
399+ User retrieved = m.get(expected.getUserId());
400+ assertThat(retrieved).isEqualTo(expected);
401+
402+ // Mapper should be recreated since table changed.
403+ Mapper<User> m2 = manager.mapper(User.class);
404+ assertThat(m2).isNotSameAs(m);
405+ }
406+
407+ /**
408+ * Ensures that if a UDT is altered after a {@link Mapper} is created that has a UDT that it continues to work as
409+ * long as the change is compatible. A new field is added to the table in this case, which is a compatible change.
410+ * <p>
411+ * It also ensures that after the change is made that requesting a new {@link TypeCodec} for that UDT and a new
412+ * {@link Mapper} for a table using that UDT returns different instances instead of the existing ones.
413+ *
414+ * @jira_ticket JAVA-1126
415+ * @test_category object_mapper
416+ */
417+ @Test(groups = "short")
418+ public void should_work_normally_when_udt_is_altered_but_remains_compatible() {
419+ MappingManager manager = new MappingManager(session());
420+ User expected = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
421+ Mapper<User> m = manager.mapper(User.class);
422+ TypeCodec c = manager.udtCodec(Address.class);
423+ TypeCodec c1 = manager.udtCodec(Address.class);
424+ assertThat(c1).isSameAs(c);
425+ session().execute("ALTER TYPE address ADD foo text");
426+ m.save(expected);
427+ User retrieved = m.get(expected.getUserId());
428+ assertThat(retrieved).isEqualTo(expected);
429+
430+ // Codec should be recreated when requested since UDT and thus the table changed.
431+ Mapper m2 = manager.mapper(User.class);
432+ assertThat(m2).isNotSameAs(m);
433+
434+ // Codec should be recreated when requested since UDT changed.
435+ TypeCodec c2 = manager.udtCodec(Address.class);
436+ assertThat(c2).isNotSameAs(c);
437+ }
438+
439+ /**
440+ * Ensures that if a table is dropped after a {@link Mapper} is created that the {@link Mapper} can no longer
441+ * successfully make queries and that attempting to create a new {@link Mapper} throws an
442+ * {@link IllegalArgumentException}.
443+ * <p>
444+ * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
445+ * one cannot be created as the table has been dropped.
446+ *
447+ * @jira_ticket JAVA-1126
448+ * @test_category object_mapper
449+ */
450+ @Test(groups = "short")
451+ public void should_throw_error_when_table_is_dropped() {
452+ User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
453+ MappingManager manager = new MappingManager(session());
454+ Mapper<User> mapper = manager.mapper(User.class);
455+ session().execute("DROP TABLE users");
456+ // usage of stale mapper
457+ try {
458+ mapper.save(user);
459+ fail("Expected InvalidQueryException");
460+ } catch (InvalidQueryException e) {
461+ assertThat(e.getMessage()).contains("unconfigured", "users");
462+ }
463+ try {
464+ mapper.get(user.getUserId());
465+ fail("Expected InvalidQueryException");
466+ } catch (InvalidQueryException e) {
467+ assertThat(e.getMessage()).contains("unconfigured", "users");
468+ }
469+ // trying to use a new mapper
470+ try {
471+ manager.mapper(User.class);
472+ fail("Expected IllegalArgumentException");
473+ } catch (IllegalArgumentException e) {
474+ assertThat(e.getMessage()).isEqualTo("Table users does not exist in keyspace " + keyspace);
475+ }
476+ }
477+
478+ /**
479+ * Ensures that if a table is altered after a {@link Mapper} is created that it no longer continues to work if
480+ * the change is not compatible. A column is dropped from the table in this case, which is an incompatible change.
481+ * <p>
482+ * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
483+ * one cannot be created as a declared column is missing from the schema but is present in the class definition.
484+ *
485+ * @jira_ticket JAVA-1126
486+ * @test_category object_mapper
487+ */
488+ @Test(groups = "short")
489+ public void should_throw_error_when_table_is_altered_and_is_not_compatible_anymore() {
490+ User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
491+ MappingManager manager = new MappingManager(session());
492+ Mapper<User> mapper = manager.mapper(User.class);
493+ session().execute("ALTER TABLE users DROP mainaddress");
494+ // usage of stale mapper
495+ try {
496+ mapper.save(user);
497+ fail("Expected InvalidQueryException");
498+ } catch (InvalidQueryException e) {
499+ assertThat(e.getMessage()).isEqualTo("Unknown identifier mainaddress");
500+ }
501+ try {
502+ mapper.get(user.getUserId());
503+ fail("Expected InvalidQueryException");
504+ } catch (InvalidQueryException e) {
505+ assertThat(e.getMessage()).isEqualTo("Undefined name mainaddress in selection clause");
506+ }
507+ // trying to use a new mapper
508+ try {
509+ manager.mapper(User.class);
510+ fail("Expected IllegalArgumentException");
511+ } catch (IllegalArgumentException e) {
512+ assertThat(e.getMessage()).isEqualTo(String.format("Column \"mainaddress\" does not exist in table %s.users", keyspace));
513+ }
514+ }
515+
516+ /**
517+ * Ensures that if a UDT is altered after a {@link Mapper} is created that it no longer continues to work if
518+ * the change made to the UDT is not compatible. A field is renamed in the UDT in this case, which is not a
519+ * compatible change.
520+ * <p>
521+ * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
522+ * one cannot be created as a declared field is missing from the schema but is present in the class definition.
523+ * <p>
524+ * Also verifies that a {@link TypeCodec} cannot be requested for the UDT as well.
525+ *
526+ * @jira_ticket JAVA-1126
527+ * @test_category object_mapper
528+ */
529+ @Test(groups = "short")
530+ public void should_throw_error_when_udt_is_altered_and_is_not_compatible_anymore() {
531+ User user = new User("Paul", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
532+ MappingManager manager = new MappingManager(session());
533+ Mapper<User> mapper = manager.mapper(User.class);
534+ session().execute("ALTER TYPE address RENAME \"ZIP_code\" to zip_code");
535+ // usage of stale mapper
536+ try {
537+ mapper.save(user);
538+ fail("Expected CodecNotFoundException");
539+ } catch (CodecNotFoundException e) {
540+ // ok, codec could not be created
541+ }
542+ // insert manually to be able to test retrieval
543+ session().execute("INSERT INTO users (user_id, name, mainaddress) VALUES (?, 'Paul', { street : '12 4th Street', zip_code : 12345 })", user.getUserId());
544+ try {
545+ mapper.get(user.getUserId());
546+ fail("Expected CodecNotFoundException");
547+ } catch (CodecNotFoundException e) {
548+ // ok, codec could not be created
549+ }
550+ // trying to use a new mapper
551+ try {
552+ manager.mapper(User.class);
553+ fail("Expected IllegalArgumentException");
554+ } catch (IllegalArgumentException e) {
555+ assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type %s.address", keyspace));
556+ }
557+ try {
558+ manager.udtCodec(Address.class);
559+ fail("Expected IllegalArgumentException");
560+ } catch (IllegalArgumentException e) {
561+ assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type %s.address", keyspace));
562+ }
563+ }
564+
565+ @UDT(name = "address")
566+ public static class AddressUnknownField {
567+
568+ private String city;
569+
570+ private String street;
571+
572+ @Field(name = "ZIP_code", caseSensitive = true)
573+ private int zipCode;
574+
575+ private Set<String> phones;
576+
577+ public String province;
578+
579+ public AddressUnknownField() {
580+ }
581+
582+ public String getStreet() {
583+ return street;
584+ }
585+
586+ public void setStreet(String street) {
587+ this.street = street;
588+ }
589+
590+ public String getCity() {
591+ return city;
592+ }
593+
594+ public void setCity(String city) {
595+ this.city = city;
596+ }
597+
598+ public int getZipCode() {
599+ return zipCode;
600+ }
601+
602+ public void setZipCode(int zipCode) {
603+ this.zipCode = zipCode;
604+ }
605+
606+ public Set<String> getPhones() {
607+ return phones;
608+ }
609+
610+ public void setPhones(Set<String> phones) {
611+ this.phones = phones;
612+ }
613+
614+ public String getProvince() {
615+ return province;
616+ }
617+
618+ public void setProvince(String province) {
619+ this.province = province;
620+ }
621+ }
622+
623+
624+ /**
625+ * Ensures that when attempting to create a {@link TypeCodec} from a class that has a field that does not exist in
626+ * the UDT that an {@link IllegalArgumentException} is thrown.
627+ *
628+ * @jira_ticket JAVA-1126
629+ * @test_category object_mapper
630+ */
631+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
632+ public void should_fail_to_create_codec_if_class_has_field_not_in_udt() {
633+ MappingManager manager = new MappingManager(session());
634+ manager.getUDTCodec(AddressUnknownField.class);
635+ }
636+
637+ @UDT(name = "nonexistent")
638+ public static class NonExistentUDT {
639+ public String name;
640+
641+ public void setName(String name) {
642+ this.name = name;
643+ }
644+
645+ public String getName() {
646+ return this.name;
647+ }
648+ }
649+
650+ /**
651+ * Ensures that when attempting to create a {@link TypeCodec} from a class that has a {@link UDT} annotation with
652+ * a name that doesn't exist in the current keyspace that an {@link IllegalArgumentException} is thrown.
653+ *
654+ * @jira_ticket JAVA-1126
655+ * @test_category object_mapper
656+ */
657+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
658+ public void should_fail_to_create_codec_if_udt_does_not_exist() {
659+ MappingManager manager = new MappingManager(session());
660+ manager.getUDTCodec(NonExistentUDT.class);
661+ }
662+
663+ @Table(name = "users")
664+ public static class UserWithAddressUnknownField {
665+ @PartitionKey
666+ @Column(name = "user_id")
667+ private UUID userId;
668+
669+ private String name;
670+
671+ @Frozen
672+ private AddressUnknownField mainAddress;
673+
674+ @Column(name = "other_addresses")
675+ @FrozenValue
676+ private Map<String, Address> otherAddresses = Maps.newHashMap();
677+
678+ public UserWithAddressUnknownField() {
679+ }
680+
681+ public UUID getUserId() {
682+ return userId;
683+ }
684+
685+ public void setUserId(UUID userId) {
686+ this.userId = userId;
687+ }
688+
689+ public String getName() {
690+ return name;
691+ }
692+
693+ public void setName(String name) {
694+ this.name = name;
695+ }
696+
697+ public AddressUnknownField getMainAddress() {
698+ return mainAddress;
699+ }
700+
701+ public void setMainAddress(AddressUnknownField address) {
702+ this.mainAddress = address;
703+ }
704+
705+ public Map<String, Address> getOtherAddresses() {
706+ return otherAddresses;
707+ }
708+
709+ public void setOtherAddresses(Map<String, Address> otherAddresses) {
710+ this.otherAddresses = otherAddresses;
711+ }
712+
713+ public void addOtherAddress(String name, Address address) {
714+ this.otherAddresses.put(name, address);
715+ }
716+ }
717+
718+ /**
719+ * Ensures that when attempting to create a {@link Mapper} from a class that has a field that is a class mapping to
720+ * a user type that has a field that does not exist in that UDT that an {@link IllegalArgumentException} is thrown.
721+ *
722+ * @jira_ticket JAVA-1126
723+ * @test_category object_mapper
724+ */
725+ @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
726+ public void should_fail_to_create_mapper_if_class_has_udt_field_class_that_has_field_not_in_udt() {
727+ MappingManager manager = new MappingManager(session());
728+ manager.mapper(UserWithAddressUnknownField.class);
729+ }
730+
374731 }
modified driver-tests/osgi/pom.xml +17 −1
@@ -34,6 +34,7 @@
3434 <felix.version>4.6.0</felix.version>
3535 <!-- more recent version require JDK7+ -->
3636 <pax-exam.version>3.6.0</pax-exam.version>
37+ <url.version>2.4.0</url.version>
3738 <logback.version>1.1.3</logback.version>
3839 <test.groups>none</test.groups>
3940 <!--
@@ -71,6 +72,12 @@
7172 <version>${felix.version}</version>
7273 </dependency>
7374
75+ <dependency>
76+ <groupId>org.slf4j</groupId>
77+ <artifactId>slf4j-api</artifactId>
78+ <version>1.7.5</version>
79+ </dependency>
80+
7481 <dependency>
7582 <groupId>com.datastax.cassandra</groupId>
7683 <artifactId>cassandra-driver-core</artifactId>
@@ -95,7 +102,7 @@
95102
96103 <dependency>
97104 <groupId>org.ops4j.pax.exam</groupId>
98- <artifactId>pax-exam-container-native</artifactId>
105+ <artifactId>pax-exam-container-forked</artifactId>
99106 <version>${pax-exam.version}</version>
100107 <scope>test</scope>
101108 </dependency>
@@ -107,6 +114,13 @@
107114 <scope>test</scope>
108115 </dependency>
109116
117+ <dependency>
118+ <groupId>org.ops4j.pax.url</groupId>
119+ <artifactId>pax-url-reference</artifactId>
120+ <version>${url.version}</version>
121+ <scope>test</scope>
122+ </dependency>
123+
110124 <dependency>
111125 <groupId>javax.transaction</groupId>
112126 <artifactId>jta</artifactId>
@@ -146,12 +160,14 @@
146160 <groupId>ch.qos.logback</groupId>
147161 <artifactId>logback-classic</artifactId>
148162 <version>${logback.version}</version>
163+ <scope>test</scope>
149164 </dependency>
150165
151166 <dependency>
152167 <groupId>ch.qos.logback</groupId>
153168 <artifactId>logback-core</artifactId>
154169 <version>${logback.version}</version>
170+ <scope>test</scope>
155171 </dependency>
156172
157173 </dependencies>
modified driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java +39 −7
@@ -15,42 +15,73 @@
1515 */
1616 package com.datastax.driver.osgi.impl;
1717
18-import com.datastax.driver.core.Cluster;
19-import com.datastax.driver.core.CodecRegistry;
20-import com.datastax.driver.core.Metadata;
21-import com.datastax.driver.core.Session;
18+import com.datastax.driver.core.*;
2219 import com.datastax.driver.core.exceptions.InvalidQueryException;
20+import com.datastax.driver.core.policies.PercentileSpeculativeExecutionPolicy;
2321 import com.datastax.driver.extras.codecs.date.SimpleTimestampCodec;
2422 import com.datastax.driver.osgi.api.MailboxService;
2523 import org.osgi.framework.BundleActivator;
2624 import org.osgi.framework.BundleContext;
25+import org.slf4j.Logger;
26+import org.slf4j.LoggerFactory;
2727
2828 import java.util.Hashtable;
2929
30+import static com.datastax.driver.core.ProtocolOptions.Compression.LZ4;
3031 import static com.datastax.driver.osgi.api.MailboxMessage.TABLE;
3132
3233 public class Activator implements BundleActivator {
3334
35+ private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class);
36+
3437 private Cluster cluster;
3538
3639 @Override
3740 public void start(BundleContext context) throws Exception {
41+
42+ VersionNumber ver = VersionNumber.parse(context.getProperty("cassandra.version"));
43+ LOGGER.info("C* version: {}", ver);
44+
3845 String contactPointsStr = context.getProperty("cassandra.contactpoints");
3946 if (contactPointsStr == null) {
4047 contactPointsStr = "127.0.0.1";
4148 }
49+ LOGGER.info("Contact points: {}", contactPointsStr);
4250 String[] contactPoints = contactPointsStr.split(",");
4351
4452 String keyspace = context.getProperty("cassandra.keyspace");
4553 if (keyspace == null) {
4654 keyspace = "mailbox";
4755 }
56+ LOGGER.info("Keyspace: {}", keyspace);
4857 keyspace = Metadata.quote(keyspace);
4958
50- cluster = Cluster.builder()
59+ Cluster.Builder builder = Cluster.builder()
5160 .addContactPoints(contactPoints)
52- .withCodecRegistry(new CodecRegistry().register(SimpleTimestampCodec.instance))
53- .build();
61+ .withCodecRegistry(new CodecRegistry().register(SimpleTimestampCodec.instance));
62+
63+ String compression = context.getProperty("cassandra.compression");
64+ if (compression != null) {
65+ if (ver.getMajor() < 2 && compression.equals(LZ4.name())) {
66+ LOGGER.warn("Requested LZ4 compression but C* version is not compatible, disabling");
67+ } else {
68+ LOGGER.info("Compression: {}", compression);
69+ builder.withCompression(ProtocolOptions.Compression.valueOf(compression));
70+ }
71+ } else {
72+ LOGGER.info("Compression: NONE");
73+ }
74+
75+ String usePercentileSpeculativeExecutionPolicy = context.getProperty("cassandra.usePercentileSpeculativeExecutionPolicy");
76+ if ("true".equals(usePercentileSpeculativeExecutionPolicy)) {
77+ PerHostPercentileTracker perHostPercentileTracker = PerHostPercentileTracker.builderWithHighestTrackableLatencyMillis(15000).build();
78+ builder.withSpeculativeExecutionPolicy(new PercentileSpeculativeExecutionPolicy(perHostPercentileTracker, 99, 1));
79+ LOGGER.info("Use PercentileSpeculativeExecutionPolicy: YES");
80+ } else {
81+ LOGGER.info("Use PercentileSpeculativeExecutionPolicy: NO");
82+ }
83+
84+ cluster = builder.build();
5485
5586 Session session;
5687 try {
@@ -73,6 +104,7 @@
73104 mailbox.init();
74105
75106 context.registerService(MailboxService.class.getName(), mailbox, new Hashtable<String, String>());
107+ LOGGER.info("Mailbox Service successfully initialized");
76108 }
77109
78110 @Override
modified driver-tests/osgi/src/test/java/com/datastax/driver/osgi/BundleOptions.java +17 −0
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.osgi;
1717
18+import com.datastax.driver.core.CCMBridge;
19+import com.datastax.driver.core.ProtocolOptions;
1820 import com.datastax.driver.core.TestUtils;
1921 import org.ops4j.pax.exam.Option;
2022 import org.ops4j.pax.exam.options.CompositeOption;
@@ -48,6 +50,19 @@
4850 return mavenBundle("com.google.guava", "guava", "16.0.1");
4951 }
5052
53+ public static CompositeOption lz4Bundle() {
54+ return new CompositeOption() {
55+
56+ @Override
57+ public Option[] getOptions() {
58+ return options(
59+ systemProperty("cassandra.compression").value(ProtocolOptions.Compression.LZ4.name()),
60+ mavenBundle("net.jpountz.lz4", "lz4", "1.3.0")
61+ );
62+ }
63+ };
64+ }
65+
5166 public static CompositeOption nettyBundles() {
5267 final String nettyVersion = "4.0.33.Final";
5368 return new CompositeOption() {
@@ -78,12 +93,14 @@
7893 // Delegate javax.security.cert to the parent classloader. javax.security.cert.X509Certificate is used in
7994 // io.netty.util.internal.EmptyArrays, but not directly by the driver.
8095 bootDelegationPackage("javax.security.cert"),
96+ systemProperty("cassandra.version").value(CCMBridge.getCassandraVersion()),
8197 systemProperty("cassandra.contactpoints").value(TestUtils.IP_PREFIX + 1),
8298 systemProperty("logback.configurationFile").value("file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"),
8399 mavenBundle("org.slf4j", "slf4j-api", "1.7.5"),
84100 mavenBundle("ch.qos.logback", "logback-classic", "1.1.3"),
85101 mavenBundle("ch.qos.logback", "logback-core", "1.1.3"),
86102 mavenBundle("io.dropwizard.metrics", "metrics-core", "3.1.2"),
103+ mavenBundle("org.testng", "testng", "6.8.8"),
87104 systemPackages("org.testng", "org.junit", "org.junit.runner", "org.junit.runner.manipulation",
88105 "org.junit.runner.notification", "com.jcabi.manifests")
89106 );
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceLZ4IT.java +58 −0
@@ -0,0 +1,58 @@
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.osgi;
17+
18+import com.datastax.driver.osgi.api.MailboxException;
19+import org.ops4j.pax.exam.Configuration;
20+import org.ops4j.pax.exam.Option;
21+import org.ops4j.pax.exam.testng.listener.PaxExam;
22+import org.testng.annotations.Listeners;
23+import org.testng.annotations.Test;
24+
25+import static com.datastax.driver.osgi.BundleOptions.*;
26+import static org.ops4j.pax.exam.CoreOptions.options;
27+
28+@Listeners({CCMBridgeListener.class, PaxExam.class})
29+public class MailboxServiceLZ4IT extends MailboxServiceTests {
30+
31+ @Configuration
32+ public Option[] lz4Config() {
33+ return options(
34+ defaultOptions(),
35+ lz4Bundle(),
36+ nettyBundles(),
37+ guavaBundle(),
38+ extrasBundle(),
39+ mappingBundle(),
40+ driverBundle(),
41+ mailboxBundle()
42+ );
43+ }
44+
45+ /**
46+ * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver with
47+ * LZ4 compression activated.
48+ *
49+ * @test_category packaging
50+ * @expected_result Can create, retrieve and delete data using the mailbox service.
51+ * @jira_ticket JAVA-1200
52+ * @since 3.1.0
53+ */
54+ @Test(groups = "short")
55+ public void test_lz4() throws MailboxException {
56+ checkService();
57+ }
58+}
modified faq/README.md +11 −0
@@ -88,6 +88,17 @@
8888 ```
8989
9090
91+### Why do my 'SELECT *' `PreparedStatement`-based queries stop working after a schema change?
92+
93+Both the driver and Cassandra maintain a mapping of `PreparedStatement` queries to their
94+metadata. When a change is made to a table, such as a column being added or dropped, there
95+is currently no mechanism for Cassandra to invalidate the existing metadata. Because of this,
96+the driver is not able to properly react to these changes and will improperly read rows after
97+a schema change is made.
98+
99+See [Prepared statements](../manual/statements/prepared) for more information.
100+
101+
91102 ### Can I get the raw bytes of a text column?
92103
93104 If you need to access the raw bytes of a text column, call the
modified manual/compression/README.md +1 −1
@@ -27,7 +27,7 @@
2727 <dependency>
2828 <groupId>net.jpountz.lz4</groupId>
2929 <artifactId>lz4</artifactId>
30- <version>1.2.0</version>
30+ <version>1.3.0</version>
3131 </dependency>
3232 ```
3333
modified manual/ssl/README.md +6 −2
@@ -152,8 +152,12 @@
152152 [these instructions](http://netty.io/wiki/forked-tomcat-native.html) to
153153 add it to your dependencies.
154154
155-Note that using netty-tcnative requires JDK 1.7 or above and requires the
156-presence of OpenSSL on the system. It will not fall back to the JDK implementation.
155+There are known runtime incompatibilities between newer versions of
156+netty-tcnative and the version of netty that the driver uses. For best
157+results, use version 1.1.33.Fork18.
158+
159+Using netty-tcnative requires JDK 1.7 or above and requires the presence of
160+OpenSSL on the system. It will not fall back to the JDK implementation.
157161
158162 ##### Configuring the context
159163
modified manual/statements/prepared/README.md +40 −3
@@ -118,7 +118,7 @@
118118 ```java
119119 BoundStatement bound = ps1.bind()
120120 .setString("sku", "324378")
121- .setString("description", "LCD screen")
121+ .setString("description", "LCD screen");
122122
123123 // Using the unset method to unset previously set value.
124124 // Positional setter:
@@ -133,8 +133,27 @@
133133 serialized form.
134134
135135 `BoundStatement` is **not thread-safe**. You can reuse an instance multiple times with different parameters, but only
136-from a single thread, and only if you use the synchronous API ([Session#execute][execute] is fine,
137-[Session#executeAsync][executeAsync] is not).
136+from a single thread and only if you use synchronous calls:
137+
138+```java
139+BoundStatement bound = ps1.bind();
140+
141+// This is safe:
142+bound.setString("sku", "324378");
143+session.execute(bound);
144+
145+bound.setString("sku", "324379");
146+session.execute(bound);
147+
148+// This is NOT SAFE. executeAsync runs concurrently with your code, so the first execution might actually read the
149+// values after the second setString call, and you would insert 324381 twice:
150+bound.setString("sku", "324380");
151+session.executeAsync(bound);
152+
153+bound.setString("sku", "324381");
154+session.executeAsync(bound);
155+```
156+
138157 Also, make sure you don't accidentally reuse parameters from previous executions.
139158
140159 ### Preparing on multiple nodes
@@ -222,9 +241,27 @@
222241 specific situations; read each method's Javadoc for detailed
223242 explanations.
224243
244+### Avoid preparing 'SELECT *' queries
245+
246+Both the driver and Cassandra maintain a mapping of `PreparedStatement` queries to their
247+metadata. When a change is made to a table, such as a column being added or dropped, there
248+is currently no mechanism for Cassandra to invalidate the existing metadata. Because of this,
249+the driver is not able to properly react to these changes and will improperly read rows after
250+a schema change is made.
251+
252+Therefore it is currently recommended to not create prepared statements
253+for 'SELECT *' queries if you plan on making schema changes involving
254+adding or dropping columns. Alternatively you should list all columns of interest
255+in your statement, i.e.: `SELECT a, b, c FROM tbl`.
256+
257+This will be addressed in a future release of both Cassandra and the driver. Follow
258+[CASSANDRA-10786] and [JAVA-1196] for more information.
259+
225260 [PreparedStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PreparedStatement.html
226261 [BoundStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BoundStatement.html
227262 [setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts-boolean-
228263 [setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp-boolean-
229264 [execute]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement-
230265 [executeAsync]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement-
266+[CASSANDRA-10786]: https://issues.apache.org/jira/browse/CASSANDRA-10786
267+[JAVA-1196]: https://datastax-oss.atlassian.net/browse/JAVA-1196
No newline at the end of the file
modified pom.xml +4 −4
@@ -52,10 +52,10 @@
5252 <log4j.version>1.2.17</log4j.version>
5353 <slf4j-log4j12.version>1.7.6</slf4j-log4j12.version>
5454 <guava.version>16.0.1</guava.version>
55- <netty.version>4.0.33.Final</netty.version>
55+ <netty.version>4.0.37.Final</netty.version>
5656 <metrics.version>3.1.2</metrics.version>
5757 <snappy.version>1.0.5</snappy.version>
58- <lz4.version>1.2.0</lz4.version>
58+ <lz4.version>1.3.0</lz4.version>
5959 <hdr.version>2.1.4</hdr.version>
6060 <!-- driver-extras module -->
6161 <jackson.version>2.6.3</jackson.version>
@@ -69,7 +69,7 @@
6969 <assertj.version>1.7.0</assertj.version>
7070 <mockito.version>1.10.8</mockito.version>
7171 <commons-exec.version>1.3</commons-exec.version>
72- <scassandra.version>1.0.3</scassandra.version>
72+ <scassandra.version>1.0.9</scassandra.version>
7373 <main.basedir>${project.basedir}</main.basedir>
7474 <ipprefix>127.0.1.</ipprefix>
7575 <test.groups>unit</test.groups>
@@ -284,7 +284,7 @@
284284 </execution>
285285 </executions>
286286 <configuration>
287- <comparisonVersion>3.0.0</comparisonVersion>
287+ <comparisonVersion>3.0.2</comparisonVersion>
288288 <ignoredDifferencesFile>../clirr-ignores.xml</ignoredDifferencesFile>
289289 </configuration>
290290 <!--