kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 909018904d3ca347db2f8aea844362d51af8eab92883a857351b0e64aca83de9 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2016-07-13 15:25 -07:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-07-13 15:25 -07:00 |
| Parents | f0747dbb178c, 6c9b5d299f55 |
63 files changed
modified changelog/README.md +24 −0
| @@ -57,6 +57,30 @@ | ||
| 57 | 57 | - [improvement] JAVA-444: Add Java process information to UUIDs.makeNode() hash. |
| 58 | 58 | |
| 59 | 59 | |
| 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 | + | |
| 60 | 84 | ### 3.0.2 |
| 61 | 85 | |
| 62 | 86 | 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 @@ | ||
| 143 | 143 | <dependency> |
| 144 | 144 | <groupId>io.netty</groupId> |
| 145 | 145 | <artifactId>netty-tcnative</artifactId> |
| 146 | - <version>1.1.33.Fork10</version> | |
| 146 | + <version>1.1.33.Fork18</version> | |
| 147 | 147 | <classifier>${os.detected.classifier}</classifier> |
| 148 | 148 | <scope>test</scope> |
| 149 | 149 | </dependency> |
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +5 −0
| @@ -46,6 +46,11 @@ | ||
| 46 | 46 | * will be ignored server side (no tombstones will be generated). If you're reusing |
| 47 | 47 | * a bound statement, you can {@link #unset(int) unset} variables that were previously |
| 48 | 48 | * 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). | |
| 49 | 54 | */ |
| 50 | 55 | public class BoundStatement extends Statement implements SettableData<BoundStatement>, GettableData { |
| 51 | 56 | 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 @@ | ||
| 1857 | 1857 | if (controlConnection.refreshNodeInfo(host)) { |
| 1858 | 1858 | logger.debug("Successful reconnection to {}, setting host UP", host); |
| 1859 | 1859 | try { |
| 1860 | - if (isHostAddition) | |
| 1860 | + if (isHostAddition) { | |
| 1861 | 1861 | onAdd(host, connection); |
| 1862 | - else | |
| 1862 | + submitNodeListRefresh(); | |
| 1863 | + } else | |
| 1863 | 1864 | onUp(host, connection); |
| 1864 | 1865 | } catch (InterruptedException e) { |
| 1865 | 1866 | Thread.currentThread().interrupt(); |
| @@ -2134,8 +2135,8 @@ | ||
| 2134 | 2135 | public PreparedStatement addPrepared(PreparedStatement stmt) { |
| 2135 | 2136 | PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().id, stmt); |
| 2136 | 2137 | 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()); | |
| 2139 | 2140 | |
| 2140 | 2141 | // The one object in the cache will get GCed once it's not referenced by the client anymore since we use a weak reference. |
| 2141 | 2142 | // 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 @@ | ||
| 2232 | 2233 | return schemaRefreshRequestDebouncer.eventReceived(request); |
| 2233 | 2234 | } |
| 2234 | 2235 | |
| 2235 | - void submitNodeListRefresh() { | |
| 2236 | + ListenableFuture<Void> submitNodeListRefresh() { | |
| 2236 | 2237 | logger.trace("Submitting node list and token map refresh"); |
| 2237 | - nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest()); | |
| 2238 | + return nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest()); | |
| 2238 | 2239 | } |
| 2239 | 2240 | |
| 2240 | - void submitNodeRefresh(InetSocketAddress address, HostEvent eventType) { | |
| 2241 | + ListenableFuture<Void> submitNodeRefresh(InetSocketAddress address, HostEvent eventType) { | |
| 2241 | 2242 | NodeRefreshRequest request = new NodeRefreshRequest(address, eventType); |
| 2242 | 2243 | logger.trace("Submitting node refresh: {}", request); |
| 2243 | - nodeRefreshRequestDebouncer.eventReceived(request); | |
| 2244 | + return nodeRefreshRequestDebouncer.eventReceived(request); | |
| 2244 | 2245 | } |
| 2245 | 2246 | |
| 2246 | 2247 | // refresh the schema using the provided connection, and notice the future with the provided resultset once done |
| @@ -2271,7 +2272,15 @@ | ||
| 2271 | 2272 | if (!schemaInAgreement) |
| 2272 | 2273 | logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); |
| 2273 | 2274 | |
| 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 | + } | |
| 2275 | 2284 | final boolean finalSchemaInAgreement = schemaInAgreement; |
| 2276 | 2285 | schemaReady.addListener(new Runnable() { |
| 2277 | 2286 | @Override |
| @@ -2715,6 +2724,7 @@ | ||
| 2715 | 2724 | public void runMayThrow() throws Exception { |
| 2716 | 2725 | if (controlConnection.refreshNodeInfo(host)) { |
| 2717 | 2726 | onAdd(host, null); |
| 2727 | + submitNodeListRefresh(); | |
| 2718 | 2728 | } else { |
| 2719 | 2729 | logger.debug("Not enough info for {}, ignoring host", host); |
| 2720 | 2730 | } |
| @@ -2751,6 +2761,7 @@ | ||
| 2751 | 2761 | if (metadata.remove(host)) { |
| 2752 | 2762 | logger.info("Cassandra host {} removed", host); |
| 2753 | 2763 | onRemove(host); |
| 2764 | + submitNodeListRefresh(); | |
| 2754 | 2765 | } |
| 2755 | 2766 | } |
| 2756 | 2767 | }; |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +40 −30
| @@ -267,16 +267,15 @@ | ||
| 267 | 267 | |
| 268 | 268 | // We need to refresh the node list first so we know about the cassandra version of |
| 269 | 269 | // 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 | |
| 270 | 272 | refreshNodeListAndTokenMap(connection, cluster, isInitialConnection, true); |
| 271 | 273 | |
| 274 | + // refresh schema will also update the token map again, | |
| 275 | + // this time with information about keyspaces | |
| 272 | 276 | logger.debug("[Control connection] Refreshing schema"); |
| 273 | 277 | refreshSchema(connection, null, null, null, null, cluster); |
| 274 | 278 | |
| 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 | - | |
| 280 | 279 | return connection; |
| 281 | 280 | } catch (BusyConnectionException e) { |
| 282 | 281 | connection.closeAsync().force(); |
| @@ -306,11 +305,6 @@ | ||
| 306 | 305 | if (c == null || c.isClosed()) |
| 307 | 306 | return; |
| 308 | 307 | 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 | - } | |
| 314 | 308 | } catch (ConnectionException e) { |
| 315 | 309 | logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage()); |
| 316 | 310 | signalError(); |
| @@ -383,11 +377,13 @@ | ||
| 383 | 377 | |
| 384 | 378 | if (broadcastAddress == null) { |
| 385 | 379 | 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()))) { | |
| 387 | 381 | // Some DSE versions were inserting a line for the local node in peers (with mostly null values). This has been fixed, but if we |
| 388 | 382 | // detect that's the case, ignore it as it's not really a big deal. |
| 389 | 383 | 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); |
| 390 | 384 | return null; |
| 385 | + } else if (rpcAddress == null) { | |
| 386 | + return null; | |
| 391 | 387 | } else if (rpcAddress.equals(bindAllAddress)) { |
| 392 | 388 | 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); |
| 393 | 389 | rpcAddress = broadcastAddress; |
| @@ -550,7 +546,8 @@ | ||
| 550 | 546 | connection.write(peersFuture); |
| 551 | 547 | |
| 552 | 548 | 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>>(); | |
| 554 | 551 | |
| 555 | 552 | // Update cluster name, DC and rack for the one node we are connected to |
| 556 | 553 | Row localRow = localFuture.get().one(); |
| @@ -560,8 +557,10 @@ | ||
| 560 | 557 | cluster.metadata.clusterName = clusterName; |
| 561 | 558 | |
| 562 | 559 | partitioner = localRow.getString("partitioner"); |
| 563 | - if (partitioner != null) | |
| 560 | + if (partitioner != null) { | |
| 564 | 561 | cluster.metadata.partitioner = partitioner; |
| 562 | + factory = Token.getFactory(partitioner); | |
| 563 | + } | |
| 565 | 564 | |
| 566 | 565 | Host host = cluster.metadata.getHost(connection.address); |
| 567 | 566 | // In theory host can't be null. However there is no point in risking a NPE in case we |
| @@ -570,10 +569,12 @@ | ||
| 570 | 569 | logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address); |
| 571 | 570 | } else { |
| 572 | 571 | 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); | |
| 576 | 576 | tokenMap.put(host, tokens); |
| 577 | + } | |
| 577 | 578 | } |
| 578 | 579 | } |
| 579 | 580 | } |
| @@ -584,7 +585,7 @@ | ||
| 584 | 585 | List<String> cassandraVersions = new ArrayList<String>(); |
| 585 | 586 | List<InetAddress> broadcastAddresses = new ArrayList<InetAddress>(); |
| 586 | 587 | List<InetAddress> listenAddresses = new ArrayList<InetAddress>(); |
| 587 | - List<Set<String>> allTokens = new ArrayList<Set<String>>(); | |
| 588 | + List<Set<Token>> allTokens = new ArrayList<Set<Token>>(); | |
| 588 | 589 | List<String> dseVersions = new ArrayList<String>(); |
| 589 | 590 | List<Boolean> dseGraphEnabled = new ArrayList<Boolean>(); |
| 590 | 591 | List<String> dseWorkloads = new ArrayList<String>(); |
| @@ -601,8 +602,14 @@ | ||
| 601 | 602 | racks.add(row.getString("rack")); |
| 602 | 603 | cassandraVersions.add(row.getString("release_version")); |
| 603 | 604 | 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 | + } | |
| 606 | 613 | InetAddress listenAddress = row.getColumnDefinitions().contains("listen_address") ? row.getInet("listen_address") : null; |
| 607 | 614 | listenAddresses.add(listenAddress); |
| 608 | 615 | String dseWorkload = row.getColumnDefinitions().contains("workload") ? row.getString("workload") : null; |
| @@ -645,7 +652,7 @@ | ||
| 645 | 652 | if (dseGraphEnabled.get(i) != null) |
| 646 | 653 | host.setDseGraphEnabled(dseGraphEnabled.get(i)); |
| 647 | 654 | |
| 648 | - if (metadataEnabled && partitioner != null && !allTokens.get(i).isEmpty()) | |
| 655 | + if (metadataEnabled && factory != null && allTokens.get(i) != null) | |
| 649 | 656 | tokenMap.put(host, allTokens.get(i)); |
| 650 | 657 | |
| 651 | 658 | if (isNew && !isInitialConnection) |
| @@ -658,8 +665,16 @@ | ||
| 658 | 665 | if (!host.getSocketAddress().equals(connection.address) && !foundHostsSet.contains(host.getSocketAddress())) |
| 659 | 666 | cluster.removeHost(host, isInitialConnection); |
| 660 | 667 | |
| 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; | |
| 663 | 678 | } |
| 664 | 679 | |
| 665 | 680 | private static boolean isValidPeer(Row peerRow, boolean logIfInvalid) { |
| @@ -761,13 +776,15 @@ | ||
| 761 | 776 | public void onUp(Host host) { |
| 762 | 777 | } |
| 763 | 778 | |
| 779 | + public void onAdd(Host host) { | |
| 780 | + } | |
| 781 | + | |
| 764 | 782 | public void onDown(Host host) { |
| 765 | 783 | onHostGone(host); |
| 766 | 784 | } |
| 767 | 785 | |
| 768 | 786 | public void onRemove(Host host) { |
| 769 | 787 | onHostGone(host); |
| 770 | - cluster.submitNodeListRefresh(); | |
| 771 | 788 | } |
| 772 | 789 | |
| 773 | 790 | private void onHostGone(Host host) { |
| @@ -788,11 +805,4 @@ | ||
| 788 | 805 | backgroundReconnect(0); |
| 789 | 806 | } |
| 790 | 807 | |
| 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 | - } | |
| 798 | 808 | } |
modified driver-core/src/main/java/com/datastax/driver/core/EventDebouncer.java +1 −1
| @@ -164,7 +164,7 @@ | ||
| 164 | 164 | return entry.future; |
| 165 | 165 | } |
| 166 | 166 | |
| 167 | - private void scheduleImmediateDelivery() { | |
| 167 | + void scheduleImmediateDelivery() { | |
| 168 | 168 | cancelDelayedDelivery(); |
| 169 | 169 | |
| 170 | 170 | while (state == State.RUNNING) { |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +47 −41
| @@ -41,7 +41,7 @@ | ||
| 41 | 41 | volatile String partitioner; |
| 42 | 42 | private final ConcurrentMap<InetSocketAddress, Host> hosts = new ConcurrentHashMap<InetSocketAddress, Host>(); |
| 43 | 43 | final ConcurrentMap<String, KeyspaceMetadata> keyspaces = new ConcurrentHashMap<String, KeyspaceMetadata>(); |
| 44 | - volatile TokenMap tokenMap; | |
| 44 | + private volatile TokenMap tokenMap; | |
| 45 | 45 | |
| 46 | 46 | final ReentrantLock lock = new ReentrantLock(); |
| 47 | 47 | |
| @@ -62,18 +62,28 @@ | ||
| 62 | 62 | this.cluster = cluster; |
| 63 | 63 | } |
| 64 | 64 | |
| 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() { | |
| 66 | 67 | lock.lock(); |
| 67 | 68 | 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) | |
| 75 | 70 | 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 | + } | |
| 76 | 82 | |
| 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 { | |
| 77 | 87 | this.tokenMap = TokenMap.build(factory, allTokens, keyspaces.values()); |
| 78 | 88 | } finally { |
| 79 | 89 | lock.unlock(); |
| @@ -264,7 +274,7 @@ | ||
| 264 | 274 | if (current == null) { |
| 265 | 275 | return Collections.emptySet(); |
| 266 | 276 | } else { |
| 267 | - Map<Host, Set<TokenRange>> dcRanges = current.hostsToRanges.get(keyspace); | |
| 277 | + Map<Host, Set<TokenRange>> dcRanges = current.hostsToRangesByKeyspace.get(keyspace); | |
| 268 | 278 | if (dcRanges == null) { |
| 269 | 279 | return Collections.emptySet(); |
| 270 | 280 | } else { |
| @@ -384,7 +394,7 @@ | ||
| 384 | 394 | KeyspaceMetadata removeKeyspace(String keyspace) { |
| 385 | 395 | KeyspaceMetadata removed = keyspaces.remove(keyspace); |
| 386 | 396 | if (tokenMap != null) |
| 387 | - tokenMap.tokenToHosts.remove(keyspace); | |
| 397 | + tokenMap.tokenToHostsByKeyspace.remove(keyspace); | |
| 388 | 398 | return removed; |
| 389 | 399 | } |
| 390 | 400 | |
| @@ -609,61 +619,57 @@ | ||
| 609 | 619 | } |
| 610 | 620 | } |
| 611 | 621 | |
| 612 | - static class TokenMap { | |
| 622 | + private static class TokenMap { | |
| 613 | 623 | |
| 614 | 624 | 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; | |
| 617 | 628 | private final List<Token> ring; |
| 618 | 629 | private final Set<TokenRange> tokenRanges; |
| 619 | - final Set<Host> hosts; | |
| 630 | + private final Map<Token, Host> tokenToPrimary; | |
| 620 | 631 | |
| 621 | 632 | private TokenMap(Token.Factory factory, |
| 633 | + List<Token> ring, | |
| 634 | + Set<TokenRange> tokenRanges, | |
| 635 | + Map<Token, Host> tokenToPrimary, | |
| 622 | 636 | 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) { | |
| 626 | 639 | this.factory = factory; |
| 627 | - this.tokenToHosts = tokenToHosts; | |
| 628 | - this.hostsToRanges = hostsToRanges; | |
| 629 | 640 | this.ring = ring; |
| 630 | 641 | this.tokenRanges = tokenRanges; |
| 631 | - this.hosts = hosts; | |
| 642 | + this.tokenToPrimary = tokenToPrimary; | |
| 643 | + this.primaryToTokens = primaryToTokens; | |
| 644 | + this.tokenToHostsByKeyspace = tokenToHostsByKeyspace; | |
| 645 | + this.hostsToRangesByKeyspace = hostsToRangesByKeyspace; | |
| 632 | 646 | for (Map.Entry<Host, Set<Token>> entry : primaryToTokens.entrySet()) { |
| 633 | 647 | Host host = entry.getKey(); |
| 634 | 648 | host.setTokens(ImmutableSet.copyOf(entry.getValue())); |
| 635 | 649 | } |
| 636 | 650 | } |
| 637 | 651 | |
| 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) { | |
| 641 | 653 | Map<Token, Host> tokenToPrimary = new HashMap<Token, Host>(); |
| 642 | - Map<Host, Set<Token>> primaryToTokens = new HashMap<Host, Set<Token>>(); | |
| 643 | 654 | 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()) { | |
| 646 | 656 | Host host = entry.getKey(); |
| 647 | - for (String tokenStr : entry.getValue()) { | |
| 657 | + for (Token t : entry.getValue()) { | |
| 648 | 658 | try { |
| 649 | - Token t = factory.fromString(tokenStr); | |
| 650 | 659 | allSorted.add(t); |
| 651 | 660 | 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); | |
| 658 | 661 | } catch (IllegalArgumentException e) { |
| 659 | 662 | // If we failed parsing that token, skip it |
| 660 | 663 | } |
| 661 | 664 | } |
| 662 | 665 | } |
| 663 | - | |
| 664 | 666 | List<Token> ring = new ArrayList<Token>(allSorted); |
| 665 | 667 | Set<TokenRange> tokenRanges = makeTokenRanges(ring, factory); |
| 668 | + return build(factory, allTokens, keyspaces, ring, tokenRanges, tokenToPrimary); | |
| 669 | + } | |
| 666 | 670 | |
| 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(); | |
| 667 | 673 | Map<String, Map<Token, Set<Host>>> tokenToHosts = new HashMap<String, Map<Token, Set<Host>>>(); |
| 668 | 674 | Map<ReplicationStrategy, Map<Token, Set<Host>>> replStrategyToHosts = new HashMap<ReplicationStrategy, Map<Token, Set<Host>>>(); |
| 669 | 675 | Map<String, Map<Host, Set<TokenRange>>> hostsToRanges = new HashMap<String, Map<Host, Set<TokenRange>>>(); |
| @@ -691,17 +697,17 @@ | ||
| 691 | 697 | } |
| 692 | 698 | hostsToRanges.put(keyspace.getName(), ksRanges); |
| 693 | 699 | } |
| 694 | - return new TokenMap(factory, primaryToTokens, tokenToHosts, hostsToRanges, ring, tokenRanges, hosts); | |
| 700 | + return new TokenMap(factory, ring, tokenRanges, tokenToPrimary, allTokens, tokenToHosts, hostsToRanges); | |
| 695 | 701 | } |
| 696 | 702 | |
| 697 | 703 | private Set<Host> getReplicas(String keyspace, Token token) { |
| 698 | 704 | |
| 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) | |
| 701 | 707 | return Collections.emptySet(); |
| 702 | 708 | |
| 703 | 709 | // 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); | |
| 705 | 711 | if (hosts != null) |
| 706 | 712 | return hosts; |
| 707 | 713 | |
| @@ -713,7 +719,7 @@ | ||
| 713 | 719 | i = 0; |
| 714 | 720 | } |
| 715 | 721 | |
| 716 | - return keyspaceHosts.get(ring.get(i)); | |
| 722 | + return tokenToHosts.get(ring.get(i)); | |
| 717 | 723 | } |
| 718 | 724 | |
| 719 | 725 | 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 @@ | ||
| 165 | 165 | * nodes that do not support this protocol version will be ignored. |
| 166 | 166 | */ |
| 167 | 167 | public ProtocolVersion getProtocolVersion() { |
| 168 | - return manager.connectionFactory.protocolVersion; | |
| 168 | + return manager == null || manager.connectionFactory == null ? null : manager.connectionFactory.protocolVersion; | |
| 169 | 169 | } |
| 170 | 170 | |
| 171 | 171 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +15 −1
| @@ -16,6 +16,8 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| 19 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 20 | +import com.google.common.util.concurrent.Futures; | |
| 19 | 21 | |
| 20 | 22 | /** |
| 21 | 23 | * Options related to defaults for individual queries. |
| @@ -299,7 +301,19 @@ | ||
| 299 | 301 | boolean wasEnabled = this.metadataEnabled; |
| 300 | 302 | this.metadataEnabled = enabled; |
| 301 | 303 | 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 | + }); | |
| 303 | 317 | } |
| 304 | 318 | return this; |
| 305 | 319 | } |
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 @@ | ||
| 63 | 63 | assert rows.keyspaces != null; |
| 64 | 64 | Map<String, KeyspaceMetadata> keyspaces = buildKeyspaces(rows, cassandraVersion, cluster); |
| 65 | 65 | 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(); | |
| 66 | 69 | } else { |
| 67 | 70 | assert targetKeyspace != null; |
| 68 | 71 | KeyspaceMetadata keyspace = metadata.keyspaces.get(targetKeyspace); |
modified driver-core/src/main/java/com/datastax/driver/core/VersionNumber.java +14 −15
| @@ -60,7 +60,7 @@ | ||
| 60 | 60 | * The version string should have primarily the form X.Y.Z to which can be appended |
| 61 | 61 | * one or more pre-release label after dashes (2.0.1-beta1, 2.1.4-rc1-SNAPSHOT) |
| 62 | 62 | * 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. | |
| 64 | 64 | * |
| 65 | 65 | * @param version the string to parse |
| 66 | 66 | * @return the parsed version number. |
| @@ -139,13 +139,13 @@ | ||
| 139 | 139 | } |
| 140 | 140 | |
| 141 | 141 | /** |
| 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. | |
| 143 | 143 | * |
| 144 | 144 | * @return the pre-releases labels. The return list will be {@code null} if the version number |
| 145 | 145 | * doesn't have one. |
| 146 | 146 | */ |
| 147 | 147 | public List<String> getPreReleaseLabels() { |
| 148 | - return Collections.unmodifiableList(Arrays.asList(preReleases)); | |
| 148 | + return preReleases == null ? null : Collections.unmodifiableList(Arrays.asList(preReleases)); | |
| 149 | 149 | } |
| 150 | 150 | |
| 151 | 151 | /** |
| @@ -217,19 +217,18 @@ | ||
| 217 | 217 | } |
| 218 | 218 | |
| 219 | 219 | @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)) | |
| 222 | 224 | 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); | |
| 233 | 232 | } |
| 234 | 233 | |
| 235 | 234 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ConnectionException.java +2 −2
| @@ -40,7 +40,7 @@ | ||
| 40 | 40 | |
| 41 | 41 | @Override |
| 42 | 42 | public InetAddress getHost() { |
| 43 | - return address.getAddress(); | |
| 43 | + return address == null ? null : address.getAddress(); | |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | 46 | @Override |
| @@ -50,7 +50,7 @@ | ||
| 50 | 50 | |
| 51 | 51 | @Override |
| 52 | 52 | public String getMessage() { |
| 53 | - return String.format("[%s] %s", getHost(), getRawMessage()); | |
| 53 | + return address == null ? getRawMessage() : String.format("[%s] %s", address, getRawMessage()); | |
| 54 | 54 | } |
| 55 | 55 | |
| 56 | 56 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +4 −2
| @@ -97,8 +97,6 @@ | ||
| 97 | 97 | } else if (!dc.equals(localDc)) |
| 98 | 98 | notInLocalDC.add(String.format("%s (%s)", host.toString(), dc)); |
| 99 | 99 | |
| 100 | - if (!dc.equals(localDc)) notInLocalDC.add(String.format("%s (%s)", host.toString(), host.getDatacenter())); | |
| 101 | - | |
| 102 | 100 | CopyOnWriteArrayList<Host> prev = perDcLiveHosts.get(dc); |
| 103 | 101 | if (prev == null) |
| 104 | 102 | perDcLiveHosts.put(dc, new CopyOnWriteArrayList<Host>(Collections.singletonList(host))); |
| @@ -358,6 +356,10 @@ | ||
| 358 | 356 | * @return the policy. |
| 359 | 357 | */ |
| 360 | 358 | 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 | + } | |
| 361 | 363 | return new DCAwareRoundRobinPolicy(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, true); |
| 362 | 364 | } |
| 363 | 365 | } |
modified driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java +1 −0
| @@ -69,6 +69,7 @@ | ||
| 69 | 69 | |
| 70 | 70 | @Override |
| 71 | 71 | public void init(Cluster cluster) { |
| 72 | + childPolicy.init(cluster); | |
| 72 | 73 | queryOptions = cluster.getConfiguration().getQueryOptions(); |
| 73 | 74 | } |
| 74 | 75 |
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java +1 −1
| @@ -150,7 +150,7 @@ | ||
| 150 | 150 | |
| 151 | 151 | @Override |
| 152 | 152 | public void init(Cluster cluster) { |
| 153 | - // nothing to do | |
| 153 | + policy.init(cluster); | |
| 154 | 154 | } |
| 155 | 155 | |
| 156 | 156 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/policies/RoundRobinPolicy.java +1 −1
| @@ -102,7 +102,7 @@ | ||
| 102 | 102 | hasLoggedLocalCLUse = true; |
| 103 | 103 | logger.warn("Detected request at Consistency Level {} but the non-DC aware RoundRobinPolicy is in use. " |
| 104 | 104 | + "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); | |
| 106 | 106 | } |
| 107 | 107 | } |
| 108 | 108 |
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +3 −0
| @@ -84,4 +84,7 @@ | ||
| 84 | 84 | return new MaterializedViewMetadataAssert(view); |
| 85 | 85 | } |
| 86 | 86 | |
| 87 | + public static VersionNumberAssert assertThat(VersionNumber actual) { | |
| 88 | + return new VersionNumberAssert(actual); | |
| 89 | + } | |
| 87 | 90 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +18 −5
| @@ -167,7 +167,7 @@ | ||
| 167 | 167 | } |
| 168 | 168 | |
| 169 | 169 | if (isWindows()) { |
| 170 | - CCM_COMMAND = "cmd /c ccm.py"; | |
| 170 | + CCM_COMMAND = "powershell.exe -ExecutionPolicy Unrestricted ccm.py"; | |
| 171 | 171 | } else { |
| 172 | 172 | CCM_COMMAND = "ccm"; |
| 173 | 173 | } |
| @@ -193,7 +193,7 @@ | ||
| 193 | 193 | * |
| 194 | 194 | * @return <code>true</code> if the operating system is a Windows one, <code>false</code> otherwise. |
| 195 | 195 | */ |
| 196 | - private static boolean isWindows() { | |
| 196 | + public static boolean isWindows() { | |
| 197 | 197 | |
| 198 | 198 | String osName = System.getProperty("os.name"); |
| 199 | 199 | return osName != null && osName.startsWith("Windows"); |
| @@ -386,7 +386,11 @@ | ||
| 386 | 386 | if (logger.isDebugEnabled()) |
| 387 | 387 | logger.debug("Starting: {} - free memory: {} MB", this, TestUtils.getFreeMemoryMB()); |
| 388 | 388 | 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); | |
| 390 | 394 | } catch (CCMException e) { |
| 391 | 395 | logger.error("Could not start " + this, e); |
| 392 | 396 | logger.error("CCM output:\n{}", e.getOut()); |
| @@ -444,7 +448,11 @@ | ||
| 444 | 448 | public void start(int n) { |
| 445 | 449 | logger.debug(String.format("Starting: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this)); |
| 446 | 450 | 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); | |
| 448 | 456 | } catch (CCMException e) { |
| 449 | 457 | logger.error(String.format("Could not start node %s in %s", n, this), e); |
| 450 | 458 | logger.error("CCM output:\n{}", e.getOut()); |
| @@ -875,9 +883,14 @@ | ||
| 875 | 883 | |
| 876 | 884 | private String joinJvmArgs() { |
| 877 | 885 | StringBuilder allJvmArgs = new StringBuilder(""); |
| 886 | + String quote = isWindows() ? "\"" : ""; | |
| 878 | 887 | 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="); | |
| 880 | 892 | allJvmArgs.append(randomizePorts(jvmArg)); |
| 893 | + allJvmArgs.append(quote); | |
| 881 | 894 | } |
| 882 | 895 | return allJvmArgs.toString(); |
| 883 | 896 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +4 −4
| @@ -42,7 +42,8 @@ | ||
| 42 | 42 | import static com.datastax.driver.core.Assertions.fail; |
| 43 | 43 | import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS; |
| 44 | 44 | 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; | |
| 46 | 47 | import static org.mockito.Mockito.*; |
| 47 | 48 | |
| 48 | 49 | public class ClusterInitTest { |
| @@ -107,7 +108,6 @@ | ||
| 107 | 108 | .withReconnectionPolicy(reconnectionPolicy) |
| 108 | 109 | .withPoolingOptions(poolingOptions) |
| 109 | 110 | .withProtocolVersion(TestUtils.getDesiredProtocolVersion()) |
| 110 | - .withQueryOptions(nonDebouncingQueryOptions()) | |
| 111 | 111 | .build(); |
| 112 | 112 | cluster.connect(); |
| 113 | 113 | |
| @@ -228,7 +228,7 @@ | ||
| 228 | 228 | ScassandraCluster scassandraCluster = ScassandraCluster.builder() |
| 229 | 229 | .withIpPrefix(TestUtils.IP_PREFIX) |
| 230 | 230 | .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. | |
| 232 | 232 | .forcePeerInfo(1, 2, "release_version", "1.2.19") |
| 233 | 233 | .build(); |
| 234 | 234 | Cluster cluster = Cluster.builder() |
| @@ -262,7 +262,7 @@ | ||
| 262 | 262 | PrimingClient.builder() |
| 263 | 263 | .withHost(ipOfNode(1)) |
| 264 | 264 | .withPort(scassandra.getAdminPort()) |
| 265 | - .build(); | |
| 265 | + .build(); | |
| 266 | 266 | |
| 267 | 267 | List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(5); |
| 268 | 268 |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +39 −19
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import com.datastax.driver.core.exceptions.BusyConnectionException; |
| 20 | 20 | import com.datastax.driver.core.exceptions.ConnectionException; |
| 21 | 21 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 22 | +import com.google.common.base.Predicate; | |
| 22 | 23 | import com.google.common.util.concurrent.*; |
| 23 | 24 | import org.scassandra.cql.PrimitiveType; |
| 24 | 25 | import org.scassandra.http.client.PrimingRequest; |
| @@ -33,6 +34,7 @@ | ||
| 33 | 34 | import java.util.concurrent.atomic.AtomicReference; |
| 34 | 35 | |
| 35 | 36 | import static com.datastax.driver.core.Assertions.assertThat; |
| 37 | +import static com.datastax.driver.core.ConditionChecker.check; | |
| 36 | 38 | import static com.google.common.collect.Lists.newArrayList; |
| 37 | 39 | import static java.util.Collections.singletonList; |
| 38 | 40 | import static java.util.concurrent.TimeUnit.SECONDS; |
| @@ -49,6 +51,22 @@ | ||
| 49 | 51 | cluster.close(); |
| 50 | 52 | } |
| 51 | 53 | |
| 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 | + | |
| 52 | 70 | /** |
| 53 | 71 | * Sends 101 requests on pool, asserting that the connection used is in expectedConnections, except for the last request. |
| 54 | 72 | */ |
| @@ -157,7 +175,8 @@ | ||
| 157 | 175 | requests.addAll(fillConnectionToThreshold(pool, coreConnections)); |
| 158 | 176 | |
| 159 | 177 | // 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); | |
| 161 | 180 | |
| 162 | 181 | // Borrow more and ensure the connection returned is a non-core connection. |
| 163 | 182 | for (int i = 0; i < 100; i++) { |
| @@ -203,8 +222,8 @@ | ||
| 203 | 222 | requests.addAll(fillConnectionToThreshold(pool, singletonList(core))); |
| 204 | 223 | |
| 205 | 224 | // 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); | |
| 208 | 227 | } finally { |
| 209 | 228 | completeRequests(requests); |
| 210 | 229 | cluster.close(); |
| @@ -231,8 +250,8 @@ | ||
| 231 | 250 | |
| 232 | 251 | requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1))); |
| 233 | 252 | |
| 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); | |
| 236 | 255 | Connection connection2 = pool.connections.get(1); |
| 237 | 256 | |
| 238 | 257 | assertThat(connection1.inFlight.get()).isEqualTo(101); |
| @@ -259,7 +278,8 @@ | ||
| 259 | 278 | |
| 260 | 279 | // Borrowing one more time should resurrect the trashed connection |
| 261 | 280 | 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); | |
| 263 | 283 | |
| 264 | 284 | assertThat(pool.connections).containsExactly(connection2, connection1); |
| 265 | 285 | assertThat(pool.trash).isEmpty(); |
| @@ -291,9 +311,9 @@ | ||
| 291 | 311 | |
| 292 | 312 | requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1))); |
| 293 | 313 | |
| 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); | |
| 295 | 316 | reset(factory); |
| 296 | - assertThat(pool.connections).hasSize(2); | |
| 297 | 317 | Connection connection2 = pool.connections.get(1); |
| 298 | 318 | |
| 299 | 319 | assertThat(connection1.inFlight.get()).isEqualTo(101); |
| @@ -323,7 +343,8 @@ | ||
| 323 | 343 | // Fill the live connection to go over the threshold where a second one is needed |
| 324 | 344 | requests.addAll(fillConnectionToThreshold(pool, singletonList(connection2))); |
| 325 | 345 | 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); | |
| 327 | 348 | |
| 328 | 349 | // Borrow again to get the new connection |
| 329 | 350 | MockRequest request = MockRequest.send(pool); |
| @@ -358,7 +379,7 @@ | ||
| 358 | 379 | // Fill core connection enough to trigger creation of another one |
| 359 | 380 | requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1))); |
| 360 | 381 | |
| 361 | - verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class)); | |
| 382 | + verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); | |
| 362 | 383 | assertThat(pool.connections).hasSize(2); |
| 363 | 384 | |
| 364 | 385 | // Return enough times to get back under the threshold where one connection is enough |
| @@ -408,7 +429,7 @@ | ||
| 408 | 429 | |
| 409 | 430 | requests.addAll(fillConnectionToThreshold(pool, singletonList(core))); |
| 410 | 431 | |
| 411 | - verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class)); | |
| 432 | + verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); | |
| 412 | 433 | assertThat(pool.connections).hasSize(2); |
| 413 | 434 | |
| 414 | 435 | // Grab the new non-core connection and replace it with a spy. |
| @@ -675,7 +696,7 @@ | ||
| 675 | 696 | } |
| 676 | 697 | |
| 677 | 698 | // 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)); | |
| 679 | 700 | assertThat(pool.connections).hasSize(2); |
| 680 | 701 | |
| 681 | 702 | // Reset factory mock as we'll be checking for new open() invokes later. |
| @@ -710,12 +731,13 @@ | ||
| 710 | 731 | |
| 711 | 732 | // After some time the a connection should attempt to be opened (but will fail). |
| 712 | 733 | verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class)); |
| 734 | + assertPoolSize(pool, 1); | |
| 713 | 735 | assertThat(pool.connections).hasSize(1); |
| 714 | 736 | |
| 715 | 737 | // Wait some reasonable amount of time for connection to reestablish then check pool size. |
| 716 | 738 | Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS); |
| 717 | 739 | // Reconnecting failed since listening was enabled. |
| 718 | - assertThat(pool.connections).hasSize(1); | |
| 740 | + assertPoolSize(pool, 1); | |
| 719 | 741 | |
| 720 | 742 | // Re enable listening then wait for reconnect. |
| 721 | 743 | currentClient.enableListener(); |
| @@ -792,8 +814,7 @@ | ||
| 792 | 814 | requests.add(MockRequest.send(pool)); |
| 793 | 815 | verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class)); |
| 794 | 816 | reset(factory); |
| 795 | - Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS); | |
| 796 | - assertThat(pool.connections).hasSize(i); | |
| 817 | + assertPoolSize(pool, i); | |
| 797 | 818 | } |
| 798 | 819 | } finally { |
| 799 | 820 | completeRequests(requests); |
| @@ -896,8 +917,7 @@ | ||
| 896 | 917 | |
| 897 | 918 | // Should create up to core connections. |
| 898 | 919 | 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); | |
| 901 | 921 | } finally { |
| 902 | 922 | cluster.close(); |
| 903 | 923 | } |
| @@ -959,10 +979,10 @@ | ||
| 959 | 979 | } |
| 960 | 980 | |
| 961 | 981 | /** |
| 962 | - * <p/> | |
| 982 | + * <p> | |
| 963 | 983 | * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the |
| 964 | 984 | * insertions are being executed, the number of opened connection is monitored. |
| 965 | - * <p/> | |
| 985 | + * <p> | |
| 966 | 986 | * If at anytime, the number of opened connections is negative, this test will fail. |
| 967 | 987 | * |
| 968 | 988 | * @jira_ticket JAVA-349 |
modified driver-core/src/test/java/com/datastax/driver/core/HostMetadataIntegrationTest.java +0 −2
| @@ -24,7 +24,6 @@ | ||
| 24 | 24 | import static com.datastax.driver.core.Assertions.assertThat; |
| 25 | 25 | import static com.datastax.driver.core.CCMAccess.Workload.solr; |
| 26 | 26 | import static com.datastax.driver.core.CCMAccess.Workload.spark; |
| 27 | -import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 28 | 27 | import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; |
| 29 | 28 | |
| 30 | 29 | public class HostMetadataIntegrationTest { |
| @@ -58,7 +57,6 @@ | ||
| 58 | 57 | Cluster cluster = Cluster.builder() |
| 59 | 58 | .addContactPoints(ccm.addressOfNode(1).getAddress()) |
| 60 | 59 | .withPort(ccm.getBinaryPort()) |
| 61 | - .withQueryOptions(nonDebouncingQueryOptions()) | |
| 62 | 60 | .build(); |
| 63 | 61 | try { |
| 64 | 62 | cluster.connect(); |
modified driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +7 −39
| @@ -18,11 +18,7 @@ | ||
| 18 | 18 | import org.testng.annotations.BeforeMethod; |
| 19 | 19 | import org.testng.annotations.Test; |
| 20 | 20 | |
| 21 | -import java.util.Collection; | |
| 22 | - | |
| 23 | 21 | 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; | |
| 26 | 22 | import static org.mockito.Mockito.*; |
| 27 | 23 | |
| 28 | 24 | @CreateCCM(PER_METHOD) |
| @@ -31,21 +27,14 @@ | ||
| 31 | 27 | |
| 32 | 28 | private static final int DEBOUNCE_TIME = 2000; |
| 33 | 29 | |
| 34 | - QueryOptions queryOptions; | |
| 35 | - | |
| 36 | - Cluster cluster2; | |
| 37 | - | |
| 38 | - Session session2; | |
| 30 | + private Cluster cluster2; | |
| 39 | 31 | |
| 40 | 32 | // Control Connection to be spied. |
| 41 | 33 | private ControlConnection controlConnection; |
| 42 | 34 | |
| 43 | - // Keyspaces to drop after test completes. | |
| 44 | - private Collection<String> keyspaces = newArrayList(); | |
| 45 | - | |
| 46 | 35 | @BeforeMethod(groups = "short") |
| 47 | 36 | public void setup() { |
| 48 | - queryOptions = new QueryOptions(); | |
| 37 | + QueryOptions queryOptions = new QueryOptions(); | |
| 49 | 38 | queryOptions.setRefreshNodeListIntervalMillis(DEBOUNCE_TIME); |
| 50 | 39 | queryOptions.setMaxPendingRefreshNodeListRequests(5); |
| 51 | 40 | queryOptions.setRefreshSchemaIntervalMillis(0); |
| @@ -55,7 +44,8 @@ | ||
| 55 | 44 | .withPort(ccm().getBinaryPort()) |
| 56 | 45 | .withQueryOptions(queryOptions) |
| 57 | 46 | .build()); |
| 58 | - session2 = cluster2.connect(); | |
| 47 | + | |
| 48 | + cluster2.init(); | |
| 59 | 49 | |
| 60 | 50 | // Create a spy of the Cluster's control connection and replace it with the spy. |
| 61 | 51 | controlConnection = spy(cluster2.manager.controlConnection); |
| @@ -63,23 +53,6 @@ | ||
| 63 | 53 | reset(controlConnection); |
| 64 | 54 | } |
| 65 | 55 | |
| 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 | - | |
| 83 | 56 | /** |
| 84 | 57 | * Ensures that when enough refreshNodeList requests have been received |
| 85 | 58 | * to reach {@link QueryOptions#getMaxPendingRefreshNodeListRequests()} that a |
| @@ -90,16 +63,11 @@ | ||
| 90 | 63 | */ |
| 91 | 64 | @Test(groups = "short") |
| 92 | 65 | 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"; | |
| 96 | 66 | 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(); | |
| 100 | 68 | } |
| 101 | 69 | |
| 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(); | |
| 104 | 72 | } |
| 105 | 73 | } |
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 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| 19 | +import org.testng.SkipException; | |
| 19 | 20 | import org.testng.annotations.Test; |
| 20 | 21 | |
| 21 | 22 | import static com.datastax.driver.core.ProtocolVersion.V1; |
| @@ -33,6 +34,13 @@ | ||
| 33 | 34 | .withProtocolVersion(V1); |
| 34 | 35 | } |
| 35 | 36 | |
| 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 | + | |
| 36 | 44 | /** |
| 37 | 45 | * Validates that a simple query with no variables is correctly executed. |
| 38 | 46 | * @jira_ticket JAVA-1132 |
modified driver-core/src/test/java/com/datastax/driver/core/ReadTimeoutTest.java +1 −1
| @@ -55,7 +55,7 @@ | ||
| 55 | 55 | |
| 56 | 56 | @Test(groups = "short") |
| 57 | 57 | public void should_use_statement_timeout_if_overridden() { |
| 58 | - Statement statement = new SimpleStatement(query).setReadTimeoutMillis(200); | |
| 58 | + Statement statement = new SimpleStatement(query).setReadTimeoutMillis(10000); | |
| 59 | 59 | session.execute(statement); |
| 60 | 60 | } |
| 61 | 61 |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +59 −67
| @@ -44,7 +44,9 @@ | ||
| 44 | 44 | private static final String DROP_TABLE = "DROP TABLE %s.table1"; |
| 45 | 45 | |
| 46 | 46 | /** |
| 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. | |
| 48 | 50 | */ |
| 49 | 51 | private static final long NOTIF_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(1); |
| 50 | 52 | |
| @@ -89,7 +91,7 @@ | ||
| 89 | 91 | cluster2.init(); |
| 90 | 92 | |
| 91 | 93 | cluster1.register(listener1 = mock(SchemaChangeListener.class)); |
| 92 | - cluster1.register(listener2 = mock(SchemaChangeListener.class)); | |
| 94 | + cluster2.register(listener2 = mock(SchemaChangeListener.class)); | |
| 93 | 95 | listeners = Lists.newArrayList(listener1, listener2); |
| 94 | 96 | |
| 95 | 97 | schemaDisabledCluster.register(schemaDisabledListener = mock(SchemaChangeListener.class)); |
| @@ -150,7 +152,6 @@ | ||
| 150 | 152 | .isInKeyspace(handleId(keyspace)) |
| 151 | 153 | .hasName("table1"); |
| 152 | 154 | } |
| 153 | - refreshSchema(); | |
| 154 | 155 | for (Metadata m : metadatas()) |
| 155 | 156 | assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull(); |
| 156 | 157 | } |
| @@ -166,7 +167,6 @@ | ||
| 166 | 167 | .isInKeyspace(handleId(keyspace)) |
| 167 | 168 | .hasName("table1"); |
| 168 | 169 | } |
| 169 | - refreshSchema(); | |
| 170 | 170 | for (Metadata m : metadatas()) |
| 171 | 171 | assertThat(m.getKeyspace(keyspace).getTable("table1")).hasNoColumn("j"); |
| 172 | 172 | assert added != null; |
| @@ -183,7 +183,6 @@ | ||
| 183 | 183 | .hasName("table1") |
| 184 | 184 | .hasColumn("j"); |
| 185 | 185 | } |
| 186 | - refreshSchema(); | |
| 187 | 186 | for (Metadata m : metadatas()) |
| 188 | 187 | assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j"); |
| 189 | 188 | } |
| @@ -198,14 +197,12 @@ | ||
| 198 | 197 | .hasName("table1") |
| 199 | 198 | .isInKeyspace(handleId(keyspace)); |
| 200 | 199 | } |
| 201 | - refreshSchema(); | |
| 202 | 200 | execute(DROP_TABLE, keyspace); |
| 203 | 201 | for (SchemaChangeListener listener : listeners) { |
| 204 | 202 | ArgumentCaptor<TableMetadata> removed = ArgumentCaptor.forClass(TableMetadata.class); |
| 205 | 203 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(removed.capture()); |
| 206 | 204 | assertThat(removed.getValue()).hasName("table1"); |
| 207 | 205 | } |
| 208 | - refreshSchema(); | |
| 209 | 206 | for (Metadata m : metadatas()) |
| 210 | 207 | assertThat(m.getKeyspace(keyspace).getTable("table1")).isNull(); |
| 211 | 208 | } |
| @@ -221,7 +218,6 @@ | ||
| 221 | 218 | assertThat((DataType) added.getValue()) |
| 222 | 219 | .isUserType(handleId(keyspace), "type1"); |
| 223 | 220 | } |
| 224 | - refreshSchema(); | |
| 225 | 221 | for (Metadata m : metadatas()) |
| 226 | 222 | assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNotNull(); |
| 227 | 223 | } |
| @@ -238,7 +234,6 @@ | ||
| 238 | 234 | assertThat(previous.getValue().getFieldNames()).doesNotContain("j"); |
| 239 | 235 | assertThat(current.getValue().getFieldNames()).contains("j"); |
| 240 | 236 | } |
| 241 | - refreshSchema(); | |
| 242 | 237 | for (Metadata m : metadatas()) |
| 243 | 238 | assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j")).isNotNull(); |
| 244 | 239 | } |
| @@ -254,7 +249,6 @@ | ||
| 254 | 249 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeRemoved(removed.capture()); |
| 255 | 250 | assertThat((DataType) removed.getValue()).isUserType(handleId(keyspace), "type1"); |
| 256 | 251 | } |
| 257 | - refreshSchema(); | |
| 258 | 252 | for (Metadata m : metadatas()) |
| 259 | 253 | assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNull(); |
| 260 | 254 | } |
| @@ -263,7 +257,6 @@ | ||
| 263 | 257 | @CassandraVersion(major = 2.2) |
| 264 | 258 | public void should_notify_of_function_creation(String keyspace) { |
| 265 | 259 | session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace)); |
| 266 | - | |
| 267 | 260 | for (SchemaChangeListener listener : listeners) { |
| 268 | 261 | ArgumentCaptor<FunctionMetadata> added = ArgumentCaptor.forClass(FunctionMetadata.class); |
| 269 | 262 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionAdded(added.capture()); |
| @@ -271,7 +264,6 @@ | ||
| 271 | 264 | .isInKeyspace(handleId(keyspace)) |
| 272 | 265 | .hasSignature("\"ID\"(int)"); |
| 273 | 266 | } |
| 274 | - refreshSchema(); | |
| 275 | 267 | for (Metadata m : metadatas()) |
| 276 | 268 | assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint())) |
| 277 | 269 | .isNotNull(); |
| @@ -280,47 +272,44 @@ | ||
| 280 | 272 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 281 | 273 | @CassandraVersion(major = 2.2) |
| 282 | 274 | 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 | + } | |
| 287 | 283 | 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)); | |
| 294 | 287 | for (SchemaChangeListener listener : listeners) { |
| 295 | 288 | ArgumentCaptor<FunctionMetadata> current = ArgumentCaptor.forClass(FunctionMetadata.class); |
| 296 | 289 | ArgumentCaptor<FunctionMetadata> previous = ArgumentCaptor.forClass(FunctionMetadata.class); |
| 297 | 290 | 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;"); | |
| 300 | 293 | } |
| 301 | - refreshSchema(); | |
| 302 | 294 | 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;"); | |
| 305 | 297 | } |
| 306 | 298 | |
| 307 | 299 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 308 | 300 | @CassandraVersion(major = 2.2) |
| 309 | 301 | 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)); | |
| 312 | 303 | session1.execute(String.format("DROP FUNCTION %s.\"ID\"", keyspace)); |
| 313 | - | |
| 314 | 304 | for (SchemaChangeListener listener : listeners) { |
| 315 | 305 | ArgumentCaptor<FunctionMetadata> removed = ArgumentCaptor.forClass(FunctionMetadata.class); |
| 316 | 306 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionRemoved(removed.capture()); |
| 317 | 307 | assertThat(removed.getValue()) |
| 318 | 308 | .isInKeyspace(handleId(keyspace)) |
| 319 | - .hasSignature("\"ID\"(user)"); | |
| 309 | + .hasSignature("\"ID\"(int)"); | |
| 320 | 310 | } |
| 321 | - refreshSchema(); | |
| 322 | 311 | 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())) | |
| 324 | 313 | .isNull(); |
| 325 | 314 | } |
| 326 | 315 | |
| @@ -330,7 +319,6 @@ | ||
| 330 | 319 | session1.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java" |
| 331 | 320 | + " AS 'return s+v;'", keyspace)); |
| 332 | 321 | session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0;", keyspace)); |
| 333 | - | |
| 334 | 322 | for (SchemaChangeListener listener : listeners) { |
| 335 | 323 | ArgumentCaptor<AggregateMetadata> added = ArgumentCaptor.forClass(AggregateMetadata.class); |
| 336 | 324 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateAdded(added.capture()); |
| @@ -338,7 +326,6 @@ | ||
| 338 | 326 | .isInKeyspace(handleId(keyspace)) |
| 339 | 327 | .hasSignature("\"SUM\"(int)"); |
| 340 | 328 | } |
| 341 | - refreshSchema(); | |
| 342 | 329 | for (Metadata m : metadatas()) |
| 343 | 330 | assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint())) |
| 344 | 331 | .isNotNull(); |
| @@ -350,13 +337,17 @@ | ||
| 350 | 337 | session1.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java" |
| 351 | 338 | + " AS 'return s+v;'", keyspace)); |
| 352 | 339 | 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 | + } | |
| 354 | 347 | for (Metadata m : metadatas()) |
| 355 | 348 | assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond()) |
| 356 | 349 | .isEqualTo(0); |
| 357 | - | |
| 358 | 350 | session1.execute(String.format("CREATE OR REPLACE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 1", keyspace)); |
| 359 | - | |
| 360 | 351 | for (SchemaChangeListener listener : listeners) { |
| 361 | 352 | ArgumentCaptor<AggregateMetadata> current = ArgumentCaptor.forClass(AggregateMetadata.class); |
| 362 | 353 | ArgumentCaptor<AggregateMetadata> previous = ArgumentCaptor.forClass(AggregateMetadata.class); |
| @@ -364,7 +355,6 @@ | ||
| 364 | 355 | assertThat(previous.getValue()).hasInitCond(0); |
| 365 | 356 | assertThat(current.getValue()).hasInitCond(1); |
| 366 | 357 | } |
| 367 | - refreshSchema(); | |
| 368 | 358 | for (Metadata m : metadatas()) |
| 369 | 359 | assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond()) |
| 370 | 360 | .isEqualTo(1); |
| @@ -377,7 +367,6 @@ | ||
| 377 | 367 | + " AS 'return s+v;'", keyspace)); |
| 378 | 368 | session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace)); |
| 379 | 369 | session1.execute(String.format("DROP AGGREGATE %s.\"SUM\"", keyspace)); |
| 380 | - | |
| 381 | 370 | for (SchemaChangeListener listener : listeners) { |
| 382 | 371 | ArgumentCaptor<AggregateMetadata> removed = ArgumentCaptor.forClass(AggregateMetadata.class); |
| 383 | 372 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateRemoved(removed.capture()); |
| @@ -385,8 +374,6 @@ | ||
| 385 | 374 | .isInKeyspace(handleId(keyspace)) |
| 386 | 375 | .hasSignature("\"SUM\"(int)"); |
| 387 | 376 | } |
| 388 | - | |
| 389 | - refreshSchema(); | |
| 390 | 377 | for (Metadata m : metadatas()) |
| 391 | 378 | assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint())) |
| 392 | 379 | .isNull(); |
| @@ -397,7 +384,12 @@ | ||
| 397 | 384 | public void should_notify_of_view_creation(String keyspace) { |
| 398 | 385 | session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace)); |
| 399 | 386 | 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 | + } | |
| 401 | 393 | for (Metadata m : metadatas()) |
| 402 | 394 | assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1")).isNotNull(); |
| 403 | 395 | } |
| @@ -407,12 +399,26 @@ | ||
| 407 | 399 | public void should_notify_of_view_update(String keyspace) { |
| 408 | 400 | session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace)); |
| 409 | 401 | 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 | + } | |
| 411 | 410 | for (Metadata m : metadatas()) |
| 412 | 411 | assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1").getOptions().getCompaction().get("class")).contains("SizeTieredCompactionStrategy"); |
| 413 | - | |
| 414 | 412 | 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 | + } | |
| 416 | 422 | for (Metadata m : metadatas()) |
| 417 | 423 | assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1").getOptions().getCompaction().get("class")).contains("LeveledCompactionStrategy"); |
| 418 | 424 | } |
| @@ -423,7 +429,12 @@ | ||
| 423 | 429 | session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace)); |
| 424 | 430 | 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)); |
| 425 | 431 | 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 | + } | |
| 427 | 438 | for (Metadata m : metadatas()) |
| 428 | 439 | assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1")).isNull(); |
| 429 | 440 | } |
| @@ -436,7 +447,6 @@ | ||
| 436 | 447 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture()); |
| 437 | 448 | assertThat(added.getValue()).hasName(handleId(keyspace)); |
| 438 | 449 | } |
| 439 | - refreshSchema(); | |
| 440 | 450 | for (Metadata m : metadatas()) |
| 441 | 451 | assertThat(m.getKeyspace(keyspace)).isNotNull(); |
| 442 | 452 | } |
| @@ -451,7 +461,6 @@ | ||
| 451 | 461 | assertThat(added.getValue()).hasName(handleId(keyspace)); |
| 452 | 462 | } |
| 453 | 463 | assert added != null; |
| 454 | - refreshSchema(); | |
| 455 | 464 | for (Metadata m : metadatas()) |
| 456 | 465 | assertThat(m.getKeyspace(keyspace).isDurableWrites()).isTrue(); |
| 457 | 466 | execute(ALTER_KEYSPACE, keyspace); |
| @@ -466,7 +475,6 @@ | ||
| 466 | 475 | .hasName(handleId(keyspace)) |
| 467 | 476 | .isNotDurableWrites(); |
| 468 | 477 | } |
| 469 | - refreshSchema(); | |
| 470 | 478 | for (Metadata m : metadatas()) |
| 471 | 479 | assertThat(m.getKeyspace(keyspace)).isNotDurableWrites(); |
| 472 | 480 | } |
| @@ -474,14 +482,11 @@ | ||
| 474 | 482 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| 475 | 483 | public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedException { |
| 476 | 484 | execute(CREATE_KEYSPACE, keyspace); |
| 477 | - ArgumentCaptor<KeyspaceMetadata> added = null; | |
| 478 | 485 | for (SchemaChangeListener listener : listeners) { |
| 479 | - added = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 486 | + ArgumentCaptor<KeyspaceMetadata> added = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 480 | 487 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture()); |
| 481 | 488 | assertThat(added.getValue()).hasName(handleId(keyspace)); |
| 482 | 489 | } |
| 483 | - assert added != null; | |
| 484 | - refreshSchema(); | |
| 485 | 490 | for (Metadata m : metadatas()) |
| 486 | 491 | assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isNotEmpty(); |
| 487 | 492 | execute(CREATE_TABLE, keyspace); // to test table drop notifications |
| @@ -497,14 +502,12 @@ | ||
| 497 | 502 | assertThat(ks.getValue()) |
| 498 | 503 | .hasName(handleId(keyspace)); |
| 499 | 504 | } |
| 500 | - refreshSchema(); | |
| 501 | 505 | for (Metadata m : metadatas()) { |
| 502 | 506 | assertThat(m.getKeyspace(keyspace)).isNull(); |
| 503 | 507 | assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isEmpty(); |
| 504 | 508 | } |
| 505 | 509 | } |
| 506 | 510 | |
| 507 | - | |
| 508 | 511 | /** |
| 509 | 512 | * Ensures that calling {@link Metadata#newToken(String)} on a Cluster that has schema |
| 510 | 513 | * metadata disabled will throw a {@link IllegalStateException}. |
| @@ -588,7 +591,6 @@ | ||
| 588 | 591 | schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true); |
| 589 | 592 | |
| 590 | 593 | verify(schemaDisabledControlConnection, after(1000)).refreshSchema(null, null, null, null); |
| 591 | - verify(schemaDisabledControlConnection).refreshNodeListAndTokenMap(); | |
| 592 | 594 | |
| 593 | 595 | // Ensure that there is schema metadata. |
| 594 | 596 | assertThat(schemaDisabledCluster.getMetadata().getKeyspace(keyspace)).isNotNull(); |
| @@ -604,7 +606,6 @@ | ||
| 604 | 606 | reset(schemaDisabledControlConnection); |
| 605 | 607 | schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true); |
| 606 | 608 | verify(schemaDisabledControlConnection, after(1000).never()).refreshSchema(null, null, null, null); |
| 607 | - verify(schemaDisabledControlConnection, never()).refreshNodeListAndTokenMap(); | |
| 608 | 609 | } finally { |
| 609 | 610 | // Reset listener mock to not count it's interactions in this test. |
| 610 | 611 | reset(schemaDisabledListener); |
| @@ -643,13 +644,4 @@ | ||
| 643 | 644 | return Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata()); |
| 644 | 645 | } |
| 645 | 646 | |
| 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 | - | |
| 655 | 647 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +4 −1
| @@ -17,7 +17,6 @@ | ||
| 17 | 17 | |
| 18 | 18 | import org.mockito.ArgumentCaptor; |
| 19 | 19 | import org.testng.SkipException; |
| 20 | -import org.testng.annotations.AfterMethod; | |
| 21 | 20 | import org.testng.annotations.BeforeMethod; |
| 22 | 21 | import org.testng.annotations.Test; |
| 23 | 22 | |
| @@ -249,6 +248,8 @@ | ||
| 249 | 248 | String prefix = TestUtils.generateIdentifier("ks_"); |
| 250 | 249 | for (int i = 0; i < 3; i++) { |
| 251 | 250 | 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(); | |
| 252 | 253 | } |
| 253 | 254 | |
| 254 | 255 | verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class)); |
| @@ -275,6 +276,8 @@ | ||
| 275 | 276 | String prefix = TestUtils.generateIdentifier("ks_"); |
| 276 | 277 | for (int i = 0; i < 5; i++) { |
| 277 | 278 | 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(); | |
| 278 | 281 | } |
| 279 | 282 | |
| 280 | 283 | // 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 @@ | ||
| 34 | 34 | |
| 35 | 35 | SocketChannelMonitor channelMonitor; |
| 36 | 36 | |
| 37 | - @Test(groups = "short") | |
| 37 | + @Test(groups = "long") | |
| 38 | 38 | public void connectionLeakTest() throws Exception { |
| 39 | 39 | // Checking for JAVA-342 |
| 40 | 40 | channelMonitor = new SocketChannelMonitor(); |
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +25 −12
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | import org.mockito.Mockito; |
| 21 | 21 | import org.testng.annotations.Test; |
| 22 | 22 | |
| 23 | -import static org.assertj.core.api.Assertions.assertThat; | |
| 23 | +import static org.assertj.core.api.Assertions.fail; | |
| 24 | 24 | import static org.mockito.Mockito.times; |
| 25 | 25 | |
| 26 | 26 | /** |
| @@ -41,8 +41,7 @@ | ||
| 41 | 41 | timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE); |
| 42 | 42 | return Cluster.builder() |
| 43 | 43 | .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 | |
| 46 | 45 | .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2)); |
| 47 | 46 | } |
| 48 | 47 | |
| @@ -58,16 +57,30 @@ | ||
| 58 | 57 | public void should_use_same_default_timestamp_for_all_executions() { |
| 59 | 58 | Metrics.Errors errors = cluster().getMetrics().getErrorMetrics(); |
| 60 | 59 | |
| 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 | + } | |
| 67 | 80 | } |
| 68 | - session().execute(batch); | |
| 69 | 81 | |
| 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 | + } | |
| 72 | 85 | } |
| 73 | 86 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +1 −0
| @@ -123,6 +123,7 @@ | ||
| 123 | 123 | ResultSet rs = session.execute(statement); |
| 124 | 124 | Row row = rs.one(); |
| 125 | 125 | |
| 126 | + assertThat(row).isNotNull(); | |
| 126 | 127 | assertThat(row.getString("result")).isEqualTo("result1"); |
| 127 | 128 | assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount); |
| 128 | 129 | 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 @@ | ||
| 61 | 61 | return Cluster.builder() |
| 62 | 62 | .addContactPoints(getContactPoints().get(0)) |
| 63 | 63 | .withPort(ccm().getBinaryPort()) |
| 64 | - .withLoadBalancingPolicy(lbp) | |
| 65 | - .withQueryOptions(TestUtils.nonDebouncingQueryOptions()); | |
| 64 | + .withLoadBalancingPolicy(lbp); | |
| 66 | 65 | } |
| 67 | 66 | |
| 68 | 67 | @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 @@ | ||
| 17 | 17 | |
| 18 | 18 | import org.testng.annotations.Test; |
| 19 | 19 | |
| 20 | -import static org.testng.Assert.assertEquals; | |
| 20 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 21 | 21 | |
| 22 | 22 | public class VersionNumberTest { |
| 23 | 23 | |
| 24 | 24 | @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); | |
| 54 | 103 | } |
| 55 | 104 | } |
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 @@ | ||
| 88 | 88 | fail("expected an OperationTimedOutException"); |
| 89 | 89 | } catch (OperationTimedOutException e) { |
| 90 | 90 | 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()) | |
| 92 | 92 | ); |
| 93 | 93 | } |
| 94 | 94 | assertOnRequestErrorWasCalled(1, OperationTimedOutException.class); |
| @@ -131,7 +131,7 @@ | ||
| 131 | 131 | fail("expected a TransportException"); |
| 132 | 132 | } catch (TransportException e) { |
| 133 | 133 | assertThat(e.getMessage()).isEqualTo( |
| 134 | - String.format("[%s] Connection has been closed", host1.getAddress()) | |
| 134 | + String.format("[%s] Connection has been closed", host1.getSocketAddress()) | |
| 135 | 135 | ); |
| 136 | 136 | } |
| 137 | 137 | assertOnRequestErrorWasCalled(1, TransportException.class); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +3 −3
| @@ -187,9 +187,9 @@ | ||
| 187 | 187 | .hasOnlyElementsOfType(OperationTimedOutException.class) |
| 188 | 188 | .extractingResultOf("getMessage") |
| 189 | 189 | .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()) | |
| 193 | 193 | ); |
| 194 | 194 | } |
| 195 | 195 | assertOnRequestErrorWasCalled(3, OperationTimedOutException.class); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +3 −3
| @@ -383,9 +383,9 @@ | ||
| 383 | 383 | .hasOnlyElementsOfType(OperationTimedOutException.class) |
| 384 | 384 | .extractingResultOf("getMessage") |
| 385 | 385 | .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()) | |
| 389 | 389 | ); |
| 390 | 390 | } |
| 391 | 391 | assertOnRequestErrorWasCalled(3, OperationTimedOutException.class); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +2 −2
| @@ -96,7 +96,7 @@ | ||
| 96 | 96 | Fail.fail("expected an OperationTimedOutException"); |
| 97 | 97 | } catch (OperationTimedOutException e) { |
| 98 | 98 | 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()) | |
| 100 | 100 | ); |
| 101 | 101 | } |
| 102 | 102 | assertOnRequestErrorWasCalled(1, OperationTimedOutException.class); |
| @@ -139,7 +139,7 @@ | ||
| 139 | 139 | Fail.fail("expected a TransportException"); |
| 140 | 140 | } catch (TransportException e) { |
| 141 | 141 | assertThat(e.getMessage()).isEqualTo( |
| 142 | - String.format("[%s] Connection has been closed", host1.getAddress()) | |
| 142 | + String.format("[%s] Connection has been closed", host1.getSocketAddress()) | |
| 143 | 143 | ); |
| 144 | 144 | } |
| 145 | 145 | assertOnRequestErrorWasCalled(1, TransportException.class); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java +21 −2
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | 19 | import com.datastax.driver.core.exceptions.*; |
| 20 | 20 | import org.assertj.core.api.Fail; |
| 21 | +import org.mockito.Mockito; | |
| 21 | 22 | import org.scassandra.http.client.ClosedConnectionConfig; |
| 22 | 23 | import org.scassandra.http.client.PrimingRequest; |
| 23 | 24 | import org.scassandra.http.client.Result; |
| @@ -87,7 +88,7 @@ | ||
| 87 | 88 | fail("expected an OperationTimedOutException"); |
| 88 | 89 | } catch (OperationTimedOutException e) { |
| 89 | 90 | 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()) | |
| 91 | 92 | ); |
| 92 | 93 | } |
| 93 | 94 | assertOnRequestErrorWasCalled(1, OperationTimedOutException.class); |
| @@ -179,7 +180,7 @@ | ||
| 179 | 180 | Fail.fail("expected a TransportException"); |
| 180 | 181 | } catch (TransportException e) { |
| 181 | 182 | assertThat(e.getMessage()).isEqualTo( |
| 182 | - String.format("[%s] Connection has been closed", host1.getAddress()) | |
| 183 | + String.format("[%s] Connection has been closed", host1.getSocketAddress()) | |
| 183 | 184 | ); |
| 184 | 185 | } |
| 185 | 186 | assertOnRequestErrorWasCalled(1, TransportException.class); |
| @@ -218,6 +219,24 @@ | ||
| 218 | 219 | assertQueried(3, 1); |
| 219 | 220 | } |
| 220 | 221 | |
| 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 | + | |
| 221 | 240 | |
| 222 | 241 | /** |
| 223 | 242 | * 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 @@ | ||
| 20 | 20 | import com.datastax.driver.core.exceptions.ServerError; |
| 21 | 21 | import org.apache.log4j.Level; |
| 22 | 22 | import org.apache.log4j.Logger; |
| 23 | +import org.mockito.Mockito; | |
| 23 | 24 | import org.slf4j.helpers.MessageFormatter; |
| 24 | 25 | import org.testng.annotations.AfterMethod; |
| 25 | 26 | import org.testng.annotations.BeforeClass; |
| @@ -54,7 +55,7 @@ | ||
| 54 | 55 | setRetryPolicy(new LoggingRetryPolicy(new CustomRetryPolicy())); |
| 55 | 56 | } |
| 56 | 57 | |
| 57 | - @BeforeMethod(groups = {"short", "unit"}) | |
| 58 | + @BeforeMethod(groups = {"short"}) | |
| 58 | 59 | public void storeDefaultCL() { |
| 59 | 60 | defaultCL = cluster.getConfiguration().getQueryOptions().getConsistencyLevel(); |
| 60 | 61 | } |
| @@ -144,6 +145,24 @@ | ||
| 144 | 145 | assertThat(line.trim()).isEqualTo(expectedMessage(RETRYING_ON_REQUEST_ERROR, "next host", LOCAL_ONE, defaultCL, 0, new ServerError(host1.getSocketAddress(), "Server Error"))); |
| 145 | 146 | } |
| 146 | 147 | |
| 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 | + | |
| 147 | 166 | private String expectedMessage(String template, Object... args) { |
| 148 | 167 | return MessageFormatter.arrayFormat(template, args).getMessage(); |
| 149 | 168 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +29 −11
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.ConsistencyLevel; |
| 19 | -import com.datastax.driver.core.Metadata; | |
| 19 | +import com.datastax.driver.core.TableMetadata; | |
| 20 | 20 | import com.datastax.driver.core.TypeCodec; |
| 21 | 21 | import com.datastax.driver.core.UserType; |
| 22 | 22 | import com.datastax.driver.mapping.MethodMapper.ParamMapper; |
| @@ -31,6 +31,8 @@ | ||
| 31 | 31 | import java.util.*; |
| 32 | 32 | import java.util.concurrent.atomic.AtomicInteger; |
| 33 | 33 | |
| 34 | +import static com.datastax.driver.core.Metadata.quote; | |
| 35 | + | |
| 34 | 36 | /** |
| 35 | 37 | * Static metods that facilitates parsing class annotations into the corresponding {@link EntityMapper}. |
| 36 | 38 | */ |
| @@ -66,6 +68,10 @@ | ||
| 66 | 68 | } |
| 67 | 69 | |
| 68 | 70 | 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)); | |
| 69 | 75 | |
| 70 | 76 | List<Field> pks = new ArrayList<Field>(); |
| 71 | 77 | List<Field> ccs = new ArrayList<Field>(); |
| @@ -106,18 +112,24 @@ | ||
| 106 | 112 | validateOrder(pks, "@PartitionKey"); |
| 107 | 113 | validateOrder(ccs, "@ClusteringColumn"); |
| 108 | 114 | |
| 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)); | |
| 112 | 119 | return mapper; |
| 113 | 120 | } |
| 114 | 121 | |
| 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) { | |
| 116 | 123 | List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size()); |
| 117 | 124 | for (int i = 0; i < fields.size(); i++) { |
| 118 | 125 | Field field = fields.get(i); |
| 119 | 126 | 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)); | |
| 121 | 133 | } |
| 122 | 134 | return mappers; |
| 123 | 135 | } |
| @@ -126,7 +138,7 @@ | ||
| 126 | 138 | UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass); |
| 127 | 139 | |
| 128 | 140 | 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(); | |
| 130 | 142 | |
| 131 | 143 | if (Strings.isNullOrEmpty(udt.keyspace())) { |
| 132 | 144 | ksName = mappingManager.getSession().getLoggedKeyspace(); |
| @@ -139,6 +151,8 @@ | ||
| 139 | 151 | } |
| 140 | 152 | |
| 141 | 153 | 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)); | |
| 142 | 156 | |
| 143 | 157 | List<Field> columns = new ArrayList<Field>(); |
| 144 | 158 | |
| @@ -163,17 +177,21 @@ | ||
| 163 | 177 | break; |
| 164 | 178 | } |
| 165 | 179 | } |
| 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); | |
| 167 | 181 | return new MappedUDTCodec<T>(userType, udtClass, columnMappers, mappingManager); |
| 168 | 182 | } |
| 169 | 183 | |
| 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) { | |
| 171 | 185 | Map<String, ColumnMapper<T>> mappers = Maps.newHashMapWithExpectedSize(fields.size()); |
| 172 | 186 | for (int i = 0; i < fields.size(); i++) { |
| 173 | 187 | Field field = fields.get(i); |
| 174 | 188 | 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())); | |
| 177 | 195 | } |
| 178 | 196 | return mappers; |
| 179 | 197 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +4 −0
| @@ -46,6 +46,10 @@ | ||
| 46 | 46 | } |
| 47 | 47 | } |
| 48 | 48 | |
| 49 | + Class<T> getUdtClass() { | |
| 50 | + return udtClass; | |
| 51 | + } | |
| 52 | + | |
| 49 | 53 | @Override |
| 50 | 54 | protected ByteBuffer serializeField(T source, String fieldName, ProtocolVersion protocolVersion) { |
| 51 | 55 | // 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 @@ | ||
| 141 | 141 | return getPreparedQueryAsync(type, Collections.<ColumnMapper<?>>emptySet(), options); |
| 142 | 142 | } |
| 143 | 143 | |
| 144 | + Class<T> getMappedClass() { | |
| 145 | + return klass; | |
| 146 | + } | |
| 147 | + | |
| 144 | 148 | /** |
| 145 | 149 | * The {@code TableMetadata} for this mapper. |
| 146 | 150 | * |
| @@ -921,7 +925,7 @@ | ||
| 921 | 925 | |
| 922 | 926 | static class Ttl extends Option { |
| 923 | 927 | |
| 924 | - private int ttlValue; | |
| 928 | + private final int ttlValue; | |
| 925 | 929 | |
| 926 | 930 | Ttl(int value) { |
| 927 | 931 | super(Type.TTL); |
| @@ -957,7 +961,7 @@ | ||
| 957 | 961 | |
| 958 | 962 | static class Timestamp extends Option { |
| 959 | 963 | |
| 960 | - private long tsValue; | |
| 964 | + private final long tsValue; | |
| 961 | 965 | |
| 962 | 966 | Timestamp(long value) { |
| 963 | 967 | super(Type.TIMESTAMP); |
| @@ -993,7 +997,7 @@ | ||
| 993 | 997 | |
| 994 | 998 | static class ConsistencyLevelOption extends Option { |
| 995 | 999 | |
| 996 | - private ConsistencyLevel cl; | |
| 1000 | + private final ConsistencyLevel cl; | |
| 997 | 1001 | |
| 998 | 1002 | ConsistencyLevelOption(ConsistencyLevel cl) { |
| 999 | 1003 | super(Type.CL); |
| @@ -1029,7 +1033,7 @@ | ||
| 1029 | 1033 | |
| 1030 | 1034 | static class Tracing extends Option { |
| 1031 | 1035 | |
| 1032 | - private boolean tracing; | |
| 1036 | + private final boolean tracing; | |
| 1033 | 1037 | |
| 1034 | 1038 | Tracing(boolean tracing) { |
| 1035 | 1039 | super(Type.TRACING); |
| @@ -1066,7 +1070,7 @@ | ||
| 1066 | 1070 | |
| 1067 | 1071 | static class SaveNullFields extends Option { |
| 1068 | 1072 | |
| 1069 | - private boolean saveNullFields; | |
| 1073 | + private final boolean saveNullFields; | |
| 1070 | 1074 | |
| 1071 | 1075 | SaveNullFields(boolean saveNullFields) { |
| 1072 | 1076 | super(SAVE_NULL_FIELDS); |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +78 −6
| @@ -15,22 +15,22 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 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.*; | |
| 21 | 19 | import com.datastax.driver.mapping.annotations.Accessor; |
| 22 | 20 | import com.datastax.driver.mapping.annotations.Table; |
| 23 | 21 | import com.datastax.driver.mapping.annotations.UDT; |
| 22 | +import org.slf4j.Logger; | |
| 23 | +import org.slf4j.LoggerFactory; | |
| 24 | 24 | |
| 25 | -import java.util.Collections; | |
| 26 | -import java.util.HashMap; | |
| 27 | -import java.util.Map; | |
| 25 | +import java.util.*; | |
| 28 | 26 | |
| 29 | 27 | /** |
| 30 | 28 | * Mapping manager from which to obtain entity mappers. |
| 31 | 29 | */ |
| 32 | 30 | public class MappingManager { |
| 33 | 31 | |
| 32 | + private static final Logger LOGGER = LoggerFactory.getLogger(MappingManager.class); | |
| 33 | + | |
| 34 | 34 | private final Session session; |
| 35 | 35 | final boolean isCassandraV1; |
| 36 | 36 | |
| @@ -74,6 +74,78 @@ | ||
| 74 | 74 | // which nodes might join the cluster later. |
| 75 | 75 | // At least if protocol >=2 we know there won't be any 1.2 nodes ever. |
| 76 | 76 | 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 | + }); | |
| 77 | 149 | } |
| 78 | 150 | |
| 79 | 151 | /** |
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 @@ | ||
| 71 | 71 | // create a second cluster to perform everything asynchronously, |
| 72 | 72 | // including session initialization |
| 73 | 73 | Cluster cluster2 = register( |
| 74 | - createClusterBuilderNoDebouncing() | |
| 74 | + createClusterBuilder() | |
| 75 | 75 | .addContactPoints(getContactPoints()) |
| 76 | 76 | .withPort(ccm().getBinaryPort()) |
| 77 | 77 | .build()); |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCompositeKeyTest.java +1 −1
| @@ -32,7 +32,7 @@ | ||
| 32 | 32 | } |
| 33 | 33 | |
| 34 | 34 | @SuppressWarnings("unused") |
| 35 | - @Table(keyspace = "ks", name = "test_table") | |
| 35 | + @Table(name = "test_table") | |
| 36 | 36 | public static class TestTable { |
| 37 | 37 | @PartitionKey(0) |
| 38 | 38 | private int pk1; |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +3 −14
| @@ -17,7 +17,6 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | 19 | import com.datastax.driver.core.exceptions.CodecNotFoundException; |
| 20 | -import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 21 | 20 | import com.datastax.driver.core.utils.CassandraVersion; |
| 22 | 21 | import com.datastax.driver.mapping.annotations.*; |
| 23 | 22 | import org.testng.SkipException; |
| @@ -26,7 +25,6 @@ | ||
| 26 | 25 | |
| 27 | 26 | import static com.datastax.driver.core.Assertions.assertThat; |
| 28 | 27 | import static com.datastax.driver.core.ProtocolVersion.V1; |
| 29 | -import static org.assertj.core.api.Assertions.fail; | |
| 30 | 28 | |
| 31 | 29 | /** |
| 32 | 30 | * Tests to ensure validity of {@link com.datastax.driver.mapping.annotations.Computed} |
| @@ -54,7 +52,7 @@ | ||
| 54 | 52 | userMapper = mappingManager.mapper(User.class); |
| 55 | 53 | } |
| 56 | 54 | |
| 57 | - @Test(groups = "short", expectedExceptions = {UnsupportedOperationException.class}) | |
| 55 | + @Test(groups = "short", expectedExceptions = UnsupportedOperationException.class) | |
| 58 | 56 | void should_get_unsupported_operation_exception_on_v1() { |
| 59 | 57 | if (protocolVersion.compareTo(V1) > 0) |
| 60 | 58 | throw new SkipException("Skipped when protocol version > V1"); |
| @@ -129,19 +127,10 @@ | ||
| 129 | 127 | User_WrongComputedType user = mapper.get("testlogin"); |
| 130 | 128 | } |
| 131 | 129 | |
| 132 | - @Test(groups = "short") | |
| 130 | + @Test(groups = "short", expectedExceptions = IllegalArgumentException.class) | |
| 133 | 131 | @CassandraVersion(major = 2.0) |
| 134 | 132 | 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); | |
| 145 | 134 | } |
| 146 | 135 | |
| 147 | 136 | @Table(name = "user") |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +69 −0
| @@ -503,4 +503,73 @@ | ||
| 503 | 503 | assertThat(saveQuery.isIdempotent()).isTrue(); |
| 504 | 504 | } |
| 505 | 505 | |
| 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 | + } | |
| 506 | 575 | } |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +363 −6
| @@ -17,34 +17,39 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | 19 | import com.datastax.driver.core.exceptions.CodecNotFoundException; |
| 20 | +import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 20 | 21 | import com.datastax.driver.core.utils.CassandraVersion; |
| 21 | 22 | import com.datastax.driver.core.utils.UUIDs; |
| 22 | 23 | import com.datastax.driver.mapping.annotations.*; |
| 23 | 24 | import com.google.common.base.Objects; |
| 24 | 25 | import com.google.common.collect.Maps; |
| 25 | 26 | import org.assertj.core.data.MapEntry; |
| 27 | +import org.testng.annotations.AfterMethod; | |
| 26 | 28 | import org.testng.annotations.BeforeMethod; |
| 27 | 29 | import org.testng.annotations.Test; |
| 28 | 30 | |
| 29 | 31 | import java.util.*; |
| 30 | 32 | |
| 33 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 31 | 34 | import static org.assertj.core.api.Assertions.assertThat; |
| 32 | 35 | import static org.assertj.core.api.Assertions.fail; |
| 33 | 36 | import static org.testng.Assert.*; |
| 34 | 37 | |
| 35 | -@SuppressWarnings("unused") | |
| 38 | +@SuppressWarnings({"unused", "WeakerAccess"}) | |
| 36 | 39 | @CassandraVersion(major = 2.1) |
| 40 | +@CreateCCM(PER_METHOD) | |
| 37 | 41 | public class MapperUDTTest extends CCMTestsSupport { |
| 38 | 42 | |
| 39 | - @Override | |
| 40 | - public void onTestContextInitialized() { | |
| 43 | + @BeforeMethod(groups = "short") | |
| 44 | + public void createObjects() { | |
| 41 | 45 | execute("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)", |
| 42 | 46 | "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)"); |
| 43 | 47 | } |
| 44 | 48 | |
| 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"); | |
| 48 | 53 | } |
| 49 | 54 | |
| 50 | 55 | @Table(name = "users", |
| @@ -371,4 +376,356 @@ | ||
| 371 | 376 | Map<String, Address> otherAddresses = row.getMap("other_addresses", String.class, Address.class); |
| 372 | 377 | assertThat(otherAddresses).containsOnly(MapEntry.entry("condo", expectedOtherAddress)); |
| 373 | 378 | } |
| 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 | + | |
| 374 | 731 | } |
modified driver-tests/osgi/pom.xml +17 −1
| @@ -34,6 +34,7 @@ | ||
| 34 | 34 | <felix.version>4.6.0</felix.version> |
| 35 | 35 | <!-- more recent version require JDK7+ --> |
| 36 | 36 | <pax-exam.version>3.6.0</pax-exam.version> |
| 37 | + <url.version>2.4.0</url.version> | |
| 37 | 38 | <logback.version>1.1.3</logback.version> |
| 38 | 39 | <test.groups>none</test.groups> |
| 39 | 40 | <!-- |
| @@ -71,6 +72,12 @@ | ||
| 71 | 72 | <version>${felix.version}</version> |
| 72 | 73 | </dependency> |
| 73 | 74 | |
| 75 | + <dependency> | |
| 76 | + <groupId>org.slf4j</groupId> | |
| 77 | + <artifactId>slf4j-api</artifactId> | |
| 78 | + <version>1.7.5</version> | |
| 79 | + </dependency> | |
| 80 | + | |
| 74 | 81 | <dependency> |
| 75 | 82 | <groupId>com.datastax.cassandra</groupId> |
| 76 | 83 | <artifactId>cassandra-driver-core</artifactId> |
| @@ -95,7 +102,7 @@ | ||
| 95 | 102 | |
| 96 | 103 | <dependency> |
| 97 | 104 | <groupId>org.ops4j.pax.exam</groupId> |
| 98 | - <artifactId>pax-exam-container-native</artifactId> | |
| 105 | + <artifactId>pax-exam-container-forked</artifactId> | |
| 99 | 106 | <version>${pax-exam.version}</version> |
| 100 | 107 | <scope>test</scope> |
| 101 | 108 | </dependency> |
| @@ -107,6 +114,13 @@ | ||
| 107 | 114 | <scope>test</scope> |
| 108 | 115 | </dependency> |
| 109 | 116 | |
| 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 | + | |
| 110 | 124 | <dependency> |
| 111 | 125 | <groupId>javax.transaction</groupId> |
| 112 | 126 | <artifactId>jta</artifactId> |
| @@ -146,12 +160,14 @@ | ||
| 146 | 160 | <groupId>ch.qos.logback</groupId> |
| 147 | 161 | <artifactId>logback-classic</artifactId> |
| 148 | 162 | <version>${logback.version}</version> |
| 163 | + <scope>test</scope> | |
| 149 | 164 | </dependency> |
| 150 | 165 | |
| 151 | 166 | <dependency> |
| 152 | 167 | <groupId>ch.qos.logback</groupId> |
| 153 | 168 | <artifactId>logback-core</artifactId> |
| 154 | 169 | <version>${logback.version}</version> |
| 170 | + <scope>test</scope> | |
| 155 | 171 | </dependency> |
| 156 | 172 | |
| 157 | 173 | </dependencies> |
modified driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java +39 −7
| @@ -15,42 +15,73 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.osgi.impl; |
| 17 | 17 | |
| 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.*; | |
| 22 | 19 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 20 | +import com.datastax.driver.core.policies.PercentileSpeculativeExecutionPolicy; | |
| 23 | 21 | import com.datastax.driver.extras.codecs.date.SimpleTimestampCodec; |
| 24 | 22 | import com.datastax.driver.osgi.api.MailboxService; |
| 25 | 23 | import org.osgi.framework.BundleActivator; |
| 26 | 24 | import org.osgi.framework.BundleContext; |
| 25 | +import org.slf4j.Logger; | |
| 26 | +import org.slf4j.LoggerFactory; | |
| 27 | 27 | |
| 28 | 28 | import java.util.Hashtable; |
| 29 | 29 | |
| 30 | +import static com.datastax.driver.core.ProtocolOptions.Compression.LZ4; | |
| 30 | 31 | import static com.datastax.driver.osgi.api.MailboxMessage.TABLE; |
| 31 | 32 | |
| 32 | 33 | public class Activator implements BundleActivator { |
| 33 | 34 | |
| 35 | + private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class); | |
| 36 | + | |
| 34 | 37 | private Cluster cluster; |
| 35 | 38 | |
| 36 | 39 | @Override |
| 37 | 40 | public void start(BundleContext context) throws Exception { |
| 41 | + | |
| 42 | + VersionNumber ver = VersionNumber.parse(context.getProperty("cassandra.version")); | |
| 43 | + LOGGER.info("C* version: {}", ver); | |
| 44 | + | |
| 38 | 45 | String contactPointsStr = context.getProperty("cassandra.contactpoints"); |
| 39 | 46 | if (contactPointsStr == null) { |
| 40 | 47 | contactPointsStr = "127.0.0.1"; |
| 41 | 48 | } |
| 49 | + LOGGER.info("Contact points: {}", contactPointsStr); | |
| 42 | 50 | String[] contactPoints = contactPointsStr.split(","); |
| 43 | 51 | |
| 44 | 52 | String keyspace = context.getProperty("cassandra.keyspace"); |
| 45 | 53 | if (keyspace == null) { |
| 46 | 54 | keyspace = "mailbox"; |
| 47 | 55 | } |
| 56 | + LOGGER.info("Keyspace: {}", keyspace); | |
| 48 | 57 | keyspace = Metadata.quote(keyspace); |
| 49 | 58 | |
| 50 | - cluster = Cluster.builder() | |
| 59 | + Cluster.Builder builder = Cluster.builder() | |
| 51 | 60 | .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(); | |
| 54 | 85 | |
| 55 | 86 | Session session; |
| 56 | 87 | try { |
| @@ -73,6 +104,7 @@ | ||
| 73 | 104 | mailbox.init(); |
| 74 | 105 | |
| 75 | 106 | context.registerService(MailboxService.class.getName(), mailbox, new Hashtable<String, String>()); |
| 107 | + LOGGER.info("Mailbox Service successfully initialized"); | |
| 76 | 108 | } |
| 77 | 109 | |
| 78 | 110 | @Override |
modified driver-tests/osgi/src/test/java/com/datastax/driver/osgi/BundleOptions.java +17 −0
| @@ -15,6 +15,8 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.osgi; |
| 17 | 17 | |
| 18 | +import com.datastax.driver.core.CCMBridge; | |
| 19 | +import com.datastax.driver.core.ProtocolOptions; | |
| 18 | 20 | import com.datastax.driver.core.TestUtils; |
| 19 | 21 | import org.ops4j.pax.exam.Option; |
| 20 | 22 | import org.ops4j.pax.exam.options.CompositeOption; |
| @@ -48,6 +50,19 @@ | ||
| 48 | 50 | return mavenBundle("com.google.guava", "guava", "16.0.1"); |
| 49 | 51 | } |
| 50 | 52 | |
| 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 | + | |
| 51 | 66 | public static CompositeOption nettyBundles() { |
| 52 | 67 | final String nettyVersion = "4.0.33.Final"; |
| 53 | 68 | return new CompositeOption() { |
| @@ -78,12 +93,14 @@ | ||
| 78 | 93 | // Delegate javax.security.cert to the parent classloader. javax.security.cert.X509Certificate is used in |
| 79 | 94 | // io.netty.util.internal.EmptyArrays, but not directly by the driver. |
| 80 | 95 | bootDelegationPackage("javax.security.cert"), |
| 96 | + systemProperty("cassandra.version").value(CCMBridge.getCassandraVersion()), | |
| 81 | 97 | systemProperty("cassandra.contactpoints").value(TestUtils.IP_PREFIX + 1), |
| 82 | 98 | systemProperty("logback.configurationFile").value("file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"), |
| 83 | 99 | mavenBundle("org.slf4j", "slf4j-api", "1.7.5"), |
| 84 | 100 | mavenBundle("ch.qos.logback", "logback-classic", "1.1.3"), |
| 85 | 101 | mavenBundle("ch.qos.logback", "logback-core", "1.1.3"), |
| 86 | 102 | mavenBundle("io.dropwizard.metrics", "metrics-core", "3.1.2"), |
| 103 | + mavenBundle("org.testng", "testng", "6.8.8"), | |
| 87 | 104 | systemPackages("org.testng", "org.junit", "org.junit.runner", "org.junit.runner.manipulation", |
| 88 | 105 | "org.junit.runner.notification", "com.jcabi.manifests") |
| 89 | 106 | ); |
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 @@ | ||
| 88 | 88 | ``` |
| 89 | 89 | |
| 90 | 90 | |
| 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 | + | |
| 91 | 102 | ### Can I get the raw bytes of a text column? |
| 92 | 103 | |
| 93 | 104 | 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 @@ | ||
| 27 | 27 | <dependency> |
| 28 | 28 | <groupId>net.jpountz.lz4</groupId> |
| 29 | 29 | <artifactId>lz4</artifactId> |
| 30 | - <version>1.2.0</version> | |
| 30 | + <version>1.3.0</version> | |
| 31 | 31 | </dependency> |
| 32 | 32 | ``` |
| 33 | 33 |
modified manual/ssl/README.md +6 −2
| @@ -152,8 +152,12 @@ | ||
| 152 | 152 | [these instructions](http://netty.io/wiki/forked-tomcat-native.html) to |
| 153 | 153 | add it to your dependencies. |
| 154 | 154 | |
| 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. | |
| 157 | 161 | |
| 158 | 162 | ##### Configuring the context |
| 159 | 163 |
modified manual/statements/prepared/README.md +40 −3
| @@ -118,7 +118,7 @@ | ||
| 118 | 118 | ```java |
| 119 | 119 | BoundStatement bound = ps1.bind() |
| 120 | 120 | .setString("sku", "324378") |
| 121 | - .setString("description", "LCD screen") | |
| 121 | + .setString("description", "LCD screen"); | |
| 122 | 122 | |
| 123 | 123 | // Using the unset method to unset previously set value. |
| 124 | 124 | // Positional setter: |
| @@ -133,8 +133,27 @@ | ||
| 133 | 133 | serialized form. |
| 134 | 134 | |
| 135 | 135 | `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 | + | |
| 138 | 157 | Also, make sure you don't accidentally reuse parameters from previous executions. |
| 139 | 158 | |
| 140 | 159 | ### Preparing on multiple nodes |
| @@ -222,9 +241,27 @@ | ||
| 222 | 241 | specific situations; read each method's Javadoc for detailed |
| 223 | 242 | explanations. |
| 224 | 243 | |
| 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 | + | |
| 225 | 260 | [PreparedStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PreparedStatement.html |
| 226 | 261 | [BoundStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BoundStatement.html |
| 227 | 262 | [setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts-boolean- |
| 228 | 263 | [setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp-boolean- |
| 229 | 264 | [execute]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement- |
| 230 | 265 | [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 @@ | ||
| 52 | 52 | <log4j.version>1.2.17</log4j.version> |
| 53 | 53 | <slf4j-log4j12.version>1.7.6</slf4j-log4j12.version> |
| 54 | 54 | <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> | |
| 56 | 56 | <metrics.version>3.1.2</metrics.version> |
| 57 | 57 | <snappy.version>1.0.5</snappy.version> |
| 58 | - <lz4.version>1.2.0</lz4.version> | |
| 58 | + <lz4.version>1.3.0</lz4.version> | |
| 59 | 59 | <hdr.version>2.1.4</hdr.version> |
| 60 | 60 | <!-- driver-extras module --> |
| 61 | 61 | <jackson.version>2.6.3</jackson.version> |
| @@ -69,7 +69,7 @@ | ||
| 69 | 69 | <assertj.version>1.7.0</assertj.version> |
| 70 | 70 | <mockito.version>1.10.8</mockito.version> |
| 71 | 71 | <commons-exec.version>1.3</commons-exec.version> |
| 72 | - <scassandra.version>1.0.3</scassandra.version> | |
| 72 | + <scassandra.version>1.0.9</scassandra.version> | |
| 73 | 73 | <main.basedir>${project.basedir}</main.basedir> |
| 74 | 74 | <ipprefix>127.0.1.</ipprefix> |
| 75 | 75 | <test.groups>unit</test.groups> |
| @@ -284,7 +284,7 @@ | ||
| 284 | 284 | </execution> |
| 285 | 285 | </executions> |
| 286 | 286 | <configuration> |
| 287 | - <comparisonVersion>3.0.0</comparisonVersion> | |
| 287 | + <comparisonVersion>3.0.2</comparisonVersion> | |
| 288 | 288 | <ignoredDifferencesFile>../clirr-ignores.xml</ignoredDifferencesFile> |
| 289 | 289 | </configuration> |
| 290 | 290 | <!-- |