kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 5a43c6822d540877d04c183e599759453152cd925d9d3b62cc75ca77e92cad95 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2016-06-16 16:04 -07:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-06-16 16:10 -07:00 |
| Parents | ac6f0e396069, 47f8bf44bd1e |
208 files changed
modified README.md +11 −20
| @@ -16,28 +16,17 @@ | ||
| 16 | 16 | |
| 17 | 17 | **Features:** |
| 18 | 18 | |
| 19 | -* [Sync][sync] and [Async][async] API | |
| 20 | -* [Simple][simple_st], [Prepared][prepared_st], and [Batch][batch_st] statements | |
| 19 | +* [Sync](manual/) and [Async](manual/async/) API | |
| 20 | +* [Simple](manual/statements/simple/), [Prepared](manual/statements/prepared/), and [Batch](manual/statements/batch/) | |
| 21 | + statements | |
| 21 | 22 | * Asynchronous IO, parallel execution, request pipelining |
| 22 | -* [Connection pooling][pool] | |
| 23 | +* [Connection pooling](manual/pooling/) | |
| 23 | 24 | * Auto node discovery |
| 24 | 25 | * Automatic reconnection |
| 25 | -* Configurable [load balancing][lbp] and [retry policies][retry_policy] | |
| 26 | +* Configurable [load balancing](manual/load_balancing/) and [retry policies](manual/retries/) | |
| 26 | 27 | * Works with any cluster size |
| 27 | -* [Query builder][query_builder] | |
| 28 | -* [Object mapper][mapper] | |
| 29 | - | |
| 30 | - | |
| 31 | -[sync]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement- | |
| 32 | -[async]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement- | |
| 33 | -[simple_st]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SimpleStatement.html | |
| 34 | -[prepared_st]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#prepare-com.datastax.driver.core.RegularStatement- | |
| 35 | -[batch_st]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BatchStatement.html | |
| 36 | -[pool]: manual/pooling/ | |
| 37 | -[lbp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 38 | -[retry_policy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html | |
| 39 | -[query_builder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 40 | -[mapper]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/MappingManager.html | |
| 28 | +* [Query builder](manual/statements/built/) | |
| 29 | +* [Object mapper](manual/object_mapper/) | |
| 41 | 30 | |
| 42 | 31 | The driver architecture is based on layers. At the bottom lies the driver core. |
| 43 | 32 | This core handles everything related to the connections to a Cassandra |
| @@ -48,8 +37,10 @@ | ||
| 48 | 37 | |
| 49 | 38 | - driver-core: the core layer. |
| 50 | 39 | - driver-mapping: the object mapper. |
| 40 | +- driver-extras: optional features for the Java driver. | |
| 51 | 41 | - driver-examples: example applications using the other modules which are |
| 52 | 42 | only meant for demonstration purposes. |
| 43 | +- driver-tests: tests for the java-driver. | |
| 53 | 44 | |
| 54 | 45 | **Useful links:** |
| 55 | 46 | |
| @@ -112,14 +103,14 @@ | ||
| 112 | 103 | |
| 113 | 104 | ## Compatibility |
| 114 | 105 | |
| 115 | -The Java client driver 3.0 ([branch 3.0](https://github.com/datastax/java-driver/tree/3.0)) is compatible with Apache | |
| 106 | +The Java client driver 3.0.0 ([branch 3.0](https://github.com/datastax/java-driver/tree/3.0)) is compatible with Apache | |
| 116 | 107 | Cassandra 1.2, 2.0, 2.1, 2.2 and 3.0 (see [this page](http://datastax.github.io/java-driver/manual/native_protocol) for |
| 117 | 108 | the most up-to-date compatibility information). |
| 118 | 109 | |
| 119 | 110 | UDT and tuple support is available only when using Apache Cassandra 2.1 or higher (see [CQL improvements in Cassandra 2.1](http://www.datastax.com/dev/blog/cql-in-2-1)). |
| 120 | 111 | |
| 121 | 112 | Other features are available only when using Apache Cassandra 2.0 or higher (e.g. result set paging, |
| 122 | -[BatchStatement](https://github.com/datastax/java-driver/blob/3.0/driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java), | |
| 113 | +[BatchStatement](https://github.com/datastax/java-driver/blob/3.0/driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java), | |
| 123 | 114 | [lightweight transactions](http://www.datastax.com/documentation/cql/3.1/cql/cql_using/use_ltweight_transaction_t.html) |
| 124 | 115 | -- see [What's new in Cassandra 2.0](http://www.datastax.com/documentation/cassandra/2.0/cassandra/features/features_key_c.html)). |
| 125 | 116 | Trying to use these with a cluster running Cassandra 1.2 will result in |
modified build.yaml +1 −0
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | - 2.1 |
| 11 | 11 | - 2.2 |
| 12 | 12 | - 3.0 |
| 13 | + - 3.4 | |
| 13 | 14 | build: |
| 14 | 15 | - type: maven |
| 15 | 16 | version: 3.2.5 |
modified changelog/README.md +119 −2
| @@ -1,5 +1,60 @@ | ||
| 1 | 1 | ## Changelog |
| 2 | 2 | |
| 3 | +### 3.0.2 | |
| 4 | + | |
| 5 | +Merged from 2.1 branch: | |
| 6 | + | |
| 7 | +- [bug] JAVA-1179: Request objects should be copied when executed. | |
| 8 | +- [improvement] JAVA-1182: Throw error when synchronous call made on I/O thread. | |
| 9 | +- [bug] JAVA-1184: Unwrap StatementWrappers when extracting column definitions. | |
| 10 | + | |
| 11 | + | |
| 12 | +### 3.0.1 | |
| 13 | + | |
| 14 | +- [bug] JAVA-1132: Executing bound statement with no variables results in exception with protocol v1. | |
| 15 | +- [improvement] JAVA-1040: SimpleStatement parameters support in QueryLogger. | |
| 16 | +- [improvement] JAVA-1151: Fail fast if HdrHistogram is not in the classpath. | |
| 17 | +- [improvement] JAVA-1154: Allow individual Statement to cancel the read timeout. | |
| 18 | +- [bug] JAVA-1074: Fix documentation around default timestamp generator. | |
| 19 | +- [improvement] JAVA-1109: Document SSLOptions changes in upgrade guide. | |
| 20 | +- [improvement] JAVA-1065: Add method to create token from partition key values. | |
| 21 | +- [improvement] JAVA-1136: Enable JDK signature check in module driver-extras. | |
| 22 | +- [improvement] JAVA-866: Support tuple notation in QueryBuilder.eq/in. | |
| 23 | +- [bug] JAVA-1140: Use same connection to check for schema agreement after a DDL query. | |
| 24 | +- [improvement] JAVA-1113: Support Cassandra 3.4 LIKE operator in QueryBuilder. | |
| 25 | +- [improvement] JAVA-1086: Support Cassandra 3.2 CAST function in QueryBuilder. | |
| 26 | +- [bug] JAVA-1095: Check protocol version for custom payload before sending the query. | |
| 27 | +- [improvement] JAVA-1133: Add OSGi headers to cassandra-driver-extras. | |
| 28 | +- [bug] JAVA-1137: Incorrect string returned by DataType.asFunctionParameterString() for collections and tuples. | |
| 29 | +- [bug] JAVA-1046: (Dynamic)CompositeTypes need to be parsed as string literal, not blob. | |
| 30 | +- [improvement] JAVA-1164: Clarify documentation on Host.listenAddress and broadcastAddress. | |
| 31 | +- [improvement] JAVA-1171: Add Host method to determine if DSE Graph is enabled. | |
| 32 | +- [improvement] JAVA-1069: Bootstrap driver-examples module. | |
| 33 | +- [documentation] JAVA-1150: Add example and FAQ entry about ByteBuffer/BLOB. | |
| 34 | + | |
| 35 | +Merged from 2.1 branch: | |
| 36 | + | |
| 37 | +- [improvement] JAVA-1011: Expose PoolingOptions default values. | |
| 38 | +- [improvement] JAVA-630: Don't process DOWN events for nodes that have active connections. | |
| 39 | +- [improvement] JAVA-851: Improve UUIDs javadoc with regard to user-provided timestamps. | |
| 40 | +- [improvement] JAVA-979: Update javadoc for RegularStatement toString() and getQueryString() to indicate that consistency level and other parameters are not maintained in the query string. | |
| 41 | +- [bug] JAVA-1068: Unwrap StatementWrappers when hashing the paging state. | |
| 42 | +- [improvement] JAVA-1021: Improve error message when connect() is called with an invalid keyspace name. | |
| 43 | +- [improvement] JAVA-879: Mapper.map() accepts mapper-generated and user queries. | |
| 44 | +- [bug] JAVA-1100: Exception when connecting with shaded java driver in OSGI | |
| 45 | +- [bug] JAVA-1064: getTable create statement doesn't properly handle quotes in primary key. | |
| 46 | +- [bug] JAVA-1089: Set LWT made from BuiltStatements to non-idempotent. | |
| 47 | +- [improvement] JAVA-923: Position idempotent flag on object mapper queries. | |
| 48 | +- [bug] JAVA-1070: The Mapper should not prepare queries synchronously. | |
| 49 | +- [new feature] JAVA-982: Introduce new method ConsistencyLevel.isSerial(). | |
| 50 | +- [bug] JAVA-764: Retry with the normal consistency level (not the serial one) when a write times out on the Paxos phase. | |
| 51 | +- [improvement] JAVA-852: Ignore peers with null entries during discovery. | |
| 52 | +- [bug] JAVA-1005: DowngradingConsistencyRetryPolicy does not work with EACH_QUORUM when 1 DC is down. | |
| 53 | +- [bug] JAVA-1002: Avoid deadlock when re-preparing a statement on other hosts. | |
| 54 | +- [bug] JAVA-1072: Ensure defunct connections are properly evicted from the pool. | |
| 55 | +- [bug] JAVA-1152: Fix NPE at ControlConnection.refreshNodeListAndTokenMap(). | |
| 56 | + | |
| 57 | + | |
| 3 | 58 | ### 3.0.0 |
| 4 | 59 | |
| 5 | 60 | - [bug] JAVA-1034: fix metadata parser for collections of custom types. |
| @@ -263,16 +318,69 @@ | ||
| 263 | 318 | - [improvement] JAVA-782: Unify "Target" enum for schema elements. |
| 264 | 319 | |
| 265 | 320 | |
| 266 | -### 2.1.10 (in progress) | |
| 321 | +### 2.1.10.2 | |
| 322 | + | |
| 323 | +Merged from 2.0 branch: | |
| 324 | + | |
| 325 | +- [bug] JAVA-1179: Request objects should be copied when executed. | |
| 326 | +- [improvement] JAVA-1182: Throw error when synchronous call made on I/O thread. | |
| 327 | +- [bug] JAVA-1184: Unwrap StatementWrappers when extracting column definitions. | |
| 328 | + | |
| 329 | + | |
| 330 | +### 2.1.10.1 | |
| 331 | + | |
| 332 | +- [bug] JAVA-1152: Fix NPE at ControlConnection.refreshNodeListAndTokenMap(). | |
| 333 | +- [bug] JAVA-1156: Fix NPE at TableMetadata.equals(). | |
| 334 | + | |
| 335 | + | |
| 336 | +### 2.1.10 | |
| 267 | 337 | |
| 268 | 338 | - [bug] JAVA-988: Metadata.handleId should handle escaped double quotes. |
| 339 | +- [bug] JAVA-983: QueryBuilder cannot handle collections containing function calls. | |
| 340 | +- [improvement] JAVA-863: Idempotence propagation in PreparedStatements. | |
| 341 | +- [bug] JAVA-937: TypeCodec static initializers not always correctly executed. | |
| 342 | +- [improvement] JAVA-989: Include keyspace name when invalid replication found when generating token map. | |
| 343 | +- [improvement] JAVA-664: Reduce heap consumption for TokenMap. | |
| 269 | 344 | - [improvement] JAVA-1030: Log token to replica map computation times. |
| 270 | 345 | - [bug] JAVA-1039: Minor bugs in Event Debouncer. |
| 346 | +- [improvement] JAVA-843: Disable frozen checks in mapper. | |
| 347 | +- [improvement] JAVA-833: Improve message when a nested type can't be serialized. | |
| 348 | +- [improvement] JAVA-1011: Expose PoolingOptions default values. | |
| 349 | +- [improvement] JAVA-630: Don't process DOWN events for nodes that have active connections. | |
| 350 | +- [improvement] JAVA-851: Improve UUIDs javadoc with regard to user-provided timestamps. | |
| 351 | +- [improvement] JAVA-979: Update javadoc for RegularStatement toString() and getQueryString() to indicate that consistency level and other parameters are not maintained in the query string. | |
| 352 | +- [improvement] JAVA-1038: Fetch node info by rpc_address if its broadcast_address is not in system.peers. | |
| 353 | +- [improvement] JAVA-974: Validate accessor parameter types against bound statement. | |
| 354 | +- [bug] JAVA-1068: Unwrap StatementWrappers when hashing the paging state. | |
| 355 | +- [bug] JAVA-831: Mapper can't load an entity where the PK is a UDT. | |
| 356 | +- [improvement] JAVA-1021: Improve error message when connect() is called with an invalid keyspace name. | |
| 357 | +- [improvement] JAVA-879: Mapper.map() accepts mapper-generated and user queries. | |
| 358 | +- [bug] JAVA-1100: Exception when connecting with shaded java driver in OSGI | |
| 359 | +- [bug] JAVA-819: Expose more errors in RetryPolicy + provide idempotent-aware wrapper. | |
| 360 | +- [improvement] JAVA-1040: SimpleStatement parameters support in QueryLogger. | |
| 361 | +- [bug] JAVA-1064: getTable create statement doesn't properly handle quotes in primary key. | |
| 362 | +- [improvement] JAVA-888: Add cluster-wide percentile tracker. | |
| 363 | +- [improvement] JAVA-963: Automatically register PercentileTracker from components that use it. | |
| 364 | +- [bug] JAVA-1089: Set LWT made from BuiltStatements to non-idempotent. | |
| 365 | +- [improvement] JAVA-923: Position idempotent flag on object mapper queries. | |
| 366 | +- [new feature] JAVA-1019: SchemaBuilder support for CREATE/ALTER/DROP KEYSPACE. | |
| 367 | +- [bug] JAVA-1070: The Mapper should not prepare queries synchronously. | |
| 368 | +- [new feature] JAVA-982: Introduce new method ConsistencyLevel.isSerial(). | |
| 369 | +- [bug] JAVA-764: Retry with the normal consistency level (not the serial one) when a write times out on the Paxos phase. | |
| 370 | +- [bug] JAVA-727: Allow monotonic timestamp generators to drift in the future + use microsecond precision when possible. | |
| 371 | +- [improvement] JAVA-444: Add Java process information to UUIDs.makeNode() hash. | |
| 372 | +- [improvement] JAVA-977: Preserve original cause when BuiltStatement value can't be serialized. | |
| 373 | +- [bug] JAVA-1094: Backport TypeCodec parse and format fixes from 3.0. | |
| 374 | +- [improvement] JAVA-852: Ignore peers with null entries during discovery. | |
| 375 | +- [bug] JAVA-1132: Executing bound statement with no variables results in exception with protocol v1. | |
| 376 | +- [bug] JAVA-1005: DowngradingConsistencyRetryPolicy does not work with EACH_QUORUM when 1 DC is down. | |
| 377 | +- [bug] JAVA-1002: Avoid deadlock when re-preparing a statement on other hosts. | |
| 271 | 378 | |
| 272 | 379 | Merged from 2.0 branch: |
| 273 | 380 | |
| 274 | 381 | - [bug] JAVA-994: Don't call on(Up|Down|Add|Remove) methods if Cluster is closed/closing. |
| 275 | 382 | - [improvement] JAVA-805: Document that metrics are null until Cluster is initialized. |
| 383 | +- [bug] JAVA-1072: Ensure defunct connections are properly evicted from the pool. | |
| 276 | 384 | |
| 277 | 385 | |
| 278 | 386 | ### 2.1.9 |
| @@ -594,10 +702,19 @@ | ||
| 594 | 702 | - [bug] JAVA-377, JAVA-391: Make metadata parsing more lenient. |
| 595 | 703 | |
| 596 | 704 | |
| 597 | -### 2.0.13 (in progress) | |
| 705 | +### 2.0.12.2 | |
| 706 | + | |
| 707 | +- [bug] JAVA-1179: Request objects should be copied when executed. | |
| 708 | +- [improvement] JAVA-1182: Throw error when synchronous call made on I/O thread. | |
| 709 | +- [bug] JAVA-1184: Unwrap StatementWrappers when extracting column definitions. | |
| 710 | + | |
| 711 | + | |
| 712 | +### 2.0.12.1 | |
| 598 | 713 | |
| 599 | 714 | - [bug] JAVA-994: Don't call on(Up|Down|Add|Remove) methods if Cluster is closed/closing. |
| 600 | 715 | - [improvement] JAVA-805: Document that metrics are null until Cluster is initialized. |
| 716 | +- [bug] JAVA-1072: Ensure defunct connections are properly evicted from the pool. | |
| 717 | + | |
| 601 | 718 | |
| 602 | 719 | ### 2.0.12 |
| 603 | 720 |
modified clirr-ignores.xml +47 −0
| @@ -7,6 +7,53 @@ | ||
| 7 | 7 | * run `mvn clirr:clirr` at the root directory |
| 8 | 8 | * check the reports in `<module>/target/site/clirr-report.html` |
| 9 | 9 | * add new differences if needed. Difference types are explained at http://www.mojohaus.org/clirr-maven-plugin/examples/ignored-differences.html |
| 10 | + | |
| 11 | + The formatter introduces line breaks that make Clirr unhappy: | |
| 12 | + @formatter:off | |
| 10 | 13 | --> |
| 11 | 14 | <differences> |
| 15 | + | |
| 16 | + <difference> | |
| 17 | + <differenceType>1001</differenceType> <!-- decreased visibility --> | |
| 18 | + <className>com/datastax/driver/mapping/ColumnMapper$Kind</className> | |
| 19 | + <justification>False positive, the enclosing class is package-private so this was never exposed</justification> | |
| 20 | + </difference> | |
| 21 | + | |
| 22 | + <difference> | |
| 23 | + <differenceType>7012</differenceType> <!-- method added to interface --> | |
| 24 | + <className>com/datastax/driver/mapping/annotations/QueryParameters</className> | |
| 25 | + <method>boolean[] idempotent()</method> | |
| 26 | + <justification>False positive, it's an annotation and the new method has a default value</justification> | |
| 27 | + </difference> | |
| 28 | + | |
| 29 | + <difference> | |
| 30 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 31 | + <className>com/datastax/driver/extras/codecs/jdk8/InstantCodec</className> | |
| 32 | + <justification>This class is only present if the project was compiled with JDK 8+</justification> | |
| 33 | + </difference> | |
| 34 | + | |
| 35 | + <difference> | |
| 36 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 37 | + <className>com/datastax/driver/extras/codecs/jdk8/LocalDateCodec</className> | |
| 38 | + <justification>This class is only present if the project was compiled with JDK 8+</justification> | |
| 39 | + </difference> | |
| 40 | + | |
| 41 | + <difference> | |
| 42 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 43 | + <className>com/datastax/driver/extras/codecs/jdk8/LocalTimeCodec</className> | |
| 44 | + <justification>This class is only present if the project was compiled with JDK 8+</justification> | |
| 45 | + </difference> | |
| 46 | + | |
| 47 | + <difference> | |
| 48 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 49 | + <className>com/datastax/driver/extras/codecs/jdk8/OptionalCodec</className> | |
| 50 | + <justification>This class is only present if the project was compiled with JDK 8+</justification> | |
| 51 | + </difference> | |
| 52 | + | |
| 53 | + <difference> | |
| 54 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 55 | + <className>com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodec</className> | |
| 56 | + <justification>This class is only present if the project was compiled with JDK 8+</justification> | |
| 57 | + </difference> | |
| 58 | + | |
| 12 | 59 | </differences> |
modified driver-core/pom.xml +19 −167
| @@ -135,6 +135,20 @@ | ||
| 135 | 135 | <scope>test</scope> |
| 136 | 136 | </dependency> |
| 137 | 137 | |
| 138 | + <dependency> | |
| 139 | + <groupId>log4j</groupId> | |
| 140 | + <artifactId>log4j</artifactId> | |
| 141 | + <version>${log4j.version}</version> | |
| 142 | + <scope>test</scope> | |
| 143 | + </dependency> | |
| 144 | + | |
| 145 | + <dependency> | |
| 146 | + <groupId>org.slf4j</groupId> | |
| 147 | + <artifactId>slf4j-log4j12</artifactId> | |
| 148 | + <version>${slf4j-log4j12.version}</version> | |
| 149 | + <scope>test</scope> | |
| 150 | + </dependency> | |
| 151 | + | |
| 138 | 152 | </dependencies> |
| 139 | 153 | |
| 140 | 154 | <build> |
| @@ -172,7 +186,7 @@ | ||
| 172 | 186 | <Bundle-SymbolicName>com.datastax.driver.core</Bundle-SymbolicName> |
| 173 | 187 | <Bundle-Version>${project.version}</Bundle-Version> |
| 174 | 188 | <_include>-osgi.bnd</_include> |
| 175 | - <Import-Package><![CDATA[com.google.common*;version="[16.0.1,19)",*]]></Import-Package> | |
| 189 | + <Import-Package><![CDATA[com.google.common*;version="[16.0.1,20)",*]]></Import-Package> | |
| 176 | 190 | </instructions> |
| 177 | 191 | <supportedProjectTypes> |
| 178 | 192 | <supportedProjectType>jar</supportedProjectType> |
| @@ -192,7 +206,7 @@ | ||
| 192 | 206 | <manifestLocation>${project.build.directory}/META-INF-shaded</manifestLocation> |
| 193 | 207 | <instructions> |
| 194 | 208 | <Import-Package> |
| 195 | - <![CDATA[com.google.common.*;version="[16.0.1,19)",!io.netty.*,*]]></Import-Package> | |
| 209 | + <![CDATA[com.google.common.*;version="[16.0.1,19)",!io.netty.*,javax.security.cert,*]]></Import-Package> | |
| 196 | 210 | <Private-Package>com.datastax.shaded.*</Private-Package> |
| 197 | 211 | </instructions> |
| 198 | 212 | </configuration> |
| @@ -292,72 +306,6 @@ | ||
| 292 | 306 | </build> |
| 293 | 307 | |
| 294 | 308 | <profiles> |
| 295 | - <profile> | |
| 296 | - <id>unit</id> | |
| 297 | - <properties> | |
| 298 | - <env>default</env> | |
| 299 | - </properties> | |
| 300 | - <!-- do not use activeByDefault as other profiles might be active --> | |
| 301 | - <activation> | |
| 302 | - <property> | |
| 303 | - <name>!activateUnitTests</name> | |
| 304 | - </property> | |
| 305 | - </activation> | |
| 306 | - <build> | |
| 307 | - <plugins> | |
| 308 | - <plugin> | |
| 309 | - <groupId>org.apache.maven.plugins</groupId> | |
| 310 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 311 | - <version>2.16</version> | |
| 312 | - <configuration> | |
| 313 | - <groups>unit</groups> | |
| 314 | - <useFile>false</useFile> | |
| 315 | - <systemPropertyVariables> | |
| 316 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 317 | - <ipprefix>${ipprefix}</ipprefix> | |
| 318 | - <com.datastax.driver.NEW_NODE_DELAY_SECONDS>60 | |
| 319 | - </com.datastax.driver.NEW_NODE_DELAY_SECONDS> | |
| 320 | - </systemPropertyVariables> | |
| 321 | - <classpathDependencyExcludes> | |
| 322 | - <classpathDependencyExcludes>io.netty:netty-transport-native-epoll | |
| 323 | - </classpathDependencyExcludes> | |
| 324 | - </classpathDependencyExcludes> | |
| 325 | - <!--May be needed for debugging--> | |
| 326 | - <!--<forkMode>never</forkMode>--> | |
| 327 | - </configuration> | |
| 328 | - </plugin> | |
| 329 | - </plugins> | |
| 330 | - </build> | |
| 331 | - </profile> | |
| 332 | - | |
| 333 | - <profile> | |
| 334 | - <id>short</id> | |
| 335 | - <properties> | |
| 336 | - <env>default</env> | |
| 337 | - </properties> | |
| 338 | - <build> | |
| 339 | - <plugins> | |
| 340 | - <plugin> | |
| 341 | - <groupId>org.apache.maven.plugins</groupId> | |
| 342 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 343 | - <version>2.16</version> | |
| 344 | - <configuration> | |
| 345 | - <groups>unit,short</groups> | |
| 346 | - <useFile>false</useFile> | |
| 347 | - <systemPropertyVariables> | |
| 348 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 349 | - <ipprefix>${ipprefix}</ipprefix> | |
| 350 | - </systemPropertyVariables> | |
| 351 | - <classpathDependencyExcludes> | |
| 352 | - <classpathDependencyExcludes>io.netty:netty-transport-native-epoll | |
| 353 | - </classpathDependencyExcludes> | |
| 354 | - </classpathDependencyExcludes> | |
| 355 | - </configuration> | |
| 356 | - </plugin> | |
| 357 | - </plugins> | |
| 358 | - </build> | |
| 359 | - </profile> | |
| 360 | - | |
| 361 | 309 | <profile> |
| 362 | 310 | <id>isolated</id> |
| 363 | 311 | <properties> |
| @@ -370,108 +318,12 @@ | ||
| 370 | 318 | <artifactId>maven-surefire-plugin</artifactId> |
| 371 | 319 | <version>2.16</version> |
| 372 | 320 | <configuration> |
| 373 | - <forkCount>1</forkCount> | |
| 374 | - <reuseForks>false</reuseForks> | |
| 375 | - <groups>isolated</groups> | |
| 376 | - <!-- Files containing tests to be included must be added here. | |
| 377 | - this prevents a fork being created for each test class. --> | |
| 321 | + <skip>false</skip> | |
| 378 | 322 | <includes> |
| 379 | 323 | <include>**/SSL*Test.java</include> |
| 324 | + <include>**/ControlConnectionTest.java</include> | |
| 325 | + <include>**/ExtendedPeerCheckDisabledTest.java</include> | |
| 380 | 326 | </includes> |
| 381 | - <reportNameSuffix>isolated</reportNameSuffix> | |
| 382 | - <useFile>false</useFile> | |
| 383 | - <systemPropertyVariables> | |
| 384 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 385 | - <ipprefix>${ipprefix}</ipprefix> | |
| 386 | - </systemPropertyVariables> | |
| 387 | - <classpathDependencyExcludes> | |
| 388 | - <classpathDependencyExcludes>io.netty:netty-transport-native-epoll | |
| 389 | - </classpathDependencyExcludes> | |
| 390 | - </classpathDependencyExcludes> | |
| 391 | - </configuration> | |
| 392 | - </plugin> | |
| 393 | - </plugins> | |
| 394 | - </build> | |
| 395 | - </profile> | |
| 396 | - | |
| 397 | - <profile> | |
| 398 | - <id>long</id> | |
| 399 | - <properties> | |
| 400 | - <env>default</env> | |
| 401 | - </properties> | |
| 402 | - <build> | |
| 403 | - <plugins> | |
| 404 | - <plugin> | |
| 405 | - <groupId>org.apache.maven.plugins</groupId> | |
| 406 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 407 | - <version>2.16</version> | |
| 408 | - <configuration> | |
| 409 | - <groups>unit,short,long</groups> | |
| 410 | - <useFile>false</useFile> | |
| 411 | - <systemPropertyVariables> | |
| 412 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 413 | - <ipprefix>${ipprefix}</ipprefix> | |
| 414 | - </systemPropertyVariables> | |
| 415 | - <classpathDependencyExcludes> | |
| 416 | - <classpathDependencyExcludes>io.netty:netty-transport-native-epoll | |
| 417 | - </classpathDependencyExcludes> | |
| 418 | - </classpathDependencyExcludes> | |
| 419 | - </configuration> | |
| 420 | - </plugin> | |
| 421 | - </plugins> | |
| 422 | - </build> | |
| 423 | - </profile> | |
| 424 | - | |
| 425 | - <profile> | |
| 426 | - <id>duration</id> | |
| 427 | - <properties> | |
| 428 | - <env>default</env> | |
| 429 | - </properties> | |
| 430 | - <build> | |
| 431 | - <plugins> | |
| 432 | - <plugin> | |
| 433 | - <groupId>org.apache.maven.plugins</groupId> | |
| 434 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 435 | - <version>2.16</version> | |
| 436 | - <configuration> | |
| 437 | - <groups>unit,short,long,duration</groups> | |
| 438 | - <useFile>false</useFile> | |
| 439 | - <systemPropertyVariables> | |
| 440 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 441 | - <ipprefix>${ipprefix}</ipprefix> | |
| 442 | - </systemPropertyVariables> | |
| 443 | - <classpathDependencyExcludes> | |
| 444 | - <classpathDependencyExcludes>io.netty:netty-transport-native-epoll | |
| 445 | - </classpathDependencyExcludes> | |
| 446 | - </classpathDependencyExcludes> | |
| 447 | - </configuration> | |
| 448 | - </plugin> | |
| 449 | - </plugins> | |
| 450 | - </build> | |
| 451 | - </profile> | |
| 452 | - | |
| 453 | - <profile> | |
| 454 | - <id>doc</id> | |
| 455 | - <properties> | |
| 456 | - <env>default</env> | |
| 457 | - </properties> | |
| 458 | - <build> | |
| 459 | - <plugins> | |
| 460 | - <plugin> | |
| 461 | - <groupId>org.apache.maven.plugins</groupId> | |
| 462 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 463 | - <version>2.16</version> | |
| 464 | - <configuration> | |
| 465 | - <groups>unit,doc</groups> | |
| 466 | - <useFile>false</useFile> | |
| 467 | - <systemPropertyVariables> | |
| 468 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 469 | - <ipprefix>${ipprefix}</ipprefix> | |
| 470 | - </systemPropertyVariables> | |
| 471 | - <classpathDependencyExcludes> | |
| 472 | - <classpathDependencyExcludes>io.netty:netty-transport-native-epoll | |
| 473 | - </classpathDependencyExcludes> | |
| 474 | - </classpathDependencyExcludes> | |
| 475 | 327 | </configuration> |
| 476 | 328 | </plugin> |
| 477 | 329 | </plugins> |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +12 −0
| @@ -60,6 +60,7 @@ | ||
| 60 | 60 | */ |
| 61 | 61 | @Override |
| 62 | 62 | public ResultSet execute(Statement statement) { |
| 63 | + checkNotInEventLoop(); | |
| 63 | 64 | return executeAsync(statement).getUninterruptibly(); |
| 64 | 65 | } |
| 65 | 66 | |
| @@ -92,6 +93,7 @@ | ||
| 92 | 93 | */ |
| 93 | 94 | @Override |
| 94 | 95 | public PreparedStatement prepare(String query) { |
| 96 | + checkNotInEventLoop(); | |
| 95 | 97 | try { |
| 96 | 98 | return Uninterruptibles.getUninterruptibly(prepareAsync(query)); |
| 97 | 99 | } catch (ExecutionException e) { |
| @@ -104,6 +106,7 @@ | ||
| 104 | 106 | */ |
| 105 | 107 | @Override |
| 106 | 108 | public PreparedStatement prepare(RegularStatement statement) { |
| 109 | + checkNotInEventLoop(); | |
| 107 | 110 | try { |
| 108 | 111 | return Uninterruptibles.getUninterruptibly(prepareAsync(statement)); |
| 109 | 112 | } catch (ExecutionException e) { |
| @@ -172,4 +175,13 @@ | ||
| 172 | 175 | Thread.currentThread().interrupt(); |
| 173 | 176 | } |
| 174 | 177 | } |
| 178 | + | |
| 179 | + /** | |
| 180 | + * Checks that the current thread is not one of the Netty I/O threads used by the driver. | |
| 181 | + * <p/> | |
| 182 | + * This is called from the synchronous methods of this class to prevent deadlock issues. | |
| 183 | + */ | |
| 184 | + protected void checkNotInEventLoop() { | |
| 185 | + // This method is concrete only to avoid a breaking change. See subclass for the actual implementation. | |
| 186 | + } | |
| 175 | 187 | } |
modified driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java +45 −3
| @@ -15,9 +15,12 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import com.datastax.driver.core.utils.Bytes; | |
| 18 | 19 | import com.google.common.base.Objects; |
| 19 | 20 | import com.google.common.collect.ImmutableList; |
| 20 | 21 | import com.google.common.collect.Lists; |
| 22 | +import org.slf4j.Logger; | |
| 23 | +import org.slf4j.LoggerFactory; | |
| 21 | 24 | |
| 22 | 25 | import java.nio.ByteBuffer; |
| 23 | 26 | import java.util.Collections; |
| @@ -28,6 +31,8 @@ | ||
| 28 | 31 | */ |
| 29 | 32 | public class AggregateMetadata { |
| 30 | 33 | |
| 34 | + private static final Logger LOGGER = LoggerFactory.getLogger(AggregateMetadata.class); | |
| 35 | + | |
| 31 | 36 | private final KeyspaceMetadata keyspace; |
| 32 | 37 | private final String simpleName; |
| 33 | 38 | private final List<DataType> argumentTypes; |
| @@ -101,11 +106,29 @@ | ||
| 101 | 106 | if (version.getMajor() >= 3) { |
| 102 | 107 | stateType = DataTypeCqlNameParser.parse(stateTypeName, cluster, ksm.getName(), ksm.userTypes, null, false, false); |
| 103 | 108 | String rawInitCond = row.getString("initcond"); |
| 104 | - initCond = rawInitCond == null ? null : codecRegistry.codecFor(stateType).parse(rawInitCond); | |
| 109 | + if (rawInitCond == null) { | |
| 110 | + initCond = null; | |
| 111 | + } else { | |
| 112 | + try { | |
| 113 | + initCond = codecRegistry.codecFor(stateType).parse(rawInitCond); | |
| 114 | + } catch (RuntimeException e) { | |
| 115 | + LOGGER.warn("Failed to parse INITCOND literal: {}; getInitCond() will return the text literal instead.", rawInitCond); | |
| 116 | + initCond = rawInitCond; | |
| 117 | + } | |
| 118 | + } | |
| 105 | 119 | } else { |
| 106 | 120 | stateType = DataTypeClassNameParser.parseOne(stateTypeName, protocolVersion, codecRegistry); |
| 107 | 121 | ByteBuffer rawInitCond = row.getBytes("initcond"); |
| 108 | - initCond = rawInitCond == null ? null : codecRegistry.codecFor(stateType).deserialize(rawInitCond, protocolVersion); | |
| 122 | + if (rawInitCond == null) { | |
| 123 | + initCond = null; | |
| 124 | + } else { | |
| 125 | + try { | |
| 126 | + initCond = codecRegistry.codecFor(stateType).deserialize(rawInitCond, protocolVersion); | |
| 127 | + } catch (RuntimeException e) { | |
| 128 | + LOGGER.warn("Failed to deserialize INITCOND value: {}; getInitCond() will return the raw bytes instead.", Bytes.toHexString(rawInitCond)); | |
| 129 | + initCond = rawInitCond; | |
| 130 | + } | |
| 131 | + } | |
| 109 | 132 | } |
| 110 | 133 | |
| 111 | 134 | String finalFuncFullName = finalFuncSimpleName == null ? null : Metadata.fullFunctionName(finalFuncSimpleName, Collections.singletonList(stateType)); |
| @@ -191,13 +214,24 @@ | ||
| 191 | 214 | if (initCond != null) |
| 192 | 215 | TableMetadata.spaceOrNewLine(sb, formatted) |
| 193 | 216 | .append("INITCOND ") |
| 194 | - .append(stateTypeCodec.format(initCond)); | |
| 217 | + .append(formatInitCond()); | |
| 195 | 218 | |
| 196 | 219 | sb.append(';'); |
| 197 | 220 | |
| 198 | 221 | return sb.toString(); |
| 199 | 222 | } |
| 200 | 223 | |
| 224 | + private String formatInitCond() { | |
| 225 | + if (stateTypeCodec.accepts(initCond)) { | |
| 226 | + try { | |
| 227 | + return stateTypeCodec.format(initCond); | |
| 228 | + } catch (RuntimeException e) { | |
| 229 | + LOGGER.info("Failed to format INITCOND literal: {}", initCond); | |
| 230 | + } | |
| 231 | + } | |
| 232 | + return initCond.toString(); | |
| 233 | + } | |
| 234 | + | |
| 201 | 235 | private void appendSignature(StringBuilder sb) { |
| 202 | 236 | sb |
| 203 | 237 | .append(Metadata.escapeId(simpleName)) |
| @@ -281,6 +315,14 @@ | ||
| 281 | 315 | * This is the value specified with {@code INITCOND} in the {@code CREATE AGGREGATE...} |
| 282 | 316 | * statement. It's passed to the initial invocation of the state function (if that function |
| 283 | 317 | * does not accept null arguments). |
| 318 | + * <p/> | |
| 319 | + * The actual type of the returned object depends on the aggregate's | |
| 320 | + * {@link #getStateType() state type} and on the {@link TypeCodec codec} used | |
| 321 | + * to {@link TypeCodec#parse(String) parse} the {@code INITCOND} literal. | |
| 322 | + * <p/> | |
| 323 | + * If, for some reason, the {@code INITCOND} literal cannot be parsed, | |
| 324 | + * a warning will be logged and the returned object will be the original | |
| 325 | + * {@code INITCOND} literal in its textual, non-parsed form. | |
| 284 | 326 | * |
| 285 | 327 | * @return the initial state, or {@code null} if there is none. |
| 286 | 328 | */ |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +21 −15
| @@ -55,16 +55,16 @@ | ||
| 55 | 55 | } |
| 56 | 56 | |
| 57 | 57 | static ArrayBackedResultSet fromMessage(Responses.Result msg, SessionManager session, ProtocolVersion protocolVersion, ExecutionInfo info, Statement statement) { |
| 58 | - info = update(info, msg, session); | |
| 59 | 58 | |
| 60 | 59 | switch (msg.kind) { |
| 61 | - case VOID: | |
| 62 | - return empty(info); | |
| 63 | 60 | case ROWS: |
| 64 | 61 | Responses.Result.Rows r = (Responses.Result.Rows) msg; |
| 65 | 62 | |
| 66 | 63 | ColumnDefinitions columnDefs; |
| 67 | 64 | if (r.metadata.columns == null) { |
| 65 | + if (statement instanceof StatementWrapper) { | |
| 66 | + statement = ((StatementWrapper) statement).getWrappedStatement(); | |
| 67 | + } | |
| 68 | 68 | assert statement instanceof BoundStatement; |
| 69 | 69 | columnDefs = ((BoundStatement) statement).statement.getPreparedId().resultSetMetadata; |
| 70 | 70 | assert columnDefs != null; |
| @@ -75,33 +75,40 @@ | ||
| 75 | 75 | Token.Factory tokenFactory = (session == null) ? null |
| 76 | 76 | : session.getCluster().manager.metadata.tokenFactory(); |
| 77 | 77 | |
| 78 | + info = update(info, r, session, r.metadata.pagingState, protocolVersion, columnDefs.codecRegistry, statement); | |
| 79 | + | |
| 78 | 80 | // info can be null only for internal calls, but we don't page those. We assert |
| 79 | - // this explicitly because MultiPage implementation don't support info == null. | |
| 81 | + // this explicitly because MultiPage implementation doesn't support info == null. | |
| 80 | 82 | assert r.metadata.pagingState == null || info != null; |
| 81 | 83 | |
| 82 | 84 | return r.metadata.pagingState == null |
| 83 | 85 | ? new SinglePage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info) |
| 84 | - : new MultiPage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info, r.metadata.pagingState, session, statement); | |
| 86 | + : new MultiPage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info, r.metadata.pagingState, session); | |
| 85 | 87 | |
| 88 | + case VOID: | |
| 86 | 89 | case SET_KEYSPACE: |
| 87 | 90 | case SCHEMA_CHANGE: |
| 91 | + info = update(info, msg, session, null, protocolVersion, null, statement); | |
| 88 | 92 | return empty(info); |
| 89 | 93 | case PREPARED: |
| 90 | 94 | throw new RuntimeException("Prepared statement received when a ResultSet was expected"); |
| 91 | 95 | default: |
| 92 | 96 | logger.error("Received unknown result type '{}'; returning empty result set", msg.kind); |
| 97 | + info = update(info, msg, session, null, protocolVersion, null, statement); | |
| 93 | 98 | return empty(info); |
| 94 | 99 | } |
| 95 | 100 | } |
| 96 | 101 | |
| 97 | - private static ExecutionInfo update(ExecutionInfo info, Responses.Result msg, SessionManager session) { | |
| 102 | + private static ExecutionInfo update(ExecutionInfo info, Responses.Result msg, SessionManager session, | |
| 103 | + ByteBuffer pagingState, ProtocolVersion protocolVersion, CodecRegistry codecRegistry, | |
| 104 | + Statement statement) { | |
| 98 | 105 | if (info == null) |
| 99 | 106 | return null; |
| 100 | 107 | |
| 101 | 108 | UUID tracingId = msg.getTracingId(); |
| 102 | 109 | QueryTrace trace = (tracingId == null) ? null : new QueryTrace(tracingId, session); |
| 103 | 110 | |
| 104 | - return info.withTraceAndWarnings(trace, msg.warnings); | |
| 111 | + return info.with(trace, msg.warnings, pagingState, statement, protocolVersion, codecRegistry); | |
| 105 | 112 | } |
| 106 | 113 | |
| 107 | 114 | private static ArrayBackedResultSet empty(ExecutionInfo info) { |
| @@ -236,7 +243,6 @@ | ||
| 236 | 243 | private volatile FetchingState fetchState; |
| 237 | 244 | |
| 238 | 245 | private final SessionManager session; |
| 239 | - private final Statement statement; | |
| 240 | 246 | |
| 241 | 247 | private MultiPage(ColumnDefinitions metadata, |
| 242 | 248 | Token.Factory tokenFactory, |
| @@ -245,19 +251,17 @@ | ||
| 245 | 251 | Queue<List<ByteBuffer>> rows, |
| 246 | 252 | ExecutionInfo info, |
| 247 | 253 | ByteBuffer pagingState, |
| 248 | - SessionManager session, | |
| 249 | - Statement statement) { | |
| 254 | + SessionManager session) { | |
| 250 | 255 | |
| 251 | 256 | // Note: as of Cassandra 2.1.0, it turns out that the result of a CAS update is never paged, so |
| 252 | 257 | // we could hard-code the result of wasApplied in this class to "true". However, we can not be sure |
| 253 | 258 | // that this will never change, so apply the generic check by peeking at the first row. |
| 254 | 259 | super(metadata, tokenFactory, rows.peek(), protocolVersion, codecRegistry); |
| 255 | 260 | this.currentPage = rows; |
| 256 | - this.infos.offer(info.withPagingState(pagingState, protocolVersion, codecRegistry).withStatement(statement)); | |
| 261 | + this.infos.offer(info); | |
| 257 | 262 | |
| 258 | 263 | this.fetchState = new FetchingState(pagingState, null); |
| 259 | 264 | this.session = session; |
| 260 | - this.statement = statement; | |
| 261 | 265 | } |
| 262 | 266 | |
| 263 | 267 | @Override |
| @@ -331,6 +335,9 @@ | ||
| 331 | 335 | |
| 332 | 336 | private ListenableFuture<ResultSet> queryNextPage(ByteBuffer nextStart, final SettableFuture<ResultSet> future) { |
| 333 | 337 | |
| 338 | + Statement statement = this.infos.peek().getStatement(); | |
| 339 | + | |
| 340 | + | |
| 334 | 341 | assert !(statement instanceof BatchStatement); |
| 335 | 342 | |
| 336 | 343 | final Message.Request request = session.makeRequestMessage(statement, nextStart); |
| @@ -351,15 +358,14 @@ | ||
| 351 | 358 | switch (response.type) { |
| 352 | 359 | case RESULT: |
| 353 | 360 | Responses.Result rm = (Responses.Result) response; |
| 354 | - info = update(info, rm, MultiPage.this.session); | |
| 355 | 361 | if (rm.kind == Responses.Result.Kind.ROWS) { |
| 356 | 362 | Responses.Result.Rows rows = (Responses.Result.Rows) rm; |
| 357 | - if (rows.metadata.pagingState != null) | |
| 358 | - info = info.withPagingState(rows.metadata.pagingState, protocolVersion, codecRegistry).withStatement(statement); | |
| 363 | + info = update(info, rm, MultiPage.this.session, rows.metadata.pagingState, protocolVersion, codecRegistry, statement); | |
| 359 | 364 | MultiPage.this.nextPages.offer(rows.data); |
| 360 | 365 | MultiPage.this.fetchState = rows.metadata.pagingState == null ? null : new FetchingState(rows.metadata.pagingState, null); |
| 361 | 366 | } else if (rm.kind == Responses.Result.Kind.VOID) { |
| 362 | 367 | // We shouldn't really get a VOID message here but well, no harm in handling it I suppose |
| 368 | + info = update(info, rm, MultiPage.this.session, null, protocolVersion, codecRegistry, statement); | |
| 363 | 369 | MultiPage.this.fetchState = null; |
| 364 | 370 | } else { |
| 365 | 371 | logger.error("Received unknown result type '{}' during paging: ignoring message", rm.kind); |
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +3 −0
| @@ -134,6 +134,9 @@ | ||
| 134 | 134 | * @throws IllegalArgumentException if adding a regular statement that uses named values. |
| 135 | 135 | */ |
| 136 | 136 | public BatchStatement add(Statement statement) { |
| 137 | + if (statement instanceof StatementWrapper) { | |
| 138 | + statement = ((StatementWrapper) statement).getWrappedStatement(); | |
| 139 | + } | |
| 137 | 140 | if ((statement instanceof RegularStatement) && ((RegularStatement) statement).usesNamedValues()) { |
| 138 | 141 | throw new IllegalArgumentException("Batch statement cannot contain regular statements with named values (" |
| 139 | 142 | + ((RegularStatement) statement).getQueryString() + ")"); |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +32 −23
| @@ -22,6 +22,7 @@ | ||
| 22 | 22 | import com.google.common.base.Functions; |
| 23 | 23 | import com.google.common.base.Predicates; |
| 24 | 24 | import com.google.common.base.Strings; |
| 25 | +import com.google.common.base.Throwables; | |
| 25 | 26 | import com.google.common.collect.*; |
| 26 | 27 | import com.google.common.util.concurrent.*; |
| 27 | 28 | import org.slf4j.Logger; |
| @@ -336,19 +337,28 @@ | ||
| 336 | 337 | if (keyspace == null) { |
| 337 | 338 | return sessionInitialized; |
| 338 | 339 | } else { |
| 340 | + final String useQuery = "USE " + keyspace; | |
| 339 | 341 | ListenableFuture<ResultSet> keyspaceSet = Futures.transform(sessionInitialized, new AsyncFunction<Session, ResultSet>() { |
| 340 | 342 | @Override |
| 341 | 343 | public ListenableFuture<ResultSet> apply(Session session) throws Exception { |
| 342 | - return session.executeAsync("USE " + keyspace); | |
| 344 | + return session.executeAsync(useQuery); | |
| 343 | 345 | } |
| 344 | 346 | }); |
| 345 | - Futures.addCallback(keyspaceSet, new MoreFutures.FailureCallback<ResultSet>() { | |
| 347 | + ListenableFuture<ResultSet> withErrorHandling = Futures.withFallback(keyspaceSet, new FutureFallback<ResultSet>() { | |
| 346 | 348 | @Override |
| 347 | - public void onFailure(Throwable t) { | |
| 349 | + public ListenableFuture<ResultSet> create(Throwable t) throws Exception { | |
| 348 | 350 | session.closeAsync(); |
| 351 | + if (t instanceof SyntaxError) { | |
| 352 | + // Give a more explicit message, because it's probably caused by a bad keyspace name | |
| 353 | + SyntaxError e = (SyntaxError) t; | |
| 354 | + t = new SyntaxError(e.getAddress(), | |
| 355 | + String.format("Error executing \"%s\" (%s). Check that your keyspace name is valid", | |
| 356 | + useQuery, e.getMessage())); | |
| 357 | + } | |
| 358 | + throw Throwables.propagate(t); | |
| 349 | 359 | } |
| 350 | 360 | }); |
| 351 | - return Futures.transform(keyspaceSet, Functions.constant(session)); | |
| 361 | + return Futures.transform(withErrorHandling, Functions.constant(session)); | |
| 352 | 362 | } |
| 353 | 363 | } |
| 354 | 364 | |
| @@ -1008,8 +1018,8 @@ | ||
| 1008 | 1018 | * generated server-side, and setting a generator through this method will have |
| 1009 | 1019 | * no effect. |
| 1010 | 1020 | * <p/> |
| 1011 | - * If no generator is set through this method, the driver will default to the | |
| 1012 | - * legacy server-side behavior by using {@link ServerSideTimestampGenerator}. | |
| 1021 | + * If no generator is set through this method, the driver will default to | |
| 1022 | + * client-side timestamps by using {@link AtomicMonotonicTimestampGenerator}. | |
| 1013 | 1023 | * |
| 1014 | 1024 | * @param timestampGenerator the generator to use. |
| 1015 | 1025 | * @return this Builder. |
| @@ -2082,18 +2092,13 @@ | ||
| 2082 | 2092 | } |
| 2083 | 2093 | } |
| 2084 | 2094 | |
| 2085 | - public boolean signalConnectionFailure(Host host, Connection connection, | |
| 2086 | - boolean isHostAddition) { | |
| 2087 | - boolean isDown = host.convictionPolicy.signalConnectionFailure(connection); | |
| 2088 | - | |
| 2095 | + public void signalHostDown(Host host, boolean isHostAddition) { | |
| 2089 | 2096 | // Don't mark the node down until we've fully initialized the controlConnection as this might mess up with |
| 2090 | 2097 | // the protocol detection |
| 2091 | 2098 | if (!isFullyInit || isClosed()) |
| 2092 | - return true; | |
| 2099 | + return; | |
| 2093 | 2100 | |
| 2094 | - if (isDown) | |
| 2095 | - triggerOnDown(host, isHostAddition, true); | |
| 2096 | - return isDown; | |
| 2101 | + triggerOnDown(host, isHostAddition, true); | |
| 2097 | 2102 | } |
| 2098 | 2103 | |
| 2099 | 2104 | public void removeHost(Host host, boolean isInitialConnection) { |
| @@ -2151,7 +2156,7 @@ | ||
| 2151 | 2156 | : reusedConnection; |
| 2152 | 2157 | |
| 2153 | 2158 | try { |
| 2154 | - controlConnection.waitForSchemaAgreement(); | |
| 2159 | + ControlConnection.waitForSchemaAgreement(connection, this); | |
| 2155 | 2160 | } catch (ExecutionException e) { |
| 2156 | 2161 | // As below, just move on |
| 2157 | 2162 | } |
| @@ -2256,7 +2261,7 @@ | ||
| 2256 | 2261 | try { |
| 2257 | 2262 | // Before refreshing the schema, wait for schema agreement so |
| 2258 | 2263 | // that querying a table just after having created it don't fail. |
| 2259 | - schemaInAgreement = controlConnection.waitForSchemaAgreement(); | |
| 2264 | + schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Cluster.Manager.this); | |
| 2260 | 2265 | if (!schemaInAgreement) |
| 2261 | 2266 | logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); |
| 2262 | 2267 | |
| @@ -2638,8 +2643,16 @@ | ||
| 2638 | 2643 | // But it is unlikely, and don't have too much consequence since we'll try reconnecting |
| 2639 | 2644 | // right away, so we favor the detection to make the Host.isUp method more reliable. |
| 2640 | 2645 | Host downHost = metadata.getHost(address); |
| 2641 | - if (downHost != null) | |
| 2642 | - futures.add(execute(hostDown(downHost))); | |
| 2646 | + if (downHost != null) { | |
| 2647 | + // Only process DOWN events if we have no active connections to the host . Otherwise, we | |
| 2648 | + // wait for the connections to fail. This is to prevent against a bad control host | |
| 2649 | + // aggressively marking DOWN all of its peers. | |
| 2650 | + if (downHost.convictionPolicy.hasActiveConnections()) { | |
| 2651 | + logger.debug("Ignoring down event on {} because it still has active connections", downHost); | |
| 2652 | + } else { | |
| 2653 | + futures.add(execute(hostDown(downHost))); | |
| 2654 | + } | |
| 2655 | + } | |
| 2643 | 2656 | break; |
| 2644 | 2657 | case REMOVED: |
| 2645 | 2658 | Host removedHost = metadata.getHost(address); |
| @@ -2720,11 +2733,7 @@ | ||
| 2720 | 2733 | return new ExceptionCatchingRunnable() { |
| 2721 | 2734 | @Override |
| 2722 | 2735 | public void runMayThrow() throws Exception { |
| 2723 | - if (controlConnection.refreshNodeInfo(host)) { | |
| 2724 | - onDown(host, false, true); | |
| 2725 | - } else { | |
| 2726 | - logger.debug("Not enough info for {}, ignoring host", host); | |
| 2727 | - } | |
| 2736 | + onDown(host, false, true); | |
| 2728 | 2737 | } |
| 2729 | 2738 | }; |
| 2730 | 2739 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +29 −22
| @@ -88,6 +88,7 @@ | ||
| 88 | 88 | |
| 89 | 89 | private volatile boolean isInitialized; |
| 90 | 90 | private final AtomicBoolean isDefunct = new AtomicBoolean(); |
| 91 | + private final AtomicBoolean signaled = new AtomicBoolean(); | |
| 91 | 92 | |
| 92 | 93 | private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>(); |
| 93 | 94 | |
| @@ -402,6 +403,21 @@ | ||
| 402 | 403 | else if (Host.statesLogger.isDebugEnabled()) |
| 403 | 404 | Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage()); |
| 404 | 405 | |
| 406 | + | |
| 407 | + Host host = factory.manager.metadata.getHost(address); | |
| 408 | + if (host != null) { | |
| 409 | + // Sometimes close() can be called before defunct(); avoid decrementing the connection count twice, but | |
| 410 | + // we still want to signal the error to the conviction policy. | |
| 411 | + boolean decrement = signaled.compareAndSet(false, true); | |
| 412 | + | |
| 413 | + boolean hostDown = host.convictionPolicy.signalConnectionFailure(this, decrement); | |
| 414 | + if (hostDown) { | |
| 415 | + factory.manager.signalHostDown(host, host.wasJustAdded()); | |
| 416 | + } else { | |
| 417 | + notifyOwnerWhenDefunct(); | |
| 418 | + } | |
| 419 | + } | |
| 420 | + | |
| 405 | 421 | // Force the connection to close to make sure the future completes. Otherwise force() might never get called and |
| 406 | 422 | // threads will wait on the future forever. |
| 407 | 423 | // (this also errors out pending handlers) |
| @@ -463,12 +479,10 @@ | ||
| 463 | 479 | Connection.this.keyspace = ((SetKeyspace) response).keyspace; |
| 464 | 480 | return MoreFutures.VOID_SUCCESS; |
| 465 | 481 | } else if (response.type == ERROR) { |
| 466 | - closeAsync().force(); | |
| 467 | 482 | Responses.Error error = (Responses.Error) response; |
| 468 | - throw error.asException(address); | |
| 483 | + throw defunct(error.asException(address)); | |
| 469 | 484 | } else { |
| 470 | - closeAsync().force(); | |
| 471 | - throw new DriverInternalError("Unexpected response while setting keyspace: " + response); | |
| 485 | + throw defunct(new DriverInternalError("Unexpected response while setting keyspace: " + response)); | |
| 472 | 486 | } |
| 473 | 487 | } |
| 474 | 488 | }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor()); |
| @@ -492,13 +506,12 @@ | ||
| 492 | 506 | return write(callback, -1, true); |
| 493 | 507 | } |
| 494 | 508 | |
| 495 | - ResponseHandler write(ResponseCallback callback, long readTimeoutMillis, boolean startTimeout) throws ConnectionException, BusyConnectionException { | |
| 496 | - | |
| 497 | - Message.Request request = callback.request(); | |
| 509 | + ResponseHandler write(ResponseCallback callback, long statementReadTimeoutMillis, boolean startTimeout) throws ConnectionException, BusyConnectionException { | |
| 498 | 510 | |
| 499 | - ResponseHandler handler = new ResponseHandler(this, readTimeoutMillis, callback); | |
| 511 | + ResponseHandler handler = new ResponseHandler(this, statementReadTimeoutMillis, callback); | |
| 500 | 512 | dispatcher.add(handler); |
| 501 | - request.setStreamId(handler.streamId); | |
| 513 | + | |
| 514 | + Message.Request request = callback.request().setStreamId(handler.streamId); | |
| 502 | 515 | |
| 503 | 516 | /* |
| 504 | 517 | * We check for close/defunct *after* having set the handler because closing/defuncting |
| @@ -615,16 +628,10 @@ | ||
| 615 | 628 | |
| 616 | 629 | logger.debug("{} closing connection", this); |
| 617 | 630 | |
| 618 | - Host host = factory.manager.metadata.getHost(address); | |
| 619 | - if (host != null) { | |
| 620 | - if (isDefunct.get()) { | |
| 621 | - boolean isDown = factory.manager.signalConnectionFailure(host, this, host.wasJustAdded()); | |
| 622 | - | |
| 623 | - if (!isDown) | |
| 624 | - notifyOwnerWhenDefunct(); | |
| 625 | - // else the driver will destroy all pools and notify the control connection as part of marking the host down, | |
| 626 | - // so no need to notify | |
| 627 | - } else { | |
| 631 | + // Only signal if defunct hasn't done it already | |
| 632 | + if (signaled.compareAndSet(false, true)) { | |
| 633 | + Host host = factory.manager.metadata.getHost(address); | |
| 634 | + if (host != null) { | |
| 628 | 635 | host.convictionPolicy.signalConnectionClosed(this); |
| 629 | 636 | } |
| 630 | 637 | } |
| @@ -678,7 +685,7 @@ | ||
| 678 | 685 | |
| 679 | 686 | final Timer timer; |
| 680 | 687 | |
| 681 | - private final EventLoopGroup eventLoopGroup; | |
| 688 | + final EventLoopGroup eventLoopGroup; | |
| 682 | 689 | private final Class<? extends Channel> channelClass; |
| 683 | 690 | |
| 684 | 691 | private final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); |
| @@ -1220,9 +1227,9 @@ | ||
| 1220 | 1227 | |
| 1221 | 1228 | private final AtomicBoolean isCancelled = new AtomicBoolean(); |
| 1222 | 1229 | |
| 1223 | - ResponseHandler(Connection connection, long readTimeoutMillis, ResponseCallback callback) throws BusyConnectionException { | |
| 1230 | + ResponseHandler(Connection connection, long statementReadTimeoutMillis, ResponseCallback callback) throws BusyConnectionException { | |
| 1224 | 1231 | this.connection = connection; |
| 1225 | - this.readTimeoutMillis = (readTimeoutMillis > 0) ? readTimeoutMillis : connection.factory.getReadTimeoutMillis(); | |
| 1232 | + this.readTimeoutMillis = (statementReadTimeoutMillis >= 0) ? statementReadTimeoutMillis : connection.factory.getReadTimeoutMillis(); | |
| 1226 | 1233 | this.streamId = connection.dispatcher.streamIdHandler.next(); |
| 1227 | 1234 | if (streamId == -1) |
| 1228 | 1235 | throw new BusyConnectionException(connection.address); |
modified driver-core/src/main/java/com/datastax/driver/core/ConsistencyLevel.java +20 −1
| @@ -58,11 +58,30 @@ | ||
| 58 | 58 | } |
| 59 | 59 | |
| 60 | 60 | /** |
| 61 | - * Whether or not the the consistency level applies to the local data-center only. | |
| 61 | + * Whether or not this consistency level applies to the local data-center only. | |
| 62 | 62 | * |
| 63 | 63 | * @return whether this consistency level is {@code LOCAL_ONE} or {@code LOCAL_QUORUM}. |
| 64 | 64 | */ |
| 65 | 65 | public boolean isDCLocal() { |
| 66 | 66 | return this == LOCAL_ONE || this == LOCAL_QUORUM; |
| 67 | 67 | } |
| 68 | + | |
| 69 | + /** | |
| 70 | + * Whether or not this consistency level is serial, that is, | |
| 71 | + * applies only to the "paxos" phase of a | |
| 72 | + * <a href="https://docs.datastax.com/en/cassandra/2.1/cassandra/dml/dml_ltwt_transaction_c.html">Lightweight transaction</a>. | |
| 73 | + * <p/> | |
| 74 | + * Serial consistency levels are only meaningful when executing conditional updates ({@code INSERT}, {@code UPDATE} | |
| 75 | + * or {@code DELETE} statements with an {@code IF} condition). | |
| 76 | + * <p/> | |
| 77 | + * Two consistency levels belong to this category: {@link #SERIAL} and {@link #LOCAL_SERIAL}. | |
| 78 | + * | |
| 79 | + * @return whether this consistency level is {@link #SERIAL} or {@link #LOCAL_SERIAL}. | |
| 80 | + * @see Statement#setSerialConsistencyLevel(ConsistencyLevel) | |
| 81 | + * @see <a href="https://docs.datastax.com/en/cassandra/2.1/cassandra/dml/dml_ltwt_transaction_c.html">Lightweight transactions</a> | |
| 82 | + */ | |
| 83 | + public boolean isSerial() { | |
| 84 | + return this == SERIAL || this == LOCAL_SERIAL; | |
| 85 | + } | |
| 86 | + | |
| 68 | 87 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +79 −26
| @@ -36,6 +36,8 @@ | ||
| 36 | 36 | |
| 37 | 37 | private static final Logger logger = LoggerFactory.getLogger(ControlConnection.class); |
| 38 | 38 | |
| 39 | + private static final boolean EXTENDED_PEER_CHECK = SystemProperties.getBoolean("com.datastax.driver.EXTENDED_PEER_CHECK", true); | |
| 40 | + | |
| 39 | 41 | private static final InetAddress bindAllAddress; |
| 40 | 42 | |
| 41 | 43 | static { |
| @@ -88,7 +90,7 @@ | ||
| 88 | 90 | r.cancel(false); |
| 89 | 91 | |
| 90 | 92 | Connection connection = connectionRef.get(); |
| 91 | - return connection == null ? CloseFuture.immediateFuture() : connection.closeAsync(); | |
| 93 | + return connection == null ? CloseFuture.immediateFuture() : connection.closeAsync().force(); | |
| 92 | 94 | } |
| 93 | 95 | |
| 94 | 96 | Host connectedHost() { |
| @@ -136,7 +138,7 @@ | ||
| 136 | 138 | @Override |
| 137 | 139 | protected void onReconnection(Connection connection) { |
| 138 | 140 | if (isShutdown) { |
| 139 | - connection.closeAsync(); | |
| 141 | + connection.closeAsync().force(); | |
| 140 | 142 | return; |
| 141 | 143 | } |
| 142 | 144 | |
| @@ -170,7 +172,7 @@ | ||
| 170 | 172 | private void signalError() { |
| 171 | 173 | Connection connection = connectionRef.get(); |
| 172 | 174 | if (connection != null) |
| 173 | - connection.closeAsync(); | |
| 175 | + connection.closeAsync().force(); | |
| 174 | 176 | |
| 175 | 177 | // If the error caused the host to go down, onDown might have already triggered a reconnect. |
| 176 | 178 | // But backgroundReconnect knows how to deal with that. |
| @@ -182,7 +184,7 @@ | ||
| 182 | 184 | newConnection.setOwner(this); |
| 183 | 185 | Connection old = connectionRef.getAndSet(newConnection); |
| 184 | 186 | if (old != null && !old.isClosed()) |
| 185 | - old.closeAsync(); | |
| 187 | + old.closeAsync().force(); | |
| 186 | 188 | } |
| 187 | 189 | |
| 188 | 190 | private Connection reconnectInternal(Iterator<Host> iter, boolean isInitialConnection) throws UnsupportedProtocolVersionException { |
| @@ -273,7 +275,7 @@ | ||
| 273 | 275 | // We need to refresh the node list again; |
| 274 | 276 | // We want that because the token map was not properly initialized by the first call above, |
| 275 | 277 | // since it requires the list of keyspaces to be loaded. |
| 276 | - refreshNodeListAndTokenMap(connection, cluster, false, true); | |
| 278 | + refreshNodeListAndTokenMap(connection, cluster, false, false); | |
| 277 | 279 | |
| 278 | 280 | return connection; |
| 279 | 281 | } catch (BusyConnectionException e) { |
| @@ -368,7 +370,7 @@ | ||
| 368 | 370 | } |
| 369 | 371 | } |
| 370 | 372 | |
| 371 | - private static InetSocketAddress rpcAddressForPeerHost(Row peersRow, InetSocketAddress connectedHost, Cluster.Manager cluster, boolean logMissingRpcAddresses) { | |
| 373 | + private static InetSocketAddress rpcAddressForPeerHost(Row peersRow, InetSocketAddress connectedHost, Cluster.Manager cluster) { | |
| 372 | 374 | |
| 373 | 375 | // after CASSANDRA-9436, system.peers contains the following inet columns: |
| 374 | 376 | // - peer: this is actually broadcast_address |
| @@ -379,15 +381,13 @@ | ||
| 379 | 381 | InetAddress broadcastAddress = peersRow.getInet("peer"); |
| 380 | 382 | InetAddress rpcAddress = peersRow.getInet("rpc_address"); |
| 381 | 383 | |
| 382 | - if (broadcastAddress.equals(connectedHost.getAddress()) || (rpcAddress != null && rpcAddress.equals(connectedHost.getAddress()))) { | |
| 384 | + if (broadcastAddress == null) { | |
| 385 | + return null; | |
| 386 | + } else if (broadcastAddress.equals(connectedHost.getAddress()) || rpcAddress.equals(connectedHost.getAddress())) { | |
| 383 | 387 | // Some DSE versions were inserting a line for the local node in peers (with mostly null values). This has been fixed, but if we |
| 384 | 388 | // detect that's the case, ignore it as it's not really a big deal. |
| 385 | 389 | 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); |
| 386 | 390 | return null; |
| 387 | - } else if (rpcAddress == null) { | |
| 388 | - if (logMissingRpcAddresses) | |
| 389 | - logger.warn("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", broadcastAddress, connectedHost, broadcastAddress); | |
| 390 | - return null; | |
| 391 | 391 | } else if (rpcAddress.equals(bindAllAddress)) { |
| 392 | 392 | 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 | 393 | rpcAddress = broadcastAddress; |
| @@ -409,7 +409,7 @@ | ||
| 409 | 409 | DefaultResultSetFuture future = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS)); |
| 410 | 410 | c.write(future); |
| 411 | 411 | for (Row row : future.get()) { |
| 412 | - InetSocketAddress addr = rpcAddressForPeerHost(row, c.address, cluster, true); | |
| 412 | + InetSocketAddress addr = rpcAddressForPeerHost(row, c.address, cluster); | |
| 413 | 413 | if (addr != null && addr.equals(host.getSocketAddress())) |
| 414 | 414 | return row; |
| 415 | 415 | } |
| @@ -442,8 +442,7 @@ | ||
| 442 | 442 | // Ignore hosts with a null rpc_address, as this is most likely a phantom row in system.peers (JAVA-428). |
| 443 | 443 | // Don't test this for the control host since we're already connected to it anyway, and we read the info from system.local |
| 444 | 444 | // which didn't have an rpc_address column (JAVA-546) until CASSANDRA-9436 |
| 445 | - } else if (!c.address.equals(host.getSocketAddress()) && row.getInet("rpc_address") == null) { | |
| 446 | - logger.warn("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress()); | |
| 445 | + } else if (!c.address.equals(host.getSocketAddress()) && !isValidPeer(row, true)) { | |
| 447 | 446 | return false; |
| 448 | 447 | } |
| 449 | 448 | |
| @@ -507,6 +506,10 @@ | ||
| 507 | 506 | String dseWorkload = row.getString("workload"); |
| 508 | 507 | host.setDseWorkload(dseWorkload); |
| 509 | 508 | } |
| 509 | + if (row.getColumnDefinitions().contains("graph")) { | |
| 510 | + boolean isDseGraph = row.getBool("graph"); | |
| 511 | + host.setDseGraphEnabled(isDseGraph); | |
| 512 | + } | |
| 510 | 513 | if (row.getColumnDefinitions().contains("dse_version")) { |
| 511 | 514 | String dseVersion = row.getString("dse_version"); |
| 512 | 515 | host.setDseVersion(dseVersion); |
| @@ -527,7 +530,7 @@ | ||
| 527 | 530 | cluster.loadBalancingPolicy().onAdd(host); |
| 528 | 531 | } |
| 529 | 532 | |
| 530 | - private static void refreshNodeListAndTokenMap(Connection connection, Cluster.Manager cluster, boolean isInitialConnection, boolean logMissingRpcAddresses) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 533 | + private static void refreshNodeListAndTokenMap(Connection connection, Cluster.Manager cluster, boolean isInitialConnection, boolean logInvalidPeers) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 531 | 534 | logger.debug("[Control connection] Refreshing node list and token map"); |
| 532 | 535 | |
| 533 | 536 | boolean metadataEnabled = cluster.configuration.getQueryOptions().isMetadataEnabled(); |
| @@ -576,13 +579,16 @@ | ||
| 576 | 579 | List<InetAddress> listenAddresses = new ArrayList<InetAddress>(); |
| 577 | 580 | List<Set<String>> allTokens = new ArrayList<Set<String>>(); |
| 578 | 581 | List<String> dseVersions = new ArrayList<String>(); |
| 582 | + List<Boolean> dseGraphEnabled = new ArrayList<Boolean>(); | |
| 579 | 583 | List<String> dseWorkloads = new ArrayList<String>(); |
| 580 | 584 | |
| 581 | 585 | for (Row row : peersFuture.get()) { |
| 582 | - InetSocketAddress rpcAddress = rpcAddressForPeerHost(row, connection.address, cluster, logMissingRpcAddresses); | |
| 583 | - if (rpcAddress == null) | |
| 586 | + if (!isValidPeer(row, logInvalidPeers)) | |
| 584 | 587 | continue; |
| 585 | 588 | |
| 589 | + InetSocketAddress rpcAddress = rpcAddressForPeerHost(row, connection.address, cluster); | |
| 590 | + if (rpcAddress == null) | |
| 591 | + continue; | |
| 586 | 592 | foundHosts.add(rpcAddress); |
| 587 | 593 | dcs.add(row.getString("data_center")); |
| 588 | 594 | racks.add(row.getString("rack")); |
| @@ -594,6 +600,8 @@ | ||
| 594 | 600 | listenAddresses.add(listenAddress); |
| 595 | 601 | String dseWorkload = row.getColumnDefinitions().contains("workload") ? row.getString("workload") : null; |
| 596 | 602 | dseWorkloads.add(dseWorkload); |
| 603 | + Boolean isDseGraph = row.getColumnDefinitions().contains("graph") ? row.getBool("graph") : null; | |
| 604 | + dseGraphEnabled.add(isDseGraph); | |
| 597 | 605 | String dseVersion = row.getColumnDefinitions().contains("dse_version") ? row.getString("dse_version") : null; |
| 598 | 606 | dseVersions.add(dseVersion); |
| 599 | 607 | } |
| @@ -627,6 +635,8 @@ | ||
| 627 | 635 | host.setDseVersion(dseVersions.get(i)); |
| 628 | 636 | if (dseWorkloads.get(i) != null) |
| 629 | 637 | host.setDseWorkload(dseWorkloads.get(i)); |
| 638 | + if (dseGraphEnabled.get(i) != null) | |
| 639 | + host.setDseGraphEnabled(dseGraphEnabled.get(i)); | |
| 630 | 640 | |
| 631 | 641 | if (metadataEnabled && partitioner != null && !allTokens.get(i).isEmpty()) |
| 632 | 642 | tokenMap.put(host, allTokens.get(i)); |
| @@ -645,13 +655,53 @@ | ||
| 645 | 655 | cluster.metadata.rebuildTokenMap(partitioner, tokenMap); |
| 646 | 656 | } |
| 647 | 657 | |
| 648 | - boolean waitForSchemaAgreement() throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 658 | + private static boolean isValidPeer(Row peerRow, boolean logIfInvalid) { | |
| 659 | + boolean isValid = peerRow.getColumnDefinitions().contains("rpc_address") | |
| 660 | + && !peerRow.isNull("rpc_address"); | |
| 661 | + if (EXTENDED_PEER_CHECK) { | |
| 662 | + isValid &= peerRow.getColumnDefinitions().contains("host_id") | |
| 663 | + && !peerRow.isNull("host_id") | |
| 664 | + && peerRow.getColumnDefinitions().contains("data_center") | |
| 665 | + && !peerRow.isNull("data_center") | |
| 666 | + && peerRow.getColumnDefinitions().contains("rack") | |
| 667 | + && !peerRow.isNull("rack") | |
| 668 | + && peerRow.getColumnDefinitions().contains("tokens") | |
| 669 | + && !peerRow.isNull("tokens"); | |
| 670 | + } | |
| 671 | + if (!isValid && logIfInvalid) | |
| 672 | + logger.warn("Found invalid row in system.peers: {}. " + | |
| 673 | + "This is likely a gossip or snitch issue, this host will be ignored.", formatInvalidPeer(peerRow)); | |
| 674 | + return isValid; | |
| 675 | + } | |
| 676 | + | |
| 677 | + // Custom formatting to avoid spamming the logs if 'tokens' is present and contains a gazillion tokens | |
| 678 | + private static String formatInvalidPeer(Row peerRow) { | |
| 679 | + StringBuilder sb = new StringBuilder("[peer=" + peerRow.getInet("peer")); | |
| 680 | + formatMissingOrNullColumn(peerRow, "rpc_address", sb); | |
| 681 | + if (EXTENDED_PEER_CHECK) { | |
| 682 | + formatMissingOrNullColumn(peerRow, "host_id", sb); | |
| 683 | + formatMissingOrNullColumn(peerRow, "data_center", sb); | |
| 684 | + formatMissingOrNullColumn(peerRow, "rack", sb); | |
| 685 | + formatMissingOrNullColumn(peerRow, "tokens", sb); | |
| 686 | + } | |
| 687 | + sb.append("]"); | |
| 688 | + return sb.toString(); | |
| 689 | + } | |
| 690 | + | |
| 691 | + private static void formatMissingOrNullColumn(Row peerRow, String columnName, StringBuilder sb) { | |
| 692 | + if (!peerRow.getColumnDefinitions().contains(columnName)) | |
| 693 | + sb.append(", missing ").append(columnName); | |
| 694 | + else if (peerRow.isNull(columnName)) | |
| 695 | + sb.append(", ").append(columnName).append("=null"); | |
| 696 | + } | |
| 697 | + | |
| 698 | + static boolean waitForSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 649 | 699 | long start = System.nanoTime(); |
| 650 | 700 | long elapsed = 0; |
| 651 | 701 | int maxSchemaAgreementWaitSeconds = cluster.configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds(); |
| 652 | 702 | while (elapsed < maxSchemaAgreementWaitSeconds * 1000) { |
| 653 | 703 | |
| 654 | - if (checkSchemaAgreement()) | |
| 704 | + if (checkSchemaAgreement(connection, cluster)) | |
| 655 | 705 | return true; |
| 656 | 706 | |
| 657 | 707 | // let's not flood the node too much |
| @@ -663,11 +713,7 @@ | ||
| 663 | 713 | return false; |
| 664 | 714 | } |
| 665 | 715 | |
| 666 | - boolean checkSchemaAgreement() throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException { | |
| 667 | - Connection connection = connectionRef.get(); | |
| 668 | - if (connection == null || connection.isClosed()) | |
| 669 | - return false; | |
| 670 | - | |
| 716 | + private static boolean checkSchemaAgreement(Connection connection, Cluster.Manager cluster) throws InterruptedException, ExecutionException { | |
| 671 | 717 | DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_PEERS)); |
| 672 | 718 | DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_LOCAL)); |
| 673 | 719 | connection.write(peersFuture); |
| @@ -681,7 +727,7 @@ | ||
| 681 | 727 | |
| 682 | 728 | for (Row row : peersFuture.get()) { |
| 683 | 729 | |
| 684 | - InetSocketAddress addr = rpcAddressForPeerHost(row, connection.address, cluster, true); | |
| 730 | + InetSocketAddress addr = rpcAddressForPeerHost(row, connection.address, cluster); | |
| 685 | 731 | if (addr == null || row.isNull("schema_version")) |
| 686 | 732 | continue; |
| 687 | 733 | |
| @@ -693,6 +739,13 @@ | ||
| 693 | 739 | return versions.size() <= 1; |
| 694 | 740 | } |
| 695 | 741 | |
| 742 | + boolean checkSchemaAgreement() throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException { | |
| 743 | + Connection connection = connectionRef.get(); | |
| 744 | + return connection != null && | |
| 745 | + !connection.isClosed() && | |
| 746 | + checkSchemaAgreement(connection, cluster); | |
| 747 | + } | |
| 748 | + | |
| 696 | 749 | boolean isOpen() { |
| 697 | 750 | Connection c = connectionRef.get(); |
| 698 | 751 | return c != null && !c.isClosed(); |
| @@ -717,7 +770,7 @@ | ||
| 717 | 770 | logger.debug("[Control connection] {} is down/removed and it was the control host, triggering reconnect", |
| 718 | 771 | current.address); |
| 719 | 772 | if (!current.isClosed()) |
| 720 | - current.closeAsync(); | |
| 773 | + current.closeAsync().force(); | |
| 721 | 774 | backgroundReconnect(0); |
| 722 | 775 | } |
| 723 | 776 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +20 −8
| @@ -49,10 +49,12 @@ | ||
| 49 | 49 | * |
| 50 | 50 | * @return whether the host should be considered down. |
| 51 | 51 | */ |
| 52 | - abstract boolean signalConnectionFailure(Connection connection); | |
| 52 | + abstract boolean signalConnectionFailure(Connection connection, boolean decrement); | |
| 53 | 53 | |
| 54 | 54 | abstract boolean canReconnectNow(); |
| 55 | 55 | |
| 56 | + abstract boolean hasActiveConnections(); | |
| 57 | + | |
| 56 | 58 | /** |
| 57 | 59 | * Simple factory interface to allow creating {@link ConvictionPolicy} instances. |
| 58 | 60 | */ |
| @@ -95,13 +97,18 @@ | ||
| 95 | 97 | } |
| 96 | 98 | |
| 97 | 99 | @Override |
| 98 | - boolean signalConnectionFailure(Connection connection) { | |
| 99 | - if (host.state != Host.State.DOWN) | |
| 100 | - updateReconnectionTime(); | |
| 101 | - | |
| 102 | - int remaining = openConnections.decrementAndGet(); | |
| 103 | - assert remaining >= 0; | |
| 104 | - Host.statesLogger.debug("[{}] {} failed, remaining = {}", host, connection, remaining); | |
| 100 | + boolean signalConnectionFailure(Connection connection, boolean decrement) { | |
| 101 | + int remaining; | |
| 102 | + if (decrement) { | |
| 103 | + if (host.state != Host.State.DOWN) | |
| 104 | + updateReconnectionTime(); | |
| 105 | + | |
| 106 | + remaining = openConnections.decrementAndGet(); | |
| 107 | + assert remaining >= 0; | |
| 108 | + Host.statesLogger.debug("[{}] {} failed, remaining = {}", host, connection, remaining); | |
| 109 | + } else { | |
| 110 | + remaining = openConnections.get(); | |
| 111 | + } | |
| 105 | 112 | return remaining == 0; |
| 106 | 113 | } |
| 107 | 114 | |
| @@ -132,6 +139,11 @@ | ||
| 132 | 139 | return canReconnectNow; |
| 133 | 140 | } |
| 134 | 141 | |
| 142 | + @Override | |
| 143 | + boolean hasActiveConnections() { | |
| 144 | + return openConnections.get() > 0; | |
| 145 | + } | |
| 146 | + | |
| 135 | 147 | static class Factory implements ConvictionPolicy.Factory { |
| 136 | 148 | |
| 137 | 149 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/DataType.java +2 −2
| @@ -691,10 +691,10 @@ | ||
| 691 | 691 | public String asFunctionParameterString() { |
| 692 | 692 | if (name == Name.MAP) { |
| 693 | 693 | String template = "%s<%s, %s>"; |
| 694 | - return String.format(template, name, typeArguments.get(0), typeArguments.get(1)); | |
| 694 | + return String.format(template, name, typeArguments.get(0).asFunctionParameterString(), typeArguments.get(1).asFunctionParameterString()); | |
| 695 | 695 | } else { |
| 696 | 696 | String template = "%s<%s>"; |
| 697 | - return String.format(template, name, typeArguments.get(0)); | |
| 697 | + return String.format(template, name, typeArguments.get(0).asFunctionParameterString()); | |
| 698 | 698 | } |
| 699 | 699 | } |
| 700 | 700 | } |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +1 −1
| @@ -161,7 +161,7 @@ | ||
| 161 | 161 | |
| 162 | 162 | @Override |
| 163 | 163 | public PreparedStatement setSerialConsistencyLevel(ConsistencyLevel serialConsistency) { |
| 164 | - if (serialConsistency != ConsistencyLevel.SERIAL && serialConsistency != ConsistencyLevel.LOCAL_SERIAL) | |
| 164 | + if (!serialConsistency.isSerial()) | |
| 165 | 165 | throw new IllegalArgumentException(); |
| 166 | 166 | this.serialConsistency = serialConsistency; |
| 167 | 167 | return this; |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +1 −1
| @@ -184,7 +184,7 @@ | ||
| 184 | 184 | setException(new DriverInternalError(String.format("Got unexpected %s response from %s", response.type, connection.address))); |
| 185 | 185 | break; |
| 186 | 186 | } |
| 187 | - } catch (RuntimeException e) { | |
| 187 | + } catch (Throwable e) { | |
| 188 | 188 | // If we get a bug here, the client will not get it, so better forwarding the error |
| 189 | 189 | setException(new DriverInternalError("Unexpected error while processing response from " + connection.address, e)); |
| 190 | 190 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +17 −10
| @@ -56,20 +56,19 @@ | ||
| 56 | 56 | this(triedHosts, null, null, null, null, null, null, true, Collections.<String>emptyList(), null); |
| 57 | 57 | } |
| 58 | 58 | |
| 59 | - ExecutionInfo withTraceAndWarnings(QueryTrace newTrace, List<String> warnings) { | |
| 60 | - return new ExecutionInfo(triedHosts, achievedConsistency, newTrace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload); | |
| 61 | - } | |
| 62 | - | |
| 63 | 59 | ExecutionInfo withAchievedConsistency(ConsistencyLevel newConsistency) { |
| 64 | 60 | return new ExecutionInfo(triedHosts, newConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload); |
| 65 | 61 | } |
| 66 | 62 | |
| 67 | - ExecutionInfo withPagingState(ByteBuffer pagingState, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 68 | - return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload); | |
| 69 | - } | |
| 70 | - | |
| 71 | - ExecutionInfo withStatement(Statement statement) { | |
| 72 | - return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, protocolVersion, codecRegistry, statement, schemaInAgreement, warnings, incomingPayload); | |
| 63 | + ExecutionInfo with(QueryTrace newTrace, List<String> newWarnings, ByteBuffer newPagingState, Statement newStatement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { | |
| 64 | + return new ExecutionInfo(this.triedHosts, this.achievedConsistency, | |
| 65 | + newTrace, | |
| 66 | + newPagingState, protocolVersion, codecRegistry, | |
| 67 | + newStatement, | |
| 68 | + schemaInAgreement, | |
| 69 | + newWarnings, | |
| 70 | + incomingPayload | |
| 71 | + ); | |
| 73 | 72 | } |
| 74 | 73 | |
| 75 | 74 | ExecutionInfo withIncomingPayload(Map<String, ByteBuffer> incomingPayload) { |
| @@ -251,4 +250,12 @@ | ||
| 251 | 250 | return incomingPayload; |
| 252 | 251 | } |
| 253 | 252 | |
| 253 | + /** | |
| 254 | + * Get the statement that has been executed. | |
| 255 | + * | |
| 256 | + * @return the statement executed. | |
| 257 | + */ | |
| 258 | + public Statement getStatement() { | |
| 259 | + return this.statement; | |
| 260 | + } | |
| 254 | 261 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +27 −10
| @@ -75,6 +75,7 @@ | ||
| 75 | 75 | private volatile Set<Token> tokens; |
| 76 | 76 | |
| 77 | 77 | private volatile String dseWorkload; |
| 78 | + private volatile boolean dseGraphEnabled; | |
| 78 | 79 | private volatile VersionNumber dseVersion; |
| 79 | 80 | |
| 80 | 81 | // ClusterMetadata keeps one Host object per inet address and we rely on this (more precisely, |
| @@ -132,6 +133,10 @@ | ||
| 132 | 133 | this.dseWorkload = dseWorkload; |
| 133 | 134 | } |
| 134 | 135 | |
| 136 | + void setDseGraphEnabled(boolean dseGraphEnabled) { | |
| 137 | + this.dseGraphEnabled = dseGraphEnabled; | |
| 138 | + } | |
| 139 | + | |
| 135 | 140 | /** |
| 136 | 141 | * Returns the address that the driver will use to connect to the node. |
| 137 | 142 | * <p/> |
| @@ -164,18 +169,20 @@ | ||
| 164 | 169 | } |
| 165 | 170 | |
| 166 | 171 | /** |
| 167 | - * Returns the node broadcast address, that is, the IP by which it should be contacted by other peers in the cluster. | |
| 172 | + * Returns the node broadcast address (that is, the IP by which it should be contacted by other peers in the | |
| 173 | + * cluster), if known. | |
| 168 | 174 | * <p/> |
| 169 | 175 | * This corresponds to the {@code broadcast_address} cassandra.yaml file setting and |
| 170 | 176 | * is by default the same as {@link #getListenAddress()}, unless specified |
| 171 | 177 | * otherwise in cassandra.yaml. |
| 172 | 178 | * <em>This is NOT the address clients should use to contact this node</em>. |
| 173 | 179 | * <p/> |
| 174 | - * Note that, depending on the Cassandra version the node is currently in, | |
| 175 | - * it might not be possible to determine the node's broadcast address, in which | |
| 176 | - * case this method will return {@code null}. | |
| 180 | + * This information is always available for peer hosts. For the control host, it's only available if CASSANDRA-9436 | |
| 181 | + * is fixed on the server side (Cassandra versions >= 2.0.16, 2.1.6, 2.2.0 rc1). For older versions, note that if | |
| 182 | + * the driver loses the control connection and reconnects to a different control host, the old control host becomes | |
| 183 | + * a peer, and therefore its broadcast address is updated. | |
| 177 | 184 | * |
| 178 | - * @return the node broadcast address. | |
| 185 | + * @return the node broadcast address, if known. Otherwise {@code null}. | |
| 179 | 186 | * @see <a href="https://docs.datastax.com/en/cassandra/2.1/cassandra/configuration/configCassandra_yaml_r.html">The cassandra.yaml configuration file</a> |
| 180 | 187 | */ |
| 181 | 188 | public InetAddress getBroadcastAddress() { |
| @@ -183,16 +190,17 @@ | ||
| 183 | 190 | } |
| 184 | 191 | |
| 185 | 192 | /** |
| 186 | - * Returns the node listen address, that is, the IP the node uses to contact other peers in the cluster. | |
| 193 | + * Returns the node listen address (that is, the IP the node uses to contact other peers in the cluster), if known. | |
| 187 | 194 | * <p/> |
| 188 | 195 | * This corresponds to the {@code listen_address} cassandra.yaml file setting. |
| 189 | 196 | * <em>This is NOT the address clients should use to contact this node</em>. |
| 190 | 197 | * <p/> |
| 191 | - * Note that, depending on the Cassandra version the node is currently in, | |
| 192 | - * it might not be possible to determine the node's listen address, in which | |
| 193 | - * case this method will return {@code null}. | |
| 198 | + * This information is available for the control host if CASSANDRA-9603 is fixed on the server side (Cassandra | |
| 199 | + * versions >= 2.0.17, 2.1.8, 2.2.0 rc2). It's currently not available for peer hosts. Note that the current driver | |
| 200 | + * code already tries to read a {@code listen_address} column in {@code system.peers}; when a future Cassandra | |
| 201 | + * version adds it, it will be picked by the driver without any further change needed. | |
| 194 | 202 | * |
| 195 | - * @return the node listen address. | |
| 203 | + * @return the node listen address, if known. Otherwise {@code null}. | |
| 196 | 204 | * @see <a href="https://docs.datastax.com/en/cassandra/2.1/cassandra/configuration/configCassandra_yaml_r.html">The cassandra.yaml configuration file</a> |
| 197 | 205 | */ |
| 198 | 206 | public InetAddress getListenAddress() { |
| @@ -266,6 +274,15 @@ | ||
| 266 | 274 | return dseWorkload; |
| 267 | 275 | } |
| 268 | 276 | |
| 277 | + /** | |
| 278 | + * Returns whether the host is running DSE Graph. | |
| 279 | + * | |
| 280 | + * @return whether the node is running DSE Graph. | |
| 281 | + */ | |
| 282 | + public boolean isDseGraphEnabled() { | |
| 283 | + return dseGraphEnabled; | |
| 284 | + } | |
| 285 | + | |
| 269 | 286 | /** |
| 270 | 287 | * Returns the tokens that this host owns. |
| 271 | 288 | * |
modified driver-core/src/main/java/com/datastax/driver/core/Message.java +15 −4
| @@ -48,7 +48,7 @@ | ||
| 48 | 48 | R decode(ByteBuf body, ProtocolVersion version, CodecRegistry codecRegistry); |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | - private volatile int streamId; | |
| 51 | + private volatile int streamId = -1; | |
| 52 | 52 | |
| 53 | 53 | /** |
| 54 | 54 | * A generic key-value custom payload. Custom payloads are simply |
| @@ -113,6 +113,19 @@ | ||
| 113 | 113 | this.tracingRequested = tracingRequested; |
| 114 | 114 | } |
| 115 | 115 | |
| 116 | + @Override | |
| 117 | + Request setStreamId(int streamId) { | |
| 118 | + // JAVA-1179: defensively guard against reusing the same Request object twice. | |
| 119 | + // If no streamId was ever set we can use this object directly, otherwise make a copy. | |
| 120 | + if (getStreamId() < 0) | |
| 121 | + return (Request) super.setStreamId(streamId); | |
| 122 | + else { | |
| 123 | + Request copy = this.copy(); | |
| 124 | + copy.setStreamId(streamId); | |
| 125 | + return copy; | |
| 126 | + } | |
| 127 | + } | |
| 128 | + | |
| 116 | 129 | boolean isTracingRequested() { |
| 117 | 130 | return tracingRequested; |
| 118 | 131 | } |
| @@ -167,9 +180,7 @@ | ||
| 167 | 180 | } |
| 168 | 181 | } |
| 169 | 182 | |
| 170 | - Request copy() { | |
| 171 | - throw new UnsupportedOperationException(); | |
| 172 | - } | |
| 183 | + abstract Request copy(); | |
| 173 | 184 | |
| 174 | 185 | Request copy(ConsistencyLevel newConsistencyLevel) { |
| 175 | 186 | throw new UnsupportedOperationException(); |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +58 −3
| @@ -48,6 +48,16 @@ | ||
| 48 | 48 | private static final Pattern alphanumeric = Pattern.compile("\\w+"); // this includes _ |
| 49 | 49 | private static final Pattern lowercaseAlphanumeric = Pattern.compile("[a-z][a-z0-9_]*"); |
| 50 | 50 | |
| 51 | + // See https://github.com/apache/cassandra/blob/trunk/doc/cql3/CQL.textile#appendixA | |
| 52 | + private static final Set<String> RESERVED_KEYWORDS = ImmutableSet.of( | |
| 53 | + "add", "allow", "alter", "and", "any", "apply", "asc", "authorize", "batch", "begin", "by", | |
| 54 | + "columnfamily", "create", "delete", "desc", "drop", "each_quorum", "from", "grant", "in", | |
| 55 | + "index", "inet", "infinity", "insert", "into", "keyspace", "keyspaces", "limit", "local_one", | |
| 56 | + "local_quorum", "modify", "nan", "norecursive", "of", "on", "one", "order", "password", | |
| 57 | + "primary", "quorum", "rename", "revoke", "schema", "select", "set", "table", "to", | |
| 58 | + "token", "three", "truncate", "two", "unlogged", "update", "use", "using", "where", "with" | |
| 59 | + ); | |
| 60 | + | |
| 51 | 61 | Metadata(Cluster.Manager cluster) { |
| 52 | 62 | this.cluster = cluster; |
| 53 | 63 | } |
| @@ -129,8 +139,11 @@ | ||
| 129 | 139 | // tables. Because it comes from Cassandra, we could just always quote it, |
| 130 | 140 | // but to get a nicer output we don't do it if it's not necessary. |
| 131 | 141 | static String escapeId(String ident) { |
| 132 | - // we don't need to escape if it's lowercase and match non-quoted CQL3 ids. | |
| 133 | - return lowercaseAlphanumeric.matcher(ident).matches() ? ident : quote(ident); | |
| 142 | + // we don't need to escape if it's lowercase and match non-quoted CQL3 ids, | |
| 143 | + // and if it's not a CQL reserved keyword | |
| 144 | + return lowercaseAlphanumeric.matcher(ident).matches() | |
| 145 | + && !isReservedCqlKeyword(ident) ? | |
| 146 | + ident : quote(ident); | |
| 134 | 147 | } |
| 135 | 148 | |
| 136 | 149 | /** |
| @@ -180,8 +193,13 @@ | ||
| 180 | 193 | * the identifier in double quotes (see the |
| 181 | 194 | * <a href="http://cassandra.apache.org/doc/cql3/CQL.html#identifiers">CQL documentation</a> |
| 182 | 195 | * for details). If you are using case sensitive identifiers, this method |
| 183 | - * can be used to enclose such identifier in double quotes, making it case | |
| 196 | + * can be used to enclose such identifiers in double quotes, making them case | |
| 184 | 197 | * sensitive. |
| 198 | + * <p/> | |
| 199 | + * Note that | |
| 200 | + * <a href="https://docs.datastax.com/en/cql/3.0/cql/cql_reference/keywords_r.html">reserved CQL keywords</a> | |
| 201 | + * should also be quoted. You can check if a given identifier is a reserved keyword | |
| 202 | + * by calling {@link #isReservedCqlKeyword(String)}. | |
| 185 | 203 | * |
| 186 | 204 | * @param id the keyspace or table identifier. |
| 187 | 205 | * @return {@code id} enclosed in double-quotes, for use in methods like |
| @@ -192,6 +210,25 @@ | ||
| 192 | 210 | return '"' + id.replace("\"", "\"\"") + '"'; |
| 193 | 211 | } |
| 194 | 212 | |
| 213 | + /** | |
| 214 | + * Checks whether an identifier is a known reserved CQL keyword or not. | |
| 215 | + * <p/> | |
| 216 | + * The check is case-insensitive, i.e., the word "{@code KeYsPaCe}" | |
| 217 | + * would be considered as a reserved CQL keyword just as "{@code keyspace}". | |
| 218 | + * <p/> | |
| 219 | + * Note: The list of reserved CQL keywords is subject to change in future | |
| 220 | + * versions of Cassandra. As a consequence, this method is provided solely as a | |
| 221 | + * convenience utility and should not be considered as an authoritative | |
| 222 | + * source of truth for checking reserved CQL keywords. | |
| 223 | + * | |
| 224 | + * @param id the identifier to check; should not be {@code null}. | |
| 225 | + * @return {@code true} if the given identifier is a known reserved | |
| 226 | + * CQL keyword, {@code false} otherwise. | |
| 227 | + */ | |
| 228 | + public static boolean isReservedCqlKeyword(String id) { | |
| 229 | + return id != null && RESERVED_KEYWORDS.contains(id.toLowerCase()); | |
| 230 | + } | |
| 231 | + | |
| 195 | 232 | /** |
| 196 | 233 | * Returns the token ranges that define data distribution in the ring. |
| 197 | 234 | * <p/> |
| @@ -423,6 +460,24 @@ | ||
| 423 | 460 | return current.factory.fromString(tokenStr); |
| 424 | 461 | } |
| 425 | 462 | |
| 463 | + /** | |
| 464 | + * Builds a new {@link Token} from a partition key. | |
| 465 | + * | |
| 466 | + * @param components the components of the partition key, in their serialized form (obtained with | |
| 467 | + * {@link TypeCodec#serialize(Object, ProtocolVersion)}). | |
| 468 | + * @return the token. | |
| 469 | + * @throws IllegalStateException if the token factory was not initialized. This would typically | |
| 470 | + * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)} | |
| 471 | + * before startup. | |
| 472 | + */ | |
| 473 | + public Token newToken(ByteBuffer... components) { | |
| 474 | + TokenMap current = tokenMap; | |
| 475 | + if (current == null) | |
| 476 | + throw new IllegalStateException("Token factory not set. This should only happen if metadata was explicitly disabled"); | |
| 477 | + return current.factory.hash( | |
| 478 | + SimpleStatement.compose(components)); | |
| 479 | + } | |
| 480 | + | |
| 426 | 481 | /** |
| 427 | 482 | * Builds a new {@link TokenRange}. |
| 428 | 483 | * |
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +2 −2
| @@ -295,7 +295,7 @@ | ||
| 295 | 295 | private final Counter speculativeExecutions = registry.counter("speculative-executions"); |
| 296 | 296 | |
| 297 | 297 | /** |
| 298 | - * Returns the number of connection to Cassandra nodes errors. | |
| 298 | + * Returns the number of errors while connecting to Cassandra nodes. | |
| 299 | 299 | * <p/> |
| 300 | 300 | * This represents the number of times that a request to a Cassandra node |
| 301 | 301 | * has failed due to a connection problem. This thus also corresponds to |
| @@ -305,7 +305,7 @@ | ||
| 305 | 305 | * (or is stopped) ,but if that number grows continuously you likely have |
| 306 | 306 | * a problem. |
| 307 | 307 | * |
| 308 | - * @return the number of connection to Cassandra nodes errors. | |
| 308 | + * @return the number of errors while connecting to Cassandra nodes. | |
| 309 | 309 | */ |
| 310 | 310 | public Counter getConnectionErrors() { |
| 311 | 311 | return connectionErrors; |
modified driver-core/src/main/java/com/datastax/driver/core/PagingState.java +3 −0
| @@ -74,6 +74,9 @@ | ||
| 74 | 74 | byte[] digest; |
| 75 | 75 | ByteBuffer[] values; |
| 76 | 76 | MessageDigest md; |
| 77 | + if (statement instanceof StatementWrapper) { | |
| 78 | + statement = ((StatementWrapper) statement).getWrappedStatement(); | |
| 79 | + } | |
| 77 | 80 | assert !(statement instanceof BatchStatement); |
| 78 | 81 | try { |
| 79 | 82 | md = MessageDigest.getInstance("MD5"); |
modified driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java +6 −0
| @@ -76,6 +76,12 @@ | ||
| 76 | 76 | int numberOfHosts, |
| 77 | 77 | int minRecordedValues, |
| 78 | 78 | long intervalMs) { |
| 79 | + try { | |
| 80 | + Histogram.class.getName(); | |
| 81 | + } catch (NoClassDefFoundError e) { | |
| 82 | + throw new IllegalStateException("HdrHistogram seems to be missing from the classpath. " + | |
| 83 | + "Make sure you depend on it explicitly (the driver declares it as optional).", e); | |
| 84 | + } | |
| 79 | 85 | this.highestTrackableLatencyMillis = highestTrackableLatencyMillis; |
| 80 | 86 | this.numberOfSignificantValueDigits = numberOfSignificantValueDigits; |
| 81 | 87 | this.minRecordedValues = minRecordedValues; |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +83 −34
| @@ -66,33 +66,76 @@ | ||
| 66 | 66 | */ |
| 67 | 67 | public static final int UNSET = Integer.MIN_VALUE; |
| 68 | 68 | |
| 69 | - private static final Map<ProtocolVersion, Map<String, Integer>> DEFAULTS = ImmutableMap.<ProtocolVersion, Map<String, Integer>>of( | |
| 70 | - ProtocolVersion.V2, ImmutableMap.<String, Integer>builder() | |
| 71 | - .put("corePoolLocal", 2) | |
| 72 | - .put("maxPoolLocal", 8) | |
| 73 | - .put("corePoolRemote", 1) | |
| 74 | - .put("maxPoolRemote", 2) | |
| 75 | - .put("newConnectionThresholdLocal", 100) | |
| 76 | - .put("newConnectionThresholdRemote", 100) | |
| 77 | - .put("maxRequestsPerConnectionLocal", 128) | |
| 78 | - .put("maxRequestsPerConnectionRemote", 128) | |
| 69 | + public static final String CORE_POOL_LOCAL_KEY = "corePoolLocal"; | |
| 70 | + public static final String MAX_POOL_LOCAL_KEY = "maxPoolLocal"; | |
| 71 | + public static final String CORE_POOL_REMOTE_KEY = "corePoolRemote"; | |
| 72 | + public static final String MAX_POOL_REMOTE_KEY = "maxPoolRemote"; | |
| 73 | + public static final String NEW_CONNECTION_THRESHOLD_LOCAL_KEY = "newConnectionThresholdLocal"; | |
| 74 | + public static final String NEW_CONNECTION_THRESHOLD_REMOTE_KEY = "newConnectionThresholdRemote"; | |
| 75 | + public static final String MAX_REQUESTS_PER_CONNECTION_LOCAL_KEY = "maxRequestsPerConnectionLocal"; | |
| 76 | + public static final String MAX_REQUESTS_PER_CONNECTION_REMOTE_KEY = "maxRequestsPerConnectionRemote"; | |
| 77 | + | |
| 78 | + /** | |
| 79 | + * The default values for connection options, that depend on the native protocol version. | |
| 80 | + * <p/> | |
| 81 | + * The map stores protocol versions in ascending order, and only the versions that introduced a change are present. | |
| 82 | + * To find the defaults for a particular version, look for the highest key that is less than or equal to that | |
| 83 | + * version, in other words: | |
| 84 | + * <pre>{@code | |
| 85 | + * ProtocolVersion referenceVersion = null; | |
| 86 | + * for (ProtocolVersion key : DEFAULTS.keySet()) { | |
| 87 | + * if (key.compareTo(actualVersion) > 0) | |
| 88 | + * break; | |
| 89 | + * else | |
| 90 | + * referenceVersion = key; | |
| 91 | + * } | |
| 92 | + * Map<String, Integer> defaults = DEFAULTS.get(referenceVersion); | |
| 93 | + * }</pre> | |
| 94 | + * Once you've extracted the underlying map, use the keys {@code CORE_POOL_LOCAL_KEY}, | |
| 95 | + * {@code MAX_POOL_LOCAL_KEY}, {@code CORE_POOL_REMOTE_KEY}, {@code MAX_POOL_REMOTE_KEY}, | |
| 96 | + * {@code NEW_CONNECTION_THRESHOLD_LOCAL_KEY}, {@code NEW_CONNECTION_THRESHOLD_REMOTE_KEY}, | |
| 97 | + * {@code MAX_REQUESTS_PER_CONNECTION_LOCAL_KEY} and {@code MAX_REQUESTS_PER_CONNECTION_REMOTE_KEY}. | |
| 98 | + * | |
| 99 | + * @see #UNSET | |
| 100 | + */ | |
| 101 | + public static final Map<ProtocolVersion, Map<String, Integer>> DEFAULTS = ImmutableMap.<ProtocolVersion, Map<String, Integer>>of( | |
| 102 | + ProtocolVersion.V1, ImmutableMap.<String, Integer>builder() | |
| 103 | + .put(CORE_POOL_LOCAL_KEY, 2) | |
| 104 | + .put(MAX_POOL_LOCAL_KEY, 8) | |
| 105 | + .put(CORE_POOL_REMOTE_KEY, 1) | |
| 106 | + .put(MAX_POOL_REMOTE_KEY, 2) | |
| 107 | + .put(NEW_CONNECTION_THRESHOLD_LOCAL_KEY, 100) | |
| 108 | + .put(NEW_CONNECTION_THRESHOLD_REMOTE_KEY, 100) | |
| 109 | + .put(MAX_REQUESTS_PER_CONNECTION_LOCAL_KEY, 128) | |
| 110 | + .put(MAX_REQUESTS_PER_CONNECTION_REMOTE_KEY, 128) | |
| 79 | 111 | .build(), |
| 80 | 112 | |
| 81 | 113 | ProtocolVersion.V3, ImmutableMap.<String, Integer>builder() |
| 82 | - .put("corePoolLocal", 1) | |
| 83 | - .put("maxPoolLocal", 1) | |
| 84 | - .put("corePoolRemote", 1) | |
| 85 | - .put("maxPoolRemote", 1) | |
| 86 | - .put("newConnectionThresholdLocal", 800) | |
| 87 | - .put("newConnectionThresholdRemote", 200) | |
| 88 | - .put("maxRequestsPerConnectionLocal", 1024) | |
| 89 | - .put("maxRequestsPerConnectionRemote", 256) | |
| 114 | + .put(CORE_POOL_LOCAL_KEY, 1) | |
| 115 | + .put(MAX_POOL_LOCAL_KEY, 1) | |
| 116 | + .put(CORE_POOL_REMOTE_KEY, 1) | |
| 117 | + .put(MAX_POOL_REMOTE_KEY, 1) | |
| 118 | + .put(NEW_CONNECTION_THRESHOLD_LOCAL_KEY, 800) | |
| 119 | + .put(NEW_CONNECTION_THRESHOLD_REMOTE_KEY, 200) | |
| 120 | + .put(MAX_REQUESTS_PER_CONNECTION_LOCAL_KEY, 1024) | |
| 121 | + .put(MAX_REQUESTS_PER_CONNECTION_REMOTE_KEY, 256) | |
| 90 | 122 | .build() |
| 91 | 123 | ); |
| 92 | 124 | |
| 93 | - private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120; | |
| 94 | - private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; | |
| 95 | - private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30; | |
| 125 | + /** | |
| 126 | + * The default value for {@link #getIdleTimeoutSeconds()} ({@value}). | |
| 127 | + */ | |
| 128 | + public static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120; | |
| 129 | + | |
| 130 | + /** | |
| 131 | + * The default value for {@link #getPoolTimeoutMillis()} ({@value}). | |
| 132 | + */ | |
| 133 | + public static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; | |
| 134 | + | |
| 135 | + /** | |
| 136 | + * The default value for {@link #getHeartbeatIntervalSeconds()} ({@value}). | |
| 137 | + */ | |
| 138 | + public static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30; | |
| 96 | 139 | |
| 97 | 140 | private static final Executor DEFAULT_INITIALIZATION_EXECUTOR = MoreExecutors.sameThreadExecutor(); |
| 98 | 141 | |
| @@ -450,40 +493,46 @@ | ||
| 450 | 493 | return this; |
| 451 | 494 | } |
| 452 | 495 | |
| 453 | - synchronized void setProtocolVersion(ProtocolVersion protocolVersion) { | |
| 454 | - this.protocolVersion = protocolVersion; | |
| 496 | + synchronized void setProtocolVersion(ProtocolVersion actualVersion) { | |
| 497 | + this.protocolVersion = actualVersion; | |
| 498 | + | |
| 499 | + ProtocolVersion referenceVersion = null; | |
| 500 | + for (ProtocolVersion key : DEFAULTS.keySet()) { | |
| 501 | + if (key.compareTo(actualVersion) > 0) | |
| 502 | + break; | |
| 503 | + else | |
| 504 | + referenceVersion = key; | |
| 505 | + } | |
| 506 | + assert referenceVersion != null; // will not happen since V1 is a key | |
| 455 | 507 | |
| 456 | - ProtocolVersion referenceVersion = (protocolVersion.compareTo(ProtocolVersion.V2) <= 0) | |
| 457 | - ? ProtocolVersion.V2 | |
| 458 | - : ProtocolVersion.V3; | |
| 459 | 508 | Map<String, Integer> defaults = DEFAULTS.get(referenceVersion); |
| 460 | 509 | |
| 461 | 510 | if (coreConnections[LOCAL.ordinal()] == UNSET) |
| 462 | - coreConnections[LOCAL.ordinal()] = defaults.get("corePoolLocal"); | |
| 511 | + coreConnections[LOCAL.ordinal()] = defaults.get(CORE_POOL_LOCAL_KEY); | |
| 463 | 512 | if (maxConnections[LOCAL.ordinal()] == UNSET) |
| 464 | - maxConnections[LOCAL.ordinal()] = defaults.get("maxPoolLocal"); | |
| 513 | + maxConnections[LOCAL.ordinal()] = defaults.get(MAX_POOL_LOCAL_KEY); | |
| 465 | 514 | checkConnectionsPerHostOrder(coreConnections[LOCAL.ordinal()], maxConnections[LOCAL.ordinal()], LOCAL); |
| 466 | 515 | |
| 467 | 516 | if (coreConnections[REMOTE.ordinal()] == UNSET) |
| 468 | - coreConnections[REMOTE.ordinal()] = defaults.get("corePoolRemote"); | |
| 517 | + coreConnections[REMOTE.ordinal()] = defaults.get(CORE_POOL_REMOTE_KEY); | |
| 469 | 518 | if (maxConnections[REMOTE.ordinal()] == UNSET) |
| 470 | - maxConnections[REMOTE.ordinal()] = defaults.get("maxPoolRemote"); | |
| 519 | + maxConnections[REMOTE.ordinal()] = defaults.get(MAX_POOL_REMOTE_KEY); | |
| 471 | 520 | checkConnectionsPerHostOrder(coreConnections[REMOTE.ordinal()], maxConnections[REMOTE.ordinal()], REMOTE); |
| 472 | 521 | |
| 473 | 522 | if (newConnectionThreshold[LOCAL.ordinal()] == UNSET) |
| 474 | - newConnectionThreshold[LOCAL.ordinal()] = defaults.get("newConnectionThresholdLocal"); | |
| 523 | + newConnectionThreshold[LOCAL.ordinal()] = defaults.get(NEW_CONNECTION_THRESHOLD_LOCAL_KEY); | |
| 475 | 524 | checkRequestsPerConnectionRange(newConnectionThreshold[LOCAL.ordinal()], "New connection threshold", LOCAL); |
| 476 | 525 | |
| 477 | 526 | if (newConnectionThreshold[REMOTE.ordinal()] == UNSET) |
| 478 | - newConnectionThreshold[REMOTE.ordinal()] = defaults.get("newConnectionThresholdRemote"); | |
| 527 | + newConnectionThreshold[REMOTE.ordinal()] = defaults.get(NEW_CONNECTION_THRESHOLD_REMOTE_KEY); | |
| 479 | 528 | checkRequestsPerConnectionRange(newConnectionThreshold[REMOTE.ordinal()], "New connection threshold", REMOTE); |
| 480 | 529 | |
| 481 | 530 | if (maxRequestsPerConnectionLocal == UNSET) |
| 482 | - maxRequestsPerConnectionLocal = defaults.get("maxRequestsPerConnectionLocal"); | |
| 531 | + maxRequestsPerConnectionLocal = defaults.get(MAX_REQUESTS_PER_CONNECTION_LOCAL_KEY); | |
| 483 | 532 | checkRequestsPerConnectionRange(maxRequestsPerConnectionLocal, "Max requests per connection", LOCAL); |
| 484 | 533 | |
| 485 | 534 | if (maxRequestsPerConnectionRemote == UNSET) |
| 486 | - maxRequestsPerConnectionRemote = defaults.get("maxRequestsPerConnectionRemote"); | |
| 535 | + maxRequestsPerConnectionRemote = defaults.get(MAX_REQUESTS_PER_CONNECTION_REMOTE_KEY); | |
| 487 | 536 | checkRequestsPerConnectionRange(maxRequestsPerConnectionRemote, "Max requests per connection", REMOTE); |
| 488 | 537 | } |
| 489 | 538 |
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +90 −9
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | import org.slf4j.LoggerFactory; |
| 22 | 22 | |
| 23 | 23 | import java.nio.ByteBuffer; |
| 24 | +import java.util.Iterator; | |
| 24 | 25 | import java.util.List; |
| 25 | 26 | |
| 26 | 27 | import static java.util.concurrent.TimeUnit.NANOSECONDS; |
| @@ -148,8 +149,10 @@ | ||
| 148 | 149 | * within a configurable threshold in milliseconds. |
| 149 | 150 | * <p/> |
| 150 | 151 | * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}. |
| 151 | - * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement}, | |
| 152 | - * then the query parameters (if any) will be logged as well (names and actual values). | |
| 152 | + * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement} | |
| 153 | + * or a {@link SimpleStatement}, then the query parameters (if any) will be logged. For a {@link BoundStatement} | |
| 154 | + * names and actual values are logged and for a {@link SimpleStatement} values are logged in positional order | |
| 155 | + * and named values are logged with names and value. | |
| 153 | 156 | * <p/> |
| 154 | 157 | * The name of this logger is {@code com.datastax.driver.core.QueryLogger.NORMAL}. |
| 155 | 158 | */ |
| @@ -160,8 +163,10 @@ | ||
| 160 | 163 | * but whose execution time exceeded a configurable threshold in milliseconds. |
| 161 | 164 | * <p/> |
| 162 | 165 | * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}. |
| 163 | - * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement}, | |
| 164 | - * then the query parameters (if any) will be logged as well (names and actual values). | |
| 166 | + * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement} | |
| 167 | + * or a {@link SimpleStatement}, then the query parameters (if any) will be logged. For a {@link BoundStatement} | |
| 168 | + * names and actual values are logged and for a {@link SimpleStatement} values are logged in positional order | |
| 169 | + * and named values are logged with names and value. | |
| 165 | 170 | * <p/> |
| 166 | 171 | * The name of this logger is {@code com.datastax.driver.core.QueryLogger.SLOW}. |
| 167 | 172 | */ |
| @@ -171,8 +176,10 @@ | ||
| 171 | 176 | * The logger used to log unsuccessful queries, i.e., queries that did not complete normally and threw an exception. |
| 172 | 177 | * <p/> |
| 173 | 178 | * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}. |
| 174 | - * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement}, | |
| 175 | - * then the query parameters (if any) will be logged as well (names and actual values). | |
| 179 | + * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement} | |
| 180 | + * or a {@link SimpleStatement}, then the query parameters (if any) will be logged. For a {@link BoundStatement} | |
| 181 | + * names and actual values are logged and for a {@link SimpleStatement} values are logged in positional order | |
| 182 | + * and named values are logged with names and value. | |
| 176 | 183 | * Note this this logger will also print the full stack trace of the reported exception. |
| 177 | 184 | * <p/> |
| 178 | 185 | * The name of this logger is {@code com.datastax.driver.core.QueryLogger.ERROR}. |
| @@ -620,6 +627,9 @@ | ||
| 620 | 627 | if (cluster == null) |
| 621 | 628 | throw new IllegalStateException("This method should only be called after the logger has been registered with a cluster"); |
| 622 | 629 | |
| 630 | + if (statement instanceof StatementWrapper) | |
| 631 | + statement = ((StatementWrapper) statement).getWrappedStatement(); | |
| 632 | + | |
| 623 | 633 | long latencyMs = NANOSECONDS.toMillis(newLatencyNanos); |
| 624 | 634 | if (exception == null) { |
| 625 | 635 | maybeLogNormalOrSlowQuery(host, statement, latencyMs); |
| @@ -650,12 +660,16 @@ | ||
| 650 | 660 | StringBuilder params = new StringBuilder(); |
| 651 | 661 | if (statement instanceof BoundStatement) { |
| 652 | 662 | appendParameters((BoundStatement) statement, params, maxLoggedParameters); |
| 663 | + } else if (statement instanceof SimpleStatement) { | |
| 664 | + appendParameters((SimpleStatement) statement, params, maxLoggedParameters); | |
| 653 | 665 | } else if (statement instanceof BatchStatement) { |
| 654 | 666 | BatchStatement batchStatement = (BatchStatement) statement; |
| 655 | 667 | int remaining = maxLoggedParameters; |
| 656 | 668 | for (Statement inner : batchStatement.getStatements()) { |
| 657 | 669 | if (inner instanceof BoundStatement) { |
| 658 | 670 | remaining = appendParameters((BoundStatement) inner, params, remaining); |
| 671 | + } else if (inner instanceof SimpleStatement) { | |
| 672 | + remaining = appendParameters((SimpleStatement) inner, params, remaining); | |
| 659 | 673 | } |
| 660 | 674 | } |
| 661 | 675 | } |
| @@ -677,6 +691,9 @@ | ||
| 677 | 691 | } else if (statement instanceof BoundStatement) { |
| 678 | 692 | int boundValues = ((BoundStatement) statement).wrapper.values.length; |
| 679 | 693 | sb.append("[" + boundValues + " bound values] "); |
| 694 | + } else if (statement instanceof SimpleStatement) { | |
| 695 | + int boundValues = ((SimpleStatement) statement).valuesCount(); | |
| 696 | + sb.append("[" + boundValues + " bound values] "); | |
| 680 | 697 | } |
| 681 | 698 | |
| 682 | 699 | append(statement, sb, maxQueryStringLength); |
| @@ -688,6 +705,8 @@ | ||
| 688 | 705 | for (Statement s : bs.getStatements()) { |
| 689 | 706 | if (s instanceof BoundStatement) |
| 690 | 707 | count += ((BoundStatement) s).wrapper.values.length; |
| 708 | + else if (s instanceof SimpleStatement) | |
| 709 | + count += ((SimpleStatement) s).valuesCount(); | |
| 691 | 710 | } |
| 692 | 711 | return count; |
| 693 | 712 | } |
| @@ -755,6 +774,71 @@ | ||
| 755 | 774 | return valueStr; |
| 756 | 775 | } |
| 757 | 776 | |
| 777 | + protected int appendParameters(SimpleStatement statement, StringBuilder buffer, int remaining) { | |
| 778 | + if (remaining == 0) | |
| 779 | + return 0; | |
| 780 | + int numberOfParameters = statement.valuesCount(); | |
| 781 | + if (numberOfParameters > 0) { | |
| 782 | + int numberOfLoggedParameters; | |
| 783 | + if (remaining == -1) { | |
| 784 | + numberOfLoggedParameters = numberOfParameters; | |
| 785 | + } else { | |
| 786 | + numberOfLoggedParameters = remaining > numberOfParameters ? numberOfParameters : remaining; | |
| 787 | + remaining -= numberOfLoggedParameters; | |
| 788 | + } | |
| 789 | + Iterator<String> valueNames = null; | |
| 790 | + if (statement.usesNamedValues()) { | |
| 791 | + valueNames = statement.getValueNames().iterator(); | |
| 792 | + } | |
| 793 | + for (int i = 0; i < numberOfLoggedParameters; i++) { | |
| 794 | + if (buffer.length() == 0) | |
| 795 | + buffer.append(" ["); | |
| 796 | + else | |
| 797 | + buffer.append(", "); | |
| 798 | + if (valueNames != null && valueNames.hasNext()) { | |
| 799 | + String valueName = valueNames.next(); | |
| 800 | + buffer.append(String.format("%s:%s", valueName, parameterValueAsString(statement.getObject(valueName)))); | |
| 801 | + } else { | |
| 802 | + buffer.append(parameterValueAsString(statement.getObject(i))); | |
| 803 | + } | |
| 804 | + } | |
| 805 | + if (numberOfLoggedParameters < numberOfParameters) { | |
| 806 | + buffer.append(FURTHER_PARAMS_OMITTED); | |
| 807 | + } | |
| 808 | + } | |
| 809 | + return remaining; | |
| 810 | + } | |
| 811 | + | |
| 812 | + protected String parameterValueAsString(Object value) { | |
| 813 | + String valueStr; | |
| 814 | + if (value == null) { | |
| 815 | + valueStr = "NULL"; | |
| 816 | + } else { | |
| 817 | + CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry(); | |
| 818 | + TypeCodec<Object> codec = codecRegistry.codecFor(value); | |
| 819 | + int maxParameterValueLength = this.maxParameterValueLength; | |
| 820 | + if (codec.cqlType.equals(DataType.blob()) && maxParameterValueLength != -1) { | |
| 821 | + // prevent large blobs from being converted to strings | |
| 822 | + ByteBuffer buf = (ByteBuffer) value; | |
| 823 | + int maxBufferLength = Math.max(2, (maxParameterValueLength - 2) / 2); | |
| 824 | + boolean bufferTooLarge = buf.remaining() > maxBufferLength; | |
| 825 | + if (bufferTooLarge) { | |
| 826 | + value = (ByteBuffer) buf.duplicate().limit(maxBufferLength); | |
| 827 | + } | |
| 828 | + valueStr = codec.format(value); | |
| 829 | + if (bufferTooLarge) { | |
| 830 | + valueStr = valueStr + TRUNCATED_OUTPUT; | |
| 831 | + } | |
| 832 | + } else { | |
| 833 | + valueStr = codec.format(value); | |
| 834 | + if (maxParameterValueLength != -1 && valueStr.length() > maxParameterValueLength) { | |
| 835 | + valueStr = valueStr.substring(0, maxParameterValueLength) + TRUNCATED_OUTPUT; | |
| 836 | + } | |
| 837 | + } | |
| 838 | + } | |
| 839 | + return valueStr; | |
| 840 | + } | |
| 841 | + | |
| 758 | 842 | private ProtocolVersion protocolVersion() { |
| 759 | 843 | // Since the QueryLogger can be registered before the Cluster was initialized, we can't retrieve |
| 760 | 844 | // it at construction time. Cache it field at first use (a volatile field is good enough since we |
| @@ -768,9 +852,6 @@ | ||
| 768 | 852 | } |
| 769 | 853 | |
| 770 | 854 | protected int append(Statement statement, StringBuilder buffer, int remaining) { |
| 771 | - if (statement instanceof StatementWrapper) | |
| 772 | - statement = ((StatementWrapper) statement).getWrappedStatement(); | |
| 773 | - | |
| 774 | 855 | if (statement instanceof RegularStatement) { |
| 775 | 856 | RegularStatement rs = (RegularStatement) statement; |
| 776 | 857 | String query = rs.getQueryString(); |
modified driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java +30 −0
| @@ -41,6 +41,23 @@ | ||
| 41 | 41 | |
| 42 | 42 | /** |
| 43 | 43 | * Returns the query string for this statement. |
| 44 | + * <p/> | |
| 45 | + * It is important to note that the query string is merely | |
| 46 | + * a CQL representation of this statement, but it does | |
| 47 | + * <em>not</em> convey all the information stored in {@link Statement} | |
| 48 | + * objects. | |
| 49 | + * <p/> | |
| 50 | + * For example, {@link Statement} objects carry numerous protocol-level | |
| 51 | + * settings, such as the {@link Statement#getConsistencyLevel() consistency level} to use, | |
| 52 | + * or the {@link Statement#isIdempotent() idempotence flag}, among others. | |
| 53 | + * <em>None of these settings will be included in the resulting query string.</em> | |
| 54 | + * <p/> | |
| 55 | + * Similarly, if values have been set on this statement because | |
| 56 | + * it has bind markers, these values will not appear in the resulting query string. | |
| 57 | + * <p/> | |
| 58 | + * Note: the consistency level was conveyed at CQL level in older versions | |
| 59 | + * of the CQL grammar, but since <a href="https://issues.apache.org/jira/browse/CASSANDRA-4734">CASSANDRA-4734</a> | |
| 60 | + * it is now a protocol-level setting and consequently does not appear in the query string. | |
| 44 | 61 | * |
| 45 | 62 | * @param codecRegistry the codec registry that will be used if the actual |
| 46 | 63 | * implementation needs to serialize Java objects in the |
| @@ -172,6 +189,19 @@ | ||
| 172 | 189 | return hasValues(CodecRegistry.DEFAULT_INSTANCE); |
| 173 | 190 | } |
| 174 | 191 | |
| 192 | + /** | |
| 193 | + * Returns this statement as a CQL query string. | |
| 194 | + * <p/> | |
| 195 | + * It is important to note that the query string is merely | |
| 196 | + * a CQL representation of this statement, but it does | |
| 197 | + * <em>not</em> convey all the information stored in {@link Statement} | |
| 198 | + * objects. | |
| 199 | + * <p/> | |
| 200 | + * See the javadocs of {@link #getQueryString()} for more information. | |
| 201 | + * | |
| 202 | + * @return this statement as a CQL query string. | |
| 203 | + * @see #getQueryString() | |
| 204 | + */ | |
| 175 | 205 | @Override |
| 176 | 206 | public String toString() { |
| 177 | 207 | return getQueryString(); |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +3 −6
| @@ -63,7 +63,7 @@ | ||
| 63 | 63 | private final long startTime; |
| 64 | 64 | |
| 65 | 65 | private final AtomicBoolean isDone = new AtomicBoolean(); |
| 66 | - private AtomicInteger executionCount = new AtomicInteger(); | |
| 66 | + private final AtomicInteger executionCount = new AtomicInteger(); | |
| 67 | 67 | |
| 68 | 68 | public RequestHandler(SessionManager manager, Callback callback, Statement statement) { |
| 69 | 69 | this.id = Long.toString(System.identityHashCode(this)); |
| @@ -105,10 +105,6 @@ | ||
| 105 | 105 | |
| 106 | 106 | Message.Request request = callback.request(); |
| 107 | 107 | int position = executionCount.incrementAndGet(); |
| 108 | - // Clone the request after the first execution, since we set the streamId on it later and we | |
| 109 | - // don't want to share that across executions. | |
| 110 | - if (position > 1) | |
| 111 | - request = request.copy(); | |
| 112 | 108 | |
| 113 | 109 | SpeculativeExecution execution = new SpeculativeExecution(request, position); |
| 114 | 110 | runningExecutions.add(execution); |
| @@ -383,7 +379,8 @@ | ||
| 383 | 379 | |
| 384 | 380 | private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) { |
| 385 | 381 | final Host h = current; |
| 386 | - this.retryConsistencyLevel = newConsistencyLevel; | |
| 382 | + if (newConsistencyLevel != null) | |
| 383 | + this.retryConsistencyLevel = newConsistencyLevel; | |
| 387 | 384 | |
| 388 | 385 | // We should not retry on the current thread as this will be an IO thread. |
| 389 | 386 | manager.executor().execute(new Runnable() { |
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +47 −8
| @@ -49,9 +49,11 @@ | ||
| 49 | 49 | }; |
| 50 | 50 | |
| 51 | 51 | private final Map<String, String> options; |
| 52 | + private final ProtocolOptions.Compression compression; | |
| 52 | 53 | |
| 53 | 54 | Startup(ProtocolOptions.Compression compression) { |
| 54 | 55 | super(Message.Request.Type.STARTUP); |
| 56 | + this.compression = compression; | |
| 55 | 57 | |
| 56 | 58 | ImmutableMap.Builder<String, String> map = new ImmutableMap.Builder<String, String>(); |
| 57 | 59 | map.put(CQL_VERSION_OPTION, CQL_VERSION); |
| @@ -60,6 +62,11 @@ | ||
| 60 | 62 | this.options = map.build(); |
| 61 | 63 | } |
| 62 | 64 | |
| 65 | + @Override | |
| 66 | + Request copy() { | |
| 67 | + return new Startup(compression); | |
| 68 | + } | |
| 69 | + | |
| 63 | 70 | @Override |
| 64 | 71 | public String toString() { |
| 65 | 72 | return "STARTUP " + options; |
| @@ -90,6 +97,11 @@ | ||
| 90 | 97 | super(Message.Request.Type.CREDENTIALS); |
| 91 | 98 | this.credentials = credentials; |
| 92 | 99 | } |
| 100 | + | |
| 101 | + @Override | |
| 102 | + Request copy() { | |
| 103 | + return new Credentials(credentials); | |
| 104 | + } | |
| 93 | 105 | } |
| 94 | 106 | |
| 95 | 107 | static class Options extends Message.Request { |
| @@ -109,6 +121,11 @@ | ||
| 109 | 121 | super(Message.Request.Type.OPTIONS); |
| 110 | 122 | } |
| 111 | 123 | |
| 124 | + @Override | |
| 125 | + Request copy() { | |
| 126 | + return new Options(); | |
| 127 | + } | |
| 128 | + | |
| 112 | 129 | @Override |
| 113 | 130 | public String toString() { |
| 114 | 131 | return "OPTIONS"; |
| @@ -231,16 +248,18 @@ | ||
| 231 | 248 | |
| 232 | 249 | static class QueryProtocolOptions { |
| 233 | 250 | |
| 234 | - static final QueryProtocolOptions DEFAULT = new QueryProtocolOptions(ConsistencyLevel.ONE, | |
| 251 | + static final QueryProtocolOptions DEFAULT = new QueryProtocolOptions( | |
| 252 | + Message.Request.Type.QUERY, | |
| 253 | + ConsistencyLevel.ONE, | |
| 235 | 254 | Collections.<ByteBuffer>emptyList(), |
| 236 | 255 | Collections.<String, ByteBuffer>emptyMap(), |
| 237 | 256 | false, |
| 238 | 257 | -1, |
| 239 | 258 | null, |
| 240 | - ConsistencyLevel.SERIAL, | |
| 241 | - Long.MIN_VALUE); | |
| 259 | + ConsistencyLevel.SERIAL, Long.MIN_VALUE); | |
| 242 | 260 | |
| 243 | 261 | private final EnumSet<QueryFlag> flags = EnumSet.noneOf(QueryFlag.class); |
| 262 | + private final Message.Request.Type requestType; | |
| 244 | 263 | final ConsistencyLevel consistency; |
| 245 | 264 | final List<ByteBuffer> positionalValues; |
| 246 | 265 | final Map<String, ByteBuffer> namedValues; |
| @@ -250,7 +269,8 @@ | ||
| 250 | 269 | final ConsistencyLevel serialConsistency; |
| 251 | 270 | final long defaultTimestamp; |
| 252 | 271 | |
| 253 | - QueryProtocolOptions(ConsistencyLevel consistency, | |
| 272 | + QueryProtocolOptions(Message.Request.Type requestType, | |
| 273 | + ConsistencyLevel consistency, | |
| 254 | 274 | List<ByteBuffer> positionalValues, |
| 255 | 275 | Map<String, ByteBuffer> namedValues, |
| 256 | 276 | boolean skipMetadata, |
| @@ -261,6 +281,7 @@ | ||
| 261 | 281 | |
| 262 | 282 | Preconditions.checkArgument(positionalValues.isEmpty() || namedValues.isEmpty()); |
| 263 | 283 | |
| 284 | + this.requestType = requestType; | |
| 264 | 285 | this.consistency = consistency; |
| 265 | 286 | this.positionalValues = positionalValues; |
| 266 | 287 | this.namedValues = namedValues; |
| @@ -290,14 +311,15 @@ | ||
| 290 | 311 | } |
| 291 | 312 | |
| 292 | 313 | QueryProtocolOptions copy(ConsistencyLevel newConsistencyLevel) { |
| 293 | - return new QueryProtocolOptions(newConsistencyLevel, positionalValues, namedValues, skipMetadata, pageSize, pagingState, serialConsistency, defaultTimestamp); | |
| 314 | + return new QueryProtocolOptions(requestType, newConsistencyLevel, positionalValues, namedValues, skipMetadata, pageSize, pagingState, serialConsistency, defaultTimestamp); | |
| 294 | 315 | } |
| 295 | 316 | |
| 296 | 317 | void encode(ByteBuf dest, ProtocolVersion version) { |
| 297 | 318 | switch (version) { |
| 298 | 319 | case V1: |
| 299 | - // Values in protocol v1 are only for bound statements, and these are never named | |
| 300 | - if (flags.contains(QueryFlag.VALUES)) | |
| 320 | + // only EXECUTE messages have variables in V1, and their list must be written | |
| 321 | + // even if it is empty; and they are never named | |
| 322 | + if (requestType == Message.Request.Type.EXECUTE) | |
| 301 | 323 | CBUtil.writeValueList(positionalValues, dest); |
| 302 | 324 | CBUtil.writeConsistencyLevel(consistency, dest); |
| 303 | 325 | break; |
| @@ -331,7 +353,9 @@ | ||
| 331 | 353 | int encodedSize(ProtocolVersion version) { |
| 332 | 354 | switch (version) { |
| 333 | 355 | case V1: |
| 334 | - return CBUtil.sizeOfValueList(positionalValues) | |
| 356 | + // only EXECUTE messages have variables in V1, and their list must be written | |
| 357 | + // even if it is empty; and they are never named | |
| 358 | + return (requestType == Message.Request.Type.EXECUTE ? CBUtil.sizeOfValueList(positionalValues) : 0) | |
| 335 | 359 | + CBUtil.sizeOfConsistencyLevel(consistency); |
| 336 | 360 | case V2: |
| 337 | 361 | case V3: |
| @@ -546,6 +570,11 @@ | ||
| 546 | 570 | this.query = query; |
| 547 | 571 | } |
| 548 | 572 | |
| 573 | + @Override | |
| 574 | + Request copy() { | |
| 575 | + return new Prepare(query); | |
| 576 | + } | |
| 577 | + | |
| 549 | 578 | @Override |
| 550 | 579 | public String toString() { |
| 551 | 580 | return "PREPARE " + query; |
| @@ -578,6 +607,11 @@ | ||
| 578 | 607 | this.eventTypes = eventTypes; |
| 579 | 608 | } |
| 580 | 609 | |
| 610 | + @Override | |
| 611 | + Request copy() { | |
| 612 | + return new Register(eventTypes); | |
| 613 | + } | |
| 614 | + | |
| 581 | 615 | @Override |
| 582 | 616 | public String toString() { |
| 583 | 617 | return "REGISTER " + eventTypes; |
| @@ -605,5 +639,10 @@ | ||
| 605 | 639 | super(Message.Request.Type.AUTH_RESPONSE); |
| 606 | 640 | this.token = token; |
| 607 | 641 | } |
| 642 | + | |
| 643 | + @Override | |
| 644 | + Request copy() { | |
| 645 | + return new AuthResponse(token); | |
| 646 | + } | |
| 608 | 647 | } |
| 609 | 648 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +28 −5
| @@ -28,6 +28,7 @@ | ||
| 28 | 28 | import com.google.common.collect.ImmutableList; |
| 29 | 29 | import com.google.common.collect.Lists; |
| 30 | 30 | import com.google.common.util.concurrent.*; |
| 31 | +import io.netty.util.concurrent.EventExecutor; | |
| 31 | 32 | import org.slf4j.Logger; |
| 32 | 33 | import org.slf4j.LoggerFactory; |
| 33 | 34 | |
| @@ -47,6 +48,9 @@ | ||
| 47 | 48 | |
| 48 | 49 | private static final Logger logger = LoggerFactory.getLogger(Session.class); |
| 49 | 50 | |
| 51 | + private static final boolean CHECK_IO_DEADLOCKS = SystemProperties.getBoolean( | |
| 52 | + "com.datastax.driver.CHECK_IO_DEADLOCKS", true); | |
| 53 | + | |
| 50 | 54 | final Cluster cluster; |
| 51 | 55 | final ConcurrentMap<Host, HostConnectionPool> pools; |
| 52 | 56 | final HostConnectionPool.PoolState poolsState; |
| @@ -223,7 +227,7 @@ | ||
| 223 | 227 | new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type))); |
| 224 | 228 | } |
| 225 | 229 | } |
| 226 | - }); | |
| 230 | + }, executor()); | |
| 227 | 231 | } |
| 228 | 232 | |
| 229 | 233 | Connection.Factory connectionFactory() { |
| @@ -502,6 +506,9 @@ | ||
| 502 | 506 | } else if (serialConsistency == null) |
| 503 | 507 | serialConsistency = configuration().getQueryOptions().getSerialConsistencyLevel(); |
| 504 | 508 | |
| 509 | + if (statement.getOutgoingPayload() != null && protocolVersion.compareTo(ProtocolVersion.V4) < 0) | |
| 510 | + throw new UnsupportedFeatureException(protocolVersion, "Custom payloads are only supported since native protocol V4"); | |
| 511 | + | |
| 505 | 512 | long defaultTimestamp = Long.MIN_VALUE; |
| 506 | 513 | if (protocolVersion.compareTo(ProtocolVersion.V3) >= 0) { |
| 507 | 514 | defaultTimestamp = statement.getDefaultTimestamp(); |
| @@ -559,8 +566,8 @@ | ||
| 559 | 566 | |
| 560 | 567 | String qString = rs.getQueryString(); |
| 561 | 568 | |
| 562 | - Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, positionalValues, namedValues, false, | |
| 563 | - fetchSize, usedPagingState, serialConsistency, defaultTimestamp); | |
| 569 | + Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(Message.Request.Type.QUERY, consistency, positionalValues, namedValues, | |
| 570 | + false, fetchSize, usedPagingState, serialConsistency, defaultTimestamp); | |
| 564 | 571 | request = new Requests.Query(qString, options, statement.isTracing()); |
| 565 | 572 | } else if (statement instanceof BoundStatement) { |
| 566 | 573 | BoundStatement bs = (BoundStatement) statement; |
| @@ -571,8 +578,8 @@ | ||
| 571 | 578 | if (protocolVersion.compareTo(ProtocolVersion.V4) < 0) |
| 572 | 579 | bs.ensureAllSet(); |
| 573 | 580 | boolean skipMetadata = protocolVersion != ProtocolVersion.V1 && bs.statement.getPreparedId().resultSetMetadata != null; |
| 574 | - Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(consistency, Arrays.asList(bs.wrapper.values), Collections.<String, ByteBuffer>emptyMap(), skipMetadata, | |
| 575 | - fetchSize, usedPagingState, serialConsistency, defaultTimestamp); | |
| 581 | + Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(Message.Request.Type.EXECUTE, consistency, Arrays.asList(bs.wrapper.values), Collections.<String, ByteBuffer>emptyMap(), | |
| 582 | + skipMetadata, fetchSize, usedPagingState, serialConsistency, defaultTimestamp); | |
| 576 | 583 | request = new Requests.Execute(bs.statement.getPreparedId().id, options, statement.isTracing()); |
| 577 | 584 | } else { |
| 578 | 585 | assert statement instanceof BatchStatement : statement; |
| @@ -658,6 +665,22 @@ | ||
| 658 | 665 | } |
| 659 | 666 | } |
| 660 | 667 | |
| 668 | + @Override | |
| 669 | + protected void checkNotInEventLoop() { | |
| 670 | + Connection.Factory connectionFactory = cluster.manager.connectionFactory; | |
| 671 | + if (!CHECK_IO_DEADLOCKS || connectionFactory == null) | |
| 672 | + return; | |
| 673 | + for (EventExecutor executor : connectionFactory.eventLoopGroup) { | |
| 674 | + if (executor.inEventLoop()) { | |
| 675 | + throw new IllegalStateException( | |
| 676 | + "Detected a synchronous Session call (execute() or prepare()) on an I/O thread, " + | |
| 677 | + "this can cause deadlocks or unpredictable behavior. " + | |
| 678 | + "Make sure your Future callbacks only use async calls, or schedule them on a " + | |
| 679 | + "different executor."); | |
| 680 | + } | |
| 681 | + } | |
| 682 | + } | |
| 683 | + | |
| 661 | 684 | private static class State implements Session.State { |
| 662 | 685 | |
| 663 | 686 | private final SessionManager session; |
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +35 −4
| @@ -18,8 +18,10 @@ | ||
| 18 | 18 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 19 | 19 | |
| 20 | 20 | import java.nio.ByteBuffer; |
| 21 | +import java.util.Collections; | |
| 21 | 22 | import java.util.HashMap; |
| 22 | 23 | import java.util.Map; |
| 24 | +import java.util.Set; | |
| 23 | 25 | |
| 24 | 26 | /** |
| 25 | 27 | * A simple {@code RegularStatement} implementation built directly from a query |
| @@ -177,21 +179,50 @@ | ||
| 177 | 179 | } |
| 178 | 180 | |
| 179 | 181 | /** |
| 180 | - * Returns the {@code i}th value as the Java type matching its CQL type. | |
| 182 | + * Returns the {@code i}th positional value as the Java type matching its CQL type. | |
| 183 | + * <p/> | |
| 184 | + * Note that, unlike with other driver types like {@link Row}, you can't retrieve named values by position. This | |
| 185 | + * getter will throw an exception if the statement was created with named values (or no values at all). Call | |
| 186 | + * {@link #usesNamedValues()} to check the type of values, and {@link #getObject(String)} if they are positional. | |
| 181 | 187 | * |
| 182 | 188 | * @param i the index to retrieve. |
| 183 | - * @return the value of the {@code i}th value of this statement. | |
| 184 | - * @throws IllegalStateException if this statement does not have values. | |
| 189 | + * @return the {@code i}th value of this statement. | |
| 190 | + * @throws IllegalStateException if this statement does not have positional values. | |
| 185 | 191 | * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. |
| 186 | 192 | */ |
| 187 | 193 | public Object getObject(int i) { |
| 188 | 194 | if (values == null) |
| 189 | - throw new IllegalStateException("This statement does not have values"); | |
| 195 | + throw new IllegalStateException("This statement does not have positional values"); | |
| 190 | 196 | if (i < 0 || i >= values.length) |
| 191 | 197 | throw new ArrayIndexOutOfBoundsException(i); |
| 192 | 198 | return values[i]; |
| 193 | 199 | } |
| 194 | 200 | |
| 201 | + /** | |
| 202 | + * Returns a named value as the Java type matching its CQL type. | |
| 203 | + * | |
| 204 | + * @param name the name of the value to retrieve. | |
| 205 | + * @return the value that matches the name, or {@code null} if there is no such name. | |
| 206 | + * @throws IllegalStateException if this statement does not have named values. | |
| 207 | + */ | |
| 208 | + public Object getObject(String name) { | |
| 209 | + if (namedValues == null) | |
| 210 | + throw new IllegalStateException("This statement does not have named values"); | |
| 211 | + return namedValues.get(name); | |
| 212 | + } | |
| 213 | + | |
| 214 | + /** | |
| 215 | + * Returns the names of the named values of this statement. | |
| 216 | + * | |
| 217 | + * @return the names of the named values of this statement. | |
| 218 | + * @throws IllegalStateException if this statement does not have named values. | |
| 219 | + */ | |
| 220 | + public Set<String> getValueNames() { | |
| 221 | + if (namedValues == null) | |
| 222 | + throw new IllegalStateException("This statement does not have named values"); | |
| 223 | + return Collections.unmodifiableSet(namedValues.keySet()); | |
| 224 | + } | |
| 225 | + | |
| 195 | 226 | /** |
| 196 | 227 | * Returns the routing key for the query. |
| 197 | 228 | * <p/> |
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +2 −4
| @@ -123,11 +123,9 @@ | ||
| 123 | 123 | * </li> |
| 124 | 124 | * </ul> |
| 125 | 125 | * <p/> |
| 126 | - * Setting a value of 0 disables read timeouts. | |
| 127 | - * <p/> | |
| 128 | - * The default value is {@link #DEFAULT_READ_TIMEOUT_MILLIS}. | |
| 126 | + * If you don't call this method, the default value is {@link #DEFAULT_READ_TIMEOUT_MILLIS}. | |
| 129 | 127 | * |
| 130 | - * @param readTimeoutMillis the timeout to set. | |
| 128 | + * @param readTimeoutMillis the timeout to set. If it is less than or equal to 0, read timeouts are disabled. | |
| 131 | 129 | * @return this {@code SocketOptions}. |
| 132 | 130 | */ |
| 133 | 131 | public SocketOptions setReadTimeoutMillis(int readTimeoutMillis) { |
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +12 −8
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException; |
| 20 | 20 | import com.datastax.driver.core.policies.RetryPolicy; |
| 21 | 21 | import com.datastax.driver.core.querybuilder.BuiltStatement; |
| 22 | +import com.google.common.base.Preconditions; | |
| 22 | 23 | import com.google.common.collect.ImmutableMap; |
| 23 | 24 | |
| 24 | 25 | import java.nio.ByteBuffer; |
| @@ -98,8 +99,9 @@ | ||
| 98 | 99 | /** |
| 99 | 100 | * Sets the serial consistency level for the query. |
| 100 | 101 | * <p/> |
| 101 | - * The serial consistency level is only used by conditional updates (so INSERT, UPDATE | |
| 102 | - * and DELETE with an IF condition). For those, the serial consistency level defines | |
| 102 | + * The serial consistency level is only used by conditional updates ({@code INSERT}, {@code UPDATE} | |
| 103 | + * or {@code DELETE} statements with an {@code IF} condition). | |
| 104 | + * For those, the serial consistency level defines | |
| 103 | 105 | * the consistency level of the serial phase (or "paxos" phase) while the |
| 104 | 106 | * normal consistency level defines the consistency for the "learn" phase, i.e. what |
| 105 | 107 | * type of reads will be guaranteed to see the update right away. For instance, if |
| @@ -122,8 +124,8 @@ | ||
| 122 | 124 | * {@code ConsistencyLevel.SERIAL} or {@code ConsistencyLevel.LOCAL_SERIAL}. |
| 123 | 125 | */ |
| 124 | 126 | public Statement setSerialConsistencyLevel(ConsistencyLevel serialConsistency) { |
| 125 | - if (serialConsistency != ConsistencyLevel.SERIAL && serialConsistency != ConsistencyLevel.LOCAL_SERIAL) | |
| 126 | - throw new IllegalArgumentException(); | |
| 127 | + if (!serialConsistency.isSerial()) | |
| 128 | + throw new IllegalArgumentException("Supplied consistency level is not serial: " + serialConsistency); | |
| 127 | 129 | this.serialConsistency = serialConsistency; |
| 128 | 130 | return this; |
| 129 | 131 | } |
| @@ -131,10 +133,10 @@ | ||
| 131 | 133 | /** |
| 132 | 134 | * The serial consistency level for this query. |
| 133 | 135 | * <p/> |
| 134 | - * See {@link #setSerialConsistencyLevel} for more detail on the serial consistency level. | |
| 136 | + * See {@link #setSerialConsistencyLevel(ConsistencyLevel)} for more detail on the serial consistency level. | |
| 135 | 137 | * |
| 136 | - * @return the consistency level for this query, or {@code null} if no serial | |
| 137 | - * consistency level has been specified (through {@code setSerialConsistencyLevel}). | |
| 138 | + * @return the serial consistency level for this query, or {@code null} if no serial | |
| 139 | + * consistency level has been specified (through {@link #setSerialConsistencyLevel(ConsistencyLevel)}). | |
| 138 | 140 | * In the latter case, the default serial consistency level will be used. |
| 139 | 141 | */ |
| 140 | 142 | public ConsistencyLevel getSerialConsistencyLevel() { |
| @@ -329,10 +331,12 @@ | ||
| 329 | 331 | * You should override this only for statements for which the coordinator may allow a longer server-side |
| 330 | 332 | * timeout (for example aggregation queries). |
| 331 | 333 | * |
| 332 | - * @param readTimeoutMillis the timeout to set. Must be greater than 0 (or the default will be used). | |
| 334 | + * @param readTimeoutMillis the timeout to set. Negative values are not allowed. If it is 0, the read timeout will | |
| 335 | + * be disabled for this statement. | |
| 333 | 336 | * @return this {@code Statement} object. |
| 334 | 337 | */ |
| 335 | 338 | public Statement setReadTimeoutMillis(int readTimeoutMillis) { |
| 339 | + Preconditions.checkArgument(readTimeoutMillis >= 0, "read timeout must be >= 0"); | |
| 336 | 340 | this.readTimeoutMillis = readTimeoutMillis; |
| 337 | 341 | return this; |
| 338 | 342 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java +3 −3
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | /** |
| 22 | 22 | * Allows overriding internal settings via system properties. |
| 23 | 23 | * <p/> |
| 24 | - * Warning: this is meant for integration tests only, NOT FOR PRODUCTION USE. | |
| 24 | + * This is generally reserved for tests or "expert" usage. | |
| 25 | 25 | */ |
| 26 | 26 | class SystemProperties { |
| 27 | 27 | private static final Logger logger = LoggerFactory.getLogger(SystemProperties.class); |
| @@ -34,7 +34,7 @@ | ||
| 34 | 34 | } |
| 35 | 35 | try { |
| 36 | 36 | int value = Integer.parseInt(stringValue); |
| 37 | - logger.warn("{} is defined, using value {}", key, value); | |
| 37 | + logger.info("{} is defined, using value {}", key, value); | |
| 38 | 38 | return value; |
| 39 | 39 | } catch (NumberFormatException e) { |
| 40 | 40 | logger.warn("{} is defined but could not parse value {}, using default value {}", key, stringValue, defaultValue); |
| @@ -50,7 +50,7 @@ | ||
| 50 | 50 | } |
| 51 | 51 | try { |
| 52 | 52 | boolean value = Boolean.parseBoolean(stringValue); |
| 53 | - logger.warn("{} is defined, using value {}", key, value); | |
| 53 | + logger.info("{} is defined, using value {}", key, value); | |
| 54 | 54 | return value; |
| 55 | 55 | } catch (NumberFormatException e) { |
| 56 | 56 | logger.warn("{} is defined but could not parse value {}, using default value {}", key, stringValue, defaultValue); |
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +2 −2
| @@ -401,12 +401,12 @@ | ||
| 401 | 401 | sb.append("CREATE TABLE ").append(Metadata.escapeId(keyspace.getName())).append('.').append(Metadata.escapeId(name)).append(" ("); |
| 402 | 402 | newLine(sb, formatted); |
| 403 | 403 | for (ColumnMetadata cm : columns.values()) |
| 404 | - newLine(sb.append(spaces(4, formatted)).append(cm).append(','), formatted); | |
| 404 | + newLine(sb.append(spaces(4, formatted)).append(cm).append(',').append(spaces(1, !formatted)), formatted); | |
| 405 | 405 | |
| 406 | 406 | // PK |
| 407 | 407 | sb.append(spaces(4, formatted)).append("PRIMARY KEY ("); |
| 408 | 408 | if (partitionKey.size() == 1) { |
| 409 | - sb.append(partitionKey.get(0).getName()); | |
| 409 | + sb.append(Metadata.escapeId(partitionKey.get(0).getName())); | |
| 410 | 410 | } else { |
| 411 | 411 | sb.append('('); |
| 412 | 412 | boolean first = true; |
modified driver-core/src/main/java/com/datastax/driver/core/TupleType.java +1 −1
| @@ -190,7 +190,7 @@ | ||
| 190 | 190 | StringBuilder sb = new StringBuilder(); |
| 191 | 191 | for (DataType type : types) { |
| 192 | 192 | sb.append(sb.length() == 0 ? "tuple<" : ", "); |
| 193 | - sb.append(type); | |
| 193 | + sb.append(type.asFunctionParameterString()); | |
| 194 | 194 | } |
| 195 | 195 | return sb.append(">").toString(); |
| 196 | 196 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/CodecNotFoundException.java +11 −4
| @@ -30,13 +30,15 @@ | ||
| 30 | 30 | private final TypeToken<?> javaType; |
| 31 | 31 | |
| 32 | 32 | public CodecNotFoundException(String msg, DataType cqlType, TypeToken<?> javaType) { |
| 33 | - super(msg); | |
| 34 | - this.cqlType = cqlType; | |
| 35 | - this.javaType = javaType; | |
| 33 | + this(msg, null, cqlType, javaType); | |
| 36 | 34 | } |
| 37 | 35 | |
| 38 | 36 | public CodecNotFoundException(Throwable cause, DataType cqlType, TypeToken<?> javaType) { |
| 39 | - super(cause); | |
| 37 | + this(null, cause, cqlType, javaType); | |
| 38 | + } | |
| 39 | + | |
| 40 | + private CodecNotFoundException(String msg, Throwable cause, DataType cqlType, TypeToken<?>javaType) { | |
| 41 | + super(msg, cause); | |
| 40 | 42 | this.cqlType = cqlType; |
| 41 | 43 | this.javaType = javaType; |
| 42 | 44 | } |
| @@ -48,4 +50,9 @@ | ||
| 48 | 50 | public TypeToken<?> getJavaType() { |
| 49 | 51 | return javaType; |
| 50 | 52 | } |
| 53 | + | |
| 54 | + @Override | |
| 55 | + public CodecNotFoundException copy() { | |
| 56 | + return new CodecNotFoundException(getMessage(), getCause(), getCqlType(), getJavaType()); | |
| 57 | + } | |
| 51 | 58 | } |
modified driver-core/src/main/java/com/datastax/driver/core/policies/AddressTranslator.java +1 −1
| @@ -59,7 +59,7 @@ | ||
| 59 | 59 | * will always be the one set at Cluster construction time (9042 by default). |
| 60 | 60 | * @return the address the driver should actually use to connect to the node |
| 61 | 61 | * designated by {@code address}. If the return is {@code null}, then {@code |
| 62 | - * address} will be used by the driver (it is thus equivalent to returing | |
| 62 | + * address} will be used by the driver (it is thus equivalent to returning | |
| 63 | 63 | * {@code address} directly) |
| 64 | 64 | */ |
| 65 | 65 | InetSocketAddress translate(InetSocketAddress address); |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +1 −1
| @@ -342,7 +342,7 @@ | ||
| 342 | 342 | * When used in conjunction with {@link #withUsedHostsPerRemoteDc(int) usedHostsPerRemoteDc} > 0, this overrides the policy of |
| 343 | 343 | * never using remote datacenter nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is however inadvisable to do |
| 344 | 344 | * so in almost all cases, as this would potentially break consistency guarantees and if you are fine with that, it's probably |
| 345 | - * better to use a weaker consitency like {@code ONE}, {@code TWO} or {@code THREE}. As such, this method should generally be | |
| 345 | + * better to use a weaker consistency like {@code ONE}, {@code TWO} or {@code THREE}. As such, this method should generally be | |
| 346 | 346 | * avoided; use it only if you know and understand what you do. |
| 347 | 347 | * |
| 348 | 348 | * @return this builder. |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +16 −43
| @@ -44,9 +44,9 @@ | ||
| 44 | 44 | } |
| 45 | 45 | |
| 46 | 46 | /** |
| 47 | - * Defines whether to retry and at which consistency level on a read timeout. | |
| 47 | + * {@inheritDoc} | |
| 48 | 48 | * <p/> |
| 49 | - * This method triggers a maximum of one retry, and only if enough | |
| 49 | + * This implementation triggers a maximum of one retry, and only if enough | |
| 50 | 50 | * replicas had responded to the read request but data was not retrieved |
| 51 | 51 | * amongst those. Indeed, that case usually means that enough replica |
| 52 | 52 | * are alive to satisfy the consistency but the coordinator picked a |
| @@ -55,15 +55,6 @@ | ||
| 55 | 55 | * timeout the dead replica will likely have been detected as dead and |
| 56 | 56 | * the retry has a high chance of success. |
| 57 | 57 | * |
| 58 | - * @param statement the original query that timed out. | |
| 59 | - * @param cl the original consistency level of the read that timed out. | |
| 60 | - * @param requiredResponses the number of responses that were required to | |
| 61 | - * achieve the requested consistency level. | |
| 62 | - * @param receivedResponses the number of responses that had been received | |
| 63 | - * by the time the timeout exception was raised. | |
| 64 | - * @param dataRetrieved whether actual data (by opposition to data checksum) | |
| 65 | - * was present in the received responses. | |
| 66 | - * @param nbRetry the number of retries already performed for this operation. | |
| 67 | 58 | * @return {@code RetryDecision.retry(cl)} if no retry attempt has yet been tried and |
| 68 | 59 | * {@code receivedResponses >= requiredResponses && !dataRetrieved}, {@code RetryDecision.rethrow()} otherwise. |
| 69 | 60 | */ |
| @@ -76,9 +67,9 @@ | ||
| 76 | 67 | } |
| 77 | 68 | |
| 78 | 69 | /** |
| 79 | - * Defines whether to retry and at which consistency level on a write timeout. | |
| 70 | + * {@inheritDoc} | |
| 80 | 71 | * <p/> |
| 81 | - * This method triggers a maximum of one retry, and only in the case of | |
| 72 | + * This implementation triggers a maximum of one retry, and only in the case of | |
| 82 | 73 | * a {@code WriteType.BATCH_LOG} write. The reasoning for the retry in |
| 83 | 74 | * that case is that write to the distributed batch log is tried by the |
| 84 | 75 | * coordinator of the write against a small subset of all the nodes alive |
| @@ -88,14 +79,6 @@ | ||
| 88 | 79 | * nodes will likely have been detected as dead and the retry has thus a |
| 89 | 80 | * high chance of success. |
| 90 | 81 | * |
| 91 | - * @param statement the original query that timed out. | |
| 92 | - * @param cl the original consistency level of the write that timed out. | |
| 93 | - * @param writeType the type of the write that timed out. | |
| 94 | - * @param requiredAcks the number of acknowledgments that were required to | |
| 95 | - * achieve the requested consistency level. | |
| 96 | - * @param receivedAcks the number of acknowledgments that had been received | |
| 97 | - * by the time the timeout exception was raised. | |
| 98 | - * @param nbRetry the number of retry already performed for this operation. | |
| 99 | 82 | * @return {@code RetryDecision.retry(cl)} if no retry attempt has yet been tried and |
| 100 | 83 | * {@code writeType == WriteType.BATCH_LOG}, {@code RetryDecision.rethrow()} otherwise. |
| 101 | 84 | */ |
| @@ -105,37 +88,27 @@ | ||
| 105 | 88 | return RetryDecision.rethrow(); |
| 106 | 89 | |
| 107 | 90 | // If the batch log write failed, retry the operation as this might just be we were unlucky at picking candidates |
| 91 | + // JAVA-764: testing the write type automatically filters out serial consistency levels as these have always WriteType.CAS. | |
| 108 | 92 | return writeType == WriteType.BATCH_LOG ? RetryDecision.retry(cl) : RetryDecision.rethrow(); |
| 109 | 93 | } |
| 110 | 94 | |
| 111 | 95 | /** |
| 112 | - * Defines whether to retry and at which consistency level on an | |
| 113 | - * unavailable exception. | |
| 96 | + * {@inheritDoc} | |
| 114 | 97 | * <p/> |
| 115 | - * This method triggers a retry iff no retry has been executed before | |
| 116 | - * (nbRetry == 0), with | |
| 117 | - * {@link RetryPolicy.RetryDecision#tryNextHost(ConsistencyLevel) RetryDecision.tryNextHost(cl)}, | |
| 118 | - * otherwise it throws an exception. The retry will be processed on the next host | |
| 119 | - * in the query plan according to the current Load Balancing Policy. | |
| 120 | - * Where retrying on the same host in the event of an Unavailable exception | |
| 121 | - * has almost no chance of success, if the first replica tried happens to | |
| 122 | - * be "network" isolated from all the other nodes but can still answer to | |
| 123 | - * the client, it makes sense to retry the query on another node. | |
| 124 | - * | |
| 125 | - * @param statement the original query for which the consistency level cannot | |
| 126 | - * be achieved. | |
| 127 | - * @param cl the original consistency level for the operation. | |
| 128 | - * @param requiredReplica the number of replica that should have been | |
| 129 | - * (known) alive for the operation to be attempted. | |
| 130 | - * @param aliveReplica the number of replica that were know to be alive by | |
| 131 | - * the coordinator of the operation. | |
| 132 | - * @param nbRetry the number of retry already performed for this operation. | |
| 133 | - * @return {@code RetryDecision.rethrow()}. | |
| 98 | + * This implementation does the following: | |
| 99 | + * <ul> | |
| 100 | + * <li>if this is the first retry ({@code nbRetry == 0}), it triggers a retry on the next host in the query plan | |
| 101 | + * with the same consistency level ({@link RetryPolicy.RetryDecision#tryNextHost(ConsistencyLevel) RetryDecision#tryNextHost(null)}. | |
| 102 | + * The rationale is that the first coordinator might have been network-isolated from all other nodes (thinking | |
| 103 | + * they're down), but still able to communicate with the client; in that case, retrying on the same host has almost | |
| 104 | + * no chance of success, but moving to the next host might solve the issue.</li> | |
| 105 | + * <li>otherwise, the exception is rethrow.</li> | |
| 106 | + * </ul> | |
| 134 | 107 | */ |
| 135 | 108 | @Override |
| 136 | 109 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { |
| 137 | 110 | return (nbRetry == 0) |
| 138 | - ? RetryDecision.tryNextHost(cl) | |
| 111 | + ? RetryDecision.tryNextHost(null) | |
| 139 | 112 | : RetryDecision.rethrow(); |
| 140 | 113 | } |
| 141 | 114 |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +43 −57
| @@ -22,39 +22,47 @@ | ||
| 22 | 22 | import com.datastax.driver.core.exceptions.DriverException; |
| 23 | 23 | |
| 24 | 24 | /** |
| 25 | - * A retry policy that sometimes retry with a lower consistency level than | |
| 25 | + * A retry policy that sometimes retries with a lower consistency level than | |
| 26 | 26 | * the one initially requested. |
| 27 | 27 | * <p/> |
| 28 | - * <b>BEWARE</b>: This policy may retry queries using a lower consistency | |
| 28 | + * <b>BEWARE</b>: this policy may retry queries using a lower consistency | |
| 29 | 29 | * level than the one initially requested. By doing so, it may break |
| 30 | 30 | * consistency guarantees. In other words, if you use this retry policy, |
| 31 | - * there is cases (documented below) where a read at {@code QUORUM} | |
| 31 | + * there are cases (documented below) where a read at {@code QUORUM} | |
| 32 | 32 | * <b>may not</b> see a preceding write at {@code QUORUM}. Do not use this |
| 33 | 33 | * policy unless you have understood the cases where this can happen and |
| 34 | 34 | * are ok with that. It is also highly recommended to always wrap this |
| 35 | 35 | * policy into {@link LoggingRetryPolicy} to log the occurrences of |
| 36 | - * such consistency break. | |
| 36 | + * such consistency breaks. | |
| 37 | 37 | * <p/> |
| 38 | 38 | * This policy implements the same retries than the {@link DefaultRetryPolicy} |
| 39 | 39 | * policy. But on top of that, it also retries in the following cases: |
| 40 | 40 | * <ul> |
| 41 | - * <li>On a read timeout: if the number of replica that responded is | |
| 42 | - * greater than one but lower than is required by the requested | |
| 41 | + * <li>On a read timeout: if the number of replicas that responded is | |
| 42 | + * greater than one, but lower than is required by the requested | |
| 43 | 43 | * consistency level, the operation is retried at a lower consistency |
| 44 | 44 | * level.</li> |
| 45 | - * <li>On a write timeout: if the operation is an {@code | |
| 45 | + * <li>On a write timeout: if the operation is a {@code | |
| 46 | 46 | * WriteType.UNLOGGED_BATCH} and at least one replica acknowledged the |
| 47 | 47 | * write, the operation is retried at a lower consistency level. |
| 48 | - * Furthermore, for other operation, if at least one replica acknowledged | |
| 48 | + * Furthermore, for other operations, if at least one replica acknowledged | |
| 49 | 49 | * the write, the timeout is ignored.</li> |
| 50 | 50 | * <li>On an unavailable exception: if at least one replica is alive, the |
| 51 | 51 | * operation is retried at a lower consistency level.</li> |
| 52 | 52 | * </ul> |
| 53 | + * The lower consistency level to use for retries is determined by the following rules: | |
| 54 | + * <ul> | |
| 55 | + * <li>if more than 3 replicas responded, use {@code THREE}.</li> | |
| 56 | + * <li>if 1, 2 or 3 replicas responded, use the corresponding level {@code ONE}, {@code TWO} or {@code THREE}.</li> | |
| 57 | + * </ul> | |
| 58 | + * Note that if the initial consistency level was {@code EACH_QUORUM}, Cassandra returns the number of live replicas | |
| 59 | + * <em>in the datacenter that failed to reach consistency</em>, not the overall number in the cluster. Therefore if this | |
| 60 | + * number is 0, we still retry at {@code ONE}, on the assumption that a host may still be up in another datacenter. | |
| 53 | 61 | * <p/> |
| 54 | 62 | * The reasoning being this retry policy is the following one. If, based |
| 55 | 63 | * on the information the Cassandra coordinator node returns, retrying the |
| 56 | - * operation with the initially requested consistency has a change to | |
| 57 | - * succeed, do it. Otherwise, if based on these information we know <b>the | |
| 64 | + * operation with the initially requested consistency has a chance to | |
| 65 | + * succeed, do it. Otherwise, if based on this information we know <b>the | |
| 58 | 66 | * initially requested consistency level cannot be achieve currently</b>, then: |
| 59 | 67 | * <ul> |
| 60 | 68 | * <li>For writes, ignore the exception (thus silently failing the |
| @@ -75,37 +83,31 @@ | ||
| 75 | 83 | private DowngradingConsistencyRetryPolicy() { |
| 76 | 84 | } |
| 77 | 85 | |
| 78 | - private RetryDecision maxLikelyToWorkCL(int knownOk) { | |
| 86 | + private RetryDecision maxLikelyToWorkCL(int knownOk, ConsistencyLevel currentCL) { | |
| 79 | 87 | if (knownOk >= 3) |
| 80 | 88 | return RetryDecision.retry(ConsistencyLevel.THREE); |
| 81 | - else if (knownOk == 2) | |
| 89 | + | |
| 90 | + if (knownOk == 2) | |
| 82 | 91 | return RetryDecision.retry(ConsistencyLevel.TWO); |
| 83 | - else if (knownOk == 1) | |
| 92 | + | |
| 93 | + // JAVA-1005: EACH_QUORUM does not report a global number of alive replicas | |
| 94 | + // so even if we get 0 alive replicas, there might be | |
| 95 | + // a node up in some other datacenter | |
| 96 | + if (knownOk == 1 || currentCL == ConsistencyLevel.EACH_QUORUM) | |
| 84 | 97 | return RetryDecision.retry(ConsistencyLevel.ONE); |
| 85 | - else | |
| 86 | - return RetryDecision.rethrow(); | |
| 98 | + | |
| 99 | + return RetryDecision.rethrow(); | |
| 87 | 100 | } |
| 88 | 101 | |
| 89 | 102 | /** |
| 90 | - * Defines whether to retry and at which consistency level on a read timeout. | |
| 103 | + * {@inheritDoc} | |
| 91 | 104 | * <p/> |
| 92 | - * This method triggers a maximum of one retry. If less replica | |
| 105 | + * This implementation triggers a maximum of one retry. If less replica | |
| 93 | 106 | * responded than required by the consistency level (but at least one |
| 94 | 107 | * replica did respond), the operation is retried at a lower |
| 95 | 108 | * consistency level. If enough replica responded but data was not |
| 96 | 109 | * retrieve, the operation is retried with the initial consistency |
| 97 | 110 | * level. Otherwise, an exception is thrown. |
| 98 | - * | |
| 99 | - * @param statement the original query that timed out. | |
| 100 | - * @param cl the original consistency level of the read that timed out. | |
| 101 | - * @param requiredResponses the number of responses that were required to | |
| 102 | - * achieve the requested consistency level. | |
| 103 | - * @param receivedResponses the number of responses that had been received | |
| 104 | - * by the time the timeout exception was raised. | |
| 105 | - * @param dataRetrieved whether actual data (by opposition to data checksum) | |
| 106 | - * was present in the received responses. | |
| 107 | - * @param nbRetry the number of retry already performed for this operation. | |
| 108 | - * @return a RetryDecision as defined above. | |
| 109 | 111 | */ |
| 110 | 112 | @Override |
| 111 | 113 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { |
| @@ -116,21 +118,21 @@ | ||
| 116 | 118 | // normal consistency levels on the committing phase. So the main use case for CAS reads is probably for |
| 117 | 119 | // when you've timed out on a CAS write and want to make sure what happened. Downgrading in that case |
| 118 | 120 | // would be always wrong so we just special case to rethrow. |
| 119 | - if (cl == ConsistencyLevel.SERIAL || cl == ConsistencyLevel.LOCAL_SERIAL) | |
| 121 | + if (cl.isSerial()) | |
| 120 | 122 | return RetryDecision.rethrow(); |
| 121 | 123 | |
| 122 | 124 | if (receivedResponses < requiredResponses) { |
| 123 | 125 | // Tries the biggest CL that is expected to work |
| 124 | - return maxLikelyToWorkCL(receivedResponses); | |
| 126 | + return maxLikelyToWorkCL(receivedResponses, cl); | |
| 125 | 127 | } |
| 126 | 128 | |
| 127 | 129 | return !dataRetrieved ? RetryDecision.retry(cl) : RetryDecision.rethrow(); |
| 128 | 130 | } |
| 129 | 131 | |
| 130 | 132 | /** |
| 131 | - * Defines whether to retry and at which consistency level on a write timeout. | |
| 133 | + * {@inheritDoc} | |
| 132 | 134 | * <p/> |
| 133 | - * This method triggers a maximum of one retry. If {@code writeType == | |
| 135 | + * This implementation triggers a maximum of one retry. If {@code writeType == | |
| 134 | 136 | * WriteType.BATCH_LOG}, the write is retried with the initial |
| 135 | 137 | * consistency level. If {@code writeType == WriteType.UNLOGGED_BATCH} |
| 136 | 138 | * and at least one replica acknowledged, the write is retried with a |
| @@ -139,16 +141,6 @@ | ||
| 139 | 141 | * all, even if {@code receivedAcks > 0}). For other write types ({@code WriteType.SIMPLE} |
| 140 | 142 | * and {@code WriteType.BATCH}), if we know the write has been persisted on at |
| 141 | 143 | * least one replica, we ignore the exception. Otherwise, an exception is thrown. |
| 142 | - * | |
| 143 | - * @param statement the original query that timed out. | |
| 144 | - * @param cl the original consistency level of the write that timed out. | |
| 145 | - * @param writeType the type of the write that timed out. | |
| 146 | - * @param requiredAcks the number of acknowledgments that were required to | |
| 147 | - * achieve the requested consistency level. | |
| 148 | - * @param receivedAcks the number of acknowledgments that had been received | |
| 149 | - * by the time the timeout exception was raised. | |
| 150 | - * @param nbRetry the number of retry already performed for this operation. | |
| 151 | - * @return a RetryDecision as defined above. | |
| 152 | 144 | */ |
| 153 | 145 | @Override |
| 154 | 146 | public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { |
| @@ -163,7 +155,7 @@ | ||
| 163 | 155 | case UNLOGGED_BATCH: |
| 164 | 156 | // Since only part of the batch could have been persisted, |
| 165 | 157 | // retry with whatever consistency should allow to persist all |
| 166 | - return maxLikelyToWorkCL(receivedAcks); | |
| 158 | + return maxLikelyToWorkCL(receivedAcks, cl); | |
| 167 | 159 | case BATCH_LOG: |
| 168 | 160 | return RetryDecision.retry(cl); |
| 169 | 161 | } |
| @@ -172,30 +164,24 @@ | ||
| 172 | 164 | } |
| 173 | 165 | |
| 174 | 166 | /** |
| 175 | - * Defines whether to retry and at which consistency level on an | |
| 176 | - * unavailable exception. | |
| 167 | + * {@inheritDoc} | |
| 177 | 168 | * <p/> |
| 178 | - * This method triggers a maximum of one retry. If at least one replica | |
| 169 | + * This implementation triggers a maximum of one retry. If at least one replica | |
| 179 | 170 | * is know to be alive, the operation is retried at a lower consistency |
| 180 | 171 | * level. |
| 181 | - * | |
| 182 | - * @param statement the original query for which the consistency level cannot | |
| 183 | - * be achieved. | |
| 184 | - * @param cl the original consistency level for the operation. | |
| 185 | - * @param requiredReplica the number of replica that should have been | |
| 186 | - * (known) alive for the operation to be attempted. | |
| 187 | - * @param aliveReplica the number of replica that were know to be alive by | |
| 188 | - * the coordinator of the operation. | |
| 189 | - * @param nbRetry the number of retry already performed for this operation. | |
| 190 | - * @return a RetryDecision as defined above. | |
| 191 | 172 | */ |
| 192 | 173 | @Override |
| 193 | 174 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { |
| 194 | 175 | if (nbRetry != 0) |
| 195 | 176 | return RetryDecision.rethrow(); |
| 196 | 177 | |
| 178 | + // JAVA-764: if the requested consistency level is serial, it means that the operation failed at the paxos phase of a LWT. | |
| 179 | + // Retry on the next host, on the assumption that the initial coordinator could be network-isolated. | |
| 180 | + if (cl.isSerial()) | |
| 181 | + return RetryDecision.tryNextHost(null); | |
| 182 | + | |
| 197 | 183 | // Tries the biggest CL that is expected to work |
| 198 | - return maxLikelyToWorkCL(aliveReplica); | |
| 184 | + return maxLikelyToWorkCL(aliveReplica, cl); | |
| 199 | 185 | } |
| 200 | 186 | |
| 201 | 187 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java +12 −38
| @@ -22,10 +22,10 @@ | ||
| 22 | 22 | import com.datastax.driver.core.exceptions.DriverException; |
| 23 | 23 | |
| 24 | 24 | /** |
| 25 | - * A retry policy that never retry (nor ignore). | |
| 25 | + * A retry policy that never retries (nor ignores). | |
| 26 | 26 | * <p/> |
| 27 | - * All of the methods of this retry policy unconditionally return {@link RetryPolicy.RetryDecision#rethrow}. | |
| 28 | - * If this policy is used, retry will have to be implemented in business code. | |
| 27 | + * All of the methods of this retry policy unconditionally return {@link RetryDecision#rethrow()}. | |
| 28 | + * If this policy is used, retry logic will have to be implemented in business code. | |
| 29 | 29 | */ |
| 30 | 30 | public class FallthroughRetryPolicy implements RetryPolicy { |
| 31 | 31 | |
| @@ -35,18 +35,9 @@ | ||
| 35 | 35 | } |
| 36 | 36 | |
| 37 | 37 | /** |
| 38 | - * Defines whether to retry and at which consistency level on a read timeout. | |
| 39 | - * | |
| 40 | - * @param statement the original query that timed out. | |
| 41 | - * @param cl the original consistency level of the read that timed out. | |
| 42 | - * @param requiredResponses the number of responses that were required to | |
| 43 | - * achieve the requested consistency level. | |
| 44 | - * @param receivedResponses the number of responses that had been received | |
| 45 | - * by the time the timeout exception was raised. | |
| 46 | - * @param dataRetrieved whether actual data (by opposition to data checksum) | |
| 47 | - * was present in the received responses. | |
| 48 | - * @param nbRetry the number of retry already performed for this operation. | |
| 49 | - * @return {@code RetryDecision.rethrow()}. | |
| 38 | + * {@inheritDoc} | |
| 39 | + * <p/> | |
| 40 | + * This implementation always returns {@code RetryDecision.rethrow()}. | |
| 50 | 41 | */ |
| 51 | 42 | @Override |
| 52 | 43 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { |
| @@ -54,17 +45,9 @@ | ||
| 54 | 45 | } |
| 55 | 46 | |
| 56 | 47 | /** |
| 57 | - * Defines whether to retry and at which consistency level on a write timeout. | |
| 58 | - * | |
| 59 | - * @param statement the original query that timed out. | |
| 60 | - * @param cl the original consistency level of the write that timed out. | |
| 61 | - * @param writeType the type of the write that timed out. | |
| 62 | - * @param requiredAcks the number of acknowledgments that were required to | |
| 63 | - * achieve the requested consistency level. | |
| 64 | - * @param receivedAcks the number of acknowledgments that had been received | |
| 65 | - * by the time the timeout exception was raised. | |
| 66 | - * @param nbRetry the number of retry already performed for this operation. | |
| 67 | - * @return {@code RetryDecision.rethrow()}. | |
| 48 | + * {@inheritDoc} | |
| 49 | + * <p/> | |
| 50 | + * This implementation always returns {@code RetryDecision.rethrow()}. | |
| 68 | 51 | */ |
| 69 | 52 | @Override |
| 70 | 53 | public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { |
| @@ -72,18 +55,9 @@ | ||
| 72 | 55 | } |
| 73 | 56 | |
| 74 | 57 | /** |
| 75 | - * Defines whether to retry and at which consistency level on an | |
| 76 | - * unavailable exception. | |
| 77 | - * | |
| 78 | - * @param statement the original query for which the consistency level cannot | |
| 79 | - * be achieved. | |
| 80 | - * @param cl the original consistency level for the operation. | |
| 81 | - * @param requiredReplica the number of replica that should have been | |
| 82 | - * (known) alive for the operation to be attempted. | |
| 83 | - * @param aliveReplica the number of replica that were know to be alive by | |
| 84 | - * the coordinator of the operation. | |
| 85 | - * @param nbRetry the number of retry already performed for this operation. | |
| 86 | - * @return {@code RetryDecision.rethrow()}. | |
| 58 | + * {@inheritDoc} | |
| 59 | + * <p/> | |
| 60 | + * This implementation always returns {@code RetryDecision.rethrow()}. | |
| 87 | 61 | */ |
| 88 | 62 | @Override |
| 89 | 63 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { |
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java +8 −3
| @@ -27,9 +27,14 @@ | ||
| 27 | 27 | /** |
| 28 | 28 | * A retry policy that wraps another policy, logging the decision made by its sub-policy. |
| 29 | 29 | * <p/> |
| 30 | - * Note that this policy only log the IGNORE and RETRY decisions (since | |
| 31 | - * RETHROW decisions are just meant to propagate the cassandra exception). The | |
| 32 | - * logging is done at the INFO level. | |
| 30 | + * Note that this policy only logs | |
| 31 | + * {@link com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type#RETRY RETRY} and | |
| 32 | + * {@link com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type#IGNORE IGNORE} decisions (since | |
| 33 | + * {@link com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type#RETHROW RETHROW} decisions | |
| 34 | + * are just meant to propagate the Cassandra exception). | |
| 35 | + * <p/> | |
| 36 | + * The logging is done at the INFO level and the logger name is | |
| 37 | + * {@code com.datastax.driver.core.policies.LoggingRetryPolicy}. | |
| 33 | 38 | */ |
| 34 | 39 | public class LoggingRetryPolicy implements RetryPolicy { |
| 35 | 40 |
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +1 −2
| @@ -16,7 +16,6 @@ | ||
| 16 | 16 | package com.datastax.driver.core.policies; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.AtomicMonotonicTimestampGenerator; |
| 19 | -import com.datastax.driver.core.ServerSideTimestampGenerator; | |
| 20 | 19 | import com.datastax.driver.core.TimestampGenerator; |
| 21 | 20 | import com.google.common.base.Objects; |
| 22 | 21 | |
| @@ -115,7 +114,7 @@ | ||
| 115 | 114 | /** |
| 116 | 115 | * The default timestamp generator. |
| 117 | 116 | * <p/> |
| 118 | - * This is an instance of {@link ServerSideTimestampGenerator}. | |
| 117 | + * This is an instance of {@link AtomicMonotonicTimestampGenerator}. | |
| 119 | 118 | * |
| 120 | 119 | * @return the default timestamp generator. |
| 121 | 120 | */ |
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +43 −9
| @@ -74,7 +74,7 @@ | ||
| 74 | 74 | * {@code IGNORE} or a {@code RETHROW} decision; |
| 75 | 75 | * for a {@code RETRY} decision, the consistency level can be {@code null}, |
| 76 | 76 | * in which case the retry is done at the same consistency level |
| 77 | - * as in the original attempt. | |
| 77 | + * as in the previous attempt. | |
| 78 | 78 | * |
| 79 | 79 | * @return the consistency level for a retry decision. |
| 80 | 80 | */ |
| @@ -105,8 +105,16 @@ | ||
| 105 | 105 | /** |
| 106 | 106 | * Creates a {@link RetryDecision.Type#RETRY} retry decision using |
| 107 | 107 | * the same host and the provided consistency level. |
| 108 | + * <p/> | |
| 109 | + * If the provided consistency level is {@code null}, the retry will be done at the same consistency level as | |
| 110 | + * the previous attempt. | |
| 111 | + * <p/> | |
| 112 | + * Beware that {@link ConsistencyLevel#isSerial() serial} consistency levels | |
| 113 | + * should never be passed to this method; attempting to do so would trigger an | |
| 114 | + * {@link com.datastax.driver.core.exceptions.InvalidQueryException InvalidQueryException}. | |
| 108 | 115 | * |
| 109 | - * @param consistency the consistency level to use for the retry. | |
| 116 | + * @param consistency the consistency level to use for the retry; if {@code null}, | |
| 117 | + * the same level as the previous attempt will be used. | |
| 110 | 118 | * @return a {@link RetryDecision.Type#RETRY} decision using |
| 111 | 119 | * the same host and the provided consistency level |
| 112 | 120 | */ |
| @@ -126,19 +134,30 @@ | ||
| 126 | 134 | /** |
| 127 | 135 | * Creates a {@link RetryDecision.Type#RETRY} retry decision using the next host |
| 128 | 136 | * in the query plan, and using the provided consistency level. |
| 137 | + * <p/> | |
| 138 | + * If the provided consistency level is {@code null}, the retry will be done at the same consistency level as | |
| 139 | + * the previous attempt. | |
| 140 | + * <p/> | |
| 141 | + * Beware that {@link ConsistencyLevel#isSerial() serial} consistency levels | |
| 142 | + * should never be passed to this method; attempting to do so would trigger an | |
| 143 | + * {@link com.datastax.driver.core.exceptions.InvalidQueryException InvalidQueryException}. | |
| 129 | 144 | * |
| 145 | + * @param consistency the consistency level to use for the retry; if {@code null}, | |
| 146 | + * the same level as the previous attempt will be used. | |
| 130 | 147 | * @return a {@link RetryDecision.Type#RETRY} retry decision using the next host |
| 131 | 148 | * in the query plan, and using the provided consistency level. |
| 132 | 149 | */ |
| 133 | - public static RetryDecision tryNextHost(ConsistencyLevel retryCL) { | |
| 134 | - return new RetryDecision(Type.RETRY, retryCL, false); | |
| 150 | + public static RetryDecision tryNextHost(ConsistencyLevel consistency) { | |
| 151 | + return new RetryDecision(Type.RETRY, consistency, false); | |
| 135 | 152 | } |
| 136 | 153 | |
| 137 | 154 | @Override |
| 138 | 155 | public String toString() { |
| 139 | 156 | switch (type) { |
| 140 | 157 | case RETRY: |
| 141 | - return "Retry at " + retryCL + " on " + (retryCurrent ? "same " : "next ") + "host."; | |
| 158 | + String retryClDesc = (retryCL == null) ? "same CL" : retryCL.toString(); | |
| 159 | + String hostDesc = retryCurrent ? "same" : "next"; | |
| 160 | + return "Retry at " + retryClDesc + " on " + hostDesc + " host."; | |
| 142 | 161 | case RETHROW: |
| 143 | 162 | return "Rethrow"; |
| 144 | 163 | case IGNORE: |
| @@ -157,7 +176,9 @@ | ||
| 157 | 176 | * {@link com.datastax.driver.core.exceptions.ReadTimeoutException#wasDataRetrieved}). |
| 158 | 177 | * |
| 159 | 178 | * @param statement the original query that timed out. |
| 160 | - * @param cl the original consistency level of the read that timed out. | |
| 179 | + * @param cl the requested consistency level of the read that timed out. | |
| 180 | + * Note that this can never be a {@link ConsistencyLevel#isSerial() serial} | |
| 181 | + * consistency level. | |
| 161 | 182 | * @param requiredResponses the number of responses that were required to |
| 162 | 183 | * achieve the requested consistency level. |
| 163 | 184 | * @param receivedResponses the number of responses that had been received |
| @@ -175,7 +196,13 @@ | ||
| 175 | 196 | * Defines whether to retry and at which consistency level on a write timeout. |
| 176 | 197 | * |
| 177 | 198 | * @param statement the original query that timed out. |
| 178 | - * @param cl the original consistency level of the write that timed out. | |
| 199 | + * @param cl the requested consistency level of the write that timed out. | |
| 200 | + * If the timeout occurred at the "paxos" phase of a | |
| 201 | + * <a href="https://docs.datastax.com/en/cassandra/2.1/cassandra/dml/dml_ltwt_transaction_c.html">Lightweight transaction</a>, | |
| 202 | + * then {@code cl} will actually be the requested {@link ConsistencyLevel#isSerial() serial} consistency level. | |
| 203 | + * <em>Beware that serial consistency levels should never be passed to a {@link RetryDecision RetryDecision} as this would | |
| 204 | + * invariably trigger an {@link com.datastax.driver.core.exceptions.InvalidQueryException InvalidQueryException}</em>. | |
| 205 | + * Also, when {@code cl} is {@link ConsistencyLevel#isSerial() serial}, then {@code writeType} is always {@link WriteType#CAS CAS}. | |
| 179 | 206 | * @param writeType the type of the write that timed out. |
| 180 | 207 | * @param requiredAcks the number of acknowledgments that were required to |
| 181 | 208 | * achieve the requested consistency level. |
| @@ -194,7 +221,12 @@ | ||
| 194 | 221 | * |
| 195 | 222 | * @param statement the original query for which the consistency level cannot |
| 196 | 223 | * be achieved. |
| 197 | - * @param cl the original consistency level for the operation. | |
| 224 | + * @param cl the requested consistency level for the operation. | |
| 225 | + * If the operation failed at the "paxos" phase of a | |
| 226 | + * <a href="https://docs.datastax.com/en/cassandra/2.1/cassandra/dml/dml_ltwt_transaction_c.html">Lightweight transaction</a>, | |
| 227 | + * then {@code cl} will actually be the requested {@link ConsistencyLevel#isSerial() serial} consistency level. | |
| 228 | + * <em>Beware that serial consistency levels should never be passed to a {@link RetryDecision RetryDecision} as this would | |
| 229 | + * invariably trigger an {@link com.datastax.driver.core.exceptions.InvalidQueryException InvalidQueryException}</em>. | |
| 198 | 230 | * @param requiredReplica the number of replica that should have been |
| 199 | 231 | * (known) alive for the operation to be attempted. |
| 200 | 232 | * @param aliveReplica the number of replica that were know to be alive by |
| @@ -224,7 +256,9 @@ | ||
| 224 | 256 | * is known to be idempotent. |
| 225 | 257 | * |
| 226 | 258 | * @param statement the original query that failed. |
| 227 | - * @param cl the original consistency level for the operation. | |
| 259 | + * @param cl the requested consistency level for the operation. | |
| 260 | + * Note that this is not necessarily the achieved consistency level (if any), | |
| 261 | + * and it is never a {@link ConsistencyLevel#isSerial() serial} one. | |
| 228 | 262 | * @param e the exception that caused this request to fail. |
| 229 | 263 | * @param nbRetry the number of retries already performed for this operation. |
| 230 | 264 | * @return the retry decision. If {@code RetryDecision.RETHROW} is returned, |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +1 −1
| @@ -37,7 +37,7 @@ | ||
| 37 | 37 | private int nonBuiltStatementValues; |
| 38 | 38 | |
| 39 | 39 | Batch(RegularStatement[] statements, boolean logged) { |
| 40 | - super((String) null); | |
| 40 | + super(null, null, null); | |
| 41 | 41 | this.statements = statements.length == 0 |
| 42 | 42 | ? new ArrayList<RegularStatement>() |
| 43 | 43 | : new ArrayList<RegularStatement>(statements.length); |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +6 −12
| @@ -77,7 +77,7 @@ | ||
| 77 | 77 | */ |
| 78 | 78 | public abstract class BuiltStatement extends RegularStatement { |
| 79 | 79 | |
| 80 | - private static final Pattern lowercaseId = Pattern.compile("[a-z][a-z0-9_]*"); | |
| 80 | + private static final Pattern lowercaseAlphanumeric = Pattern.compile("[a-z][a-z0-9_]*"); | |
| 81 | 81 | |
| 82 | 82 | private final List<ColumnMetadata> partitionKey; |
| 83 | 83 | private final List<Object> routingKeyValues; |
| @@ -94,22 +94,16 @@ | ||
| 94 | 94 | boolean hasBindMarkers; |
| 95 | 95 | private boolean forceNoValues; |
| 96 | 96 | |
| 97 | - BuiltStatement(String keyspace) { | |
| 98 | - this.partitionKey = null; | |
| 99 | - this.routingKeyValues = null; | |
| 97 | + BuiltStatement(String keyspace, List<ColumnMetadata> partitionKey, List<Object> routingKeyValues) { | |
| 98 | + this.partitionKey = partitionKey; | |
| 99 | + this.routingKeyValues = routingKeyValues; | |
| 100 | 100 | this.keyspace = keyspace; |
| 101 | 101 | } |
| 102 | 102 | |
| 103 | - BuiltStatement(TableMetadata tableMetadata) { | |
| 104 | - this.partitionKey = tableMetadata.getPartitionKey(); | |
| 105 | - this.routingKeyValues = Arrays.asList(new Object[tableMetadata.getPartitionKey().size()]); | |
| 106 | - this.keyspace = escapeId(tableMetadata.getKeyspace().getName()); | |
| 107 | - } | |
| 108 | - | |
| 109 | 103 | // Same as Metadata.escapeId, but we don't have access to it here. |
| 110 | 104 | protected static String escapeId(String ident) { |
| 111 | 105 | // we don't need to escape if it's lowercase and match non-quoted CQL3 ids. |
| 112 | - return lowercaseId.matcher(ident).matches() ? ident : Metadata.quote(ident); | |
| 106 | + return lowercaseAlphanumeric.matcher(ident).matches() ? ident : Metadata.quote(ident); | |
| 113 | 107 | } |
| 114 | 108 | |
| 115 | 109 | @Override |
| @@ -352,7 +346,7 @@ | ||
| 352 | 346 | T statement; |
| 353 | 347 | |
| 354 | 348 | ForwardingStatement(T statement) { |
| 355 | - super((String) null); | |
| 349 | + super(null, null, null); | |
| 356 | 350 | this.statement = statement; |
| 357 | 351 | } |
| 358 | 352 |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +59 −0
| @@ -224,4 +224,63 @@ | ||
| 224 | 224 | sb.append(")"); |
| 225 | 225 | } |
| 226 | 226 | } |
| 227 | + | |
| 228 | + static class CompoundInClause extends Clause { | |
| 229 | + private final List<String> names; | |
| 230 | + private final List<List<?>> valueLists; | |
| 231 | + | |
| 232 | + public CompoundInClause(List<String> names, List<List<?>> valueLists) { | |
| 233 | + this.names = names; | |
| 234 | + this.valueLists = valueLists; | |
| 235 | + } | |
| 236 | + | |
| 237 | + @Override | |
| 238 | + String name() { | |
| 239 | + // This is only used for routing key purpose, and so far CompoundClause | |
| 240 | + // are not allowed for the partitionKey anyway | |
| 241 | + return null; | |
| 242 | + } | |
| 243 | + | |
| 244 | + @Override | |
| 245 | + Object firstValue() { | |
| 246 | + // This is only used for routing key purpose, and so far CompoundClause | |
| 247 | + // are not allowed for the partitionKey anyway | |
| 248 | + return null; | |
| 249 | + } | |
| 250 | + | |
| 251 | + @Override | |
| 252 | + boolean containsBindMarker() { | |
| 253 | + for (List<?> values : valueLists) | |
| 254 | + for (Object value : values) | |
| 255 | + if (Utils.containsBindMarker(value)) | |
| 256 | + return true; | |
| 257 | + return false; | |
| 258 | + } | |
| 259 | + | |
| 260 | + @Override | |
| 261 | + void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) { | |
| 262 | + sb.append("("); | |
| 263 | + for (int i = 0; i < names.size(); i++) { | |
| 264 | + if (i > 0) | |
| 265 | + sb.append(","); | |
| 266 | + Utils.appendName(names.get(i), sb); | |
| 267 | + } | |
| 268 | + sb.append(")").append(" IN ").append("("); | |
| 269 | + for (int i = 0; i < valueLists.size(); i++) { | |
| 270 | + if (i > 0) | |
| 271 | + sb.append(","); | |
| 272 | + | |
| 273 | + List<?> values = valueLists.get(i); | |
| 274 | + | |
| 275 | + // Special case when there is only one bind marker: "IN ?" instead of "IN (?)" | |
| 276 | + if (values.size() == 1 && values.get(0) instanceof BindMarker) { | |
| 277 | + sb.append(values.get(0)); | |
| 278 | + } else { | |
| 279 | + sb.append("("); | |
| 280 | + Utils.joinAndAppendValues(sb, codecRegistry, ",", values, variables).append(')'); | |
| 281 | + } | |
| 282 | + } | |
| 283 | + sb.append(")"); | |
| 284 | + } | |
| 285 | + } | |
| 227 | 286 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +73 −16
| @@ -16,9 +16,11 @@ | ||
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CodecRegistry; |
| 19 | +import com.datastax.driver.core.ColumnMetadata; | |
| 19 | 20 | import com.datastax.driver.core.TableMetadata; |
| 20 | 21 | |
| 21 | 22 | import java.util.ArrayList; |
| 23 | +import java.util.Arrays; | |
| 22 | 24 | import java.util.List; |
| 23 | 25 | |
| 24 | 26 | /** |
| @@ -34,21 +36,33 @@ | ||
| 34 | 36 | private boolean ifExists; |
| 35 | 37 | |
| 36 | 38 | Delete(String keyspace, String table, List<Selector> columns) { |
| 37 | - super(keyspace); | |
| 38 | - this.table = table; | |
| 39 | - this.columns = columns; | |
| 40 | - this.where = new Where(this); | |
| 41 | - this.usings = new Options(this); | |
| 42 | - this.conditions = new Conditions(this); | |
| 39 | + this(keyspace, table, null, null, columns); | |
| 43 | 40 | } |
| 44 | 41 | |
| 45 | 42 | Delete(TableMetadata table, List<Selector> columns) { |
| 46 | - super(table); | |
| 47 | - this.table = escapeId(table.getName()); | |
| 43 | + this(escapeId(table.getKeyspace().getName()), | |
| 44 | + escapeId(table.getName()), | |
| 45 | + Arrays.asList(new Object[table.getPartitionKey().size()]), | |
| 46 | + table.getPartitionKey(), | |
| 47 | + columns); | |
| 48 | + } | |
| 49 | + | |
| 50 | + Delete(String keyspace, | |
| 51 | + String table, | |
| 52 | + List<Object> routingKeyValues, | |
| 53 | + List<ColumnMetadata> partitionKey, | |
| 54 | + List<Selector> columns) { | |
| 55 | + super(keyspace, partitionKey, routingKeyValues); | |
| 56 | + this.table = table; | |
| 48 | 57 | this.columns = columns; |
| 49 | 58 | this.where = new Where(this); |
| 50 | 59 | this.usings = new Options(this); |
| 51 | 60 | this.conditions = new Conditions(this); |
| 61 | + | |
| 62 | + // This is for JAVA-1089, if the query deletes an element in a list, the statement should be non-idempotent. | |
| 63 | + if (!areIdempotent(columns)) { | |
| 64 | + setNonIdempotentOps(); | |
| 65 | + } | |
| 52 | 66 | } |
| 53 | 67 | |
| 54 | 68 | @Override |
| @@ -110,6 +124,9 @@ | ||
| 110 | 124 | * Adds a conditions clause (IF) to this statement. |
| 111 | 125 | * <p/> |
| 112 | 126 | * This is a shorter/more readable version for {@code onlyIf().and(condition)}. |
| 127 | + * <p/> | |
| 128 | + * This will configure the statement as non-idempotent, see {@link com.datastax.driver.core.Statement#isIdempotent()} | |
| 129 | + * for more information. | |
| 113 | 130 | * |
| 114 | 131 | * @param condition the condition to add. |
| 115 | 132 | * @return the conditions of this query to which more conditions can be added. |
| @@ -120,6 +137,9 @@ | ||
| 120 | 137 | |
| 121 | 138 | /** |
| 122 | 139 | * Adds a conditions clause (IF) to this statement. |
| 140 | + * <p/> | |
| 141 | + * This will configure the statement as non-idempotent, see {@link com.datastax.driver.core.Statement#isIdempotent()} | |
| 142 | + * for more information. | |
| 123 | 143 | * |
| 124 | 144 | * @return the conditions of this query to which more conditions can be added. |
| 125 | 145 | */ |
| @@ -161,11 +181,14 @@ | ||
| 161 | 181 | * Please keep in mind that using this option has a non negligible |
| 162 | 182 | * performance impact and should be avoided when possible. |
| 163 | 183 | * </p> |
| 184 | + * This will configure the statement as non-idempotent, see {@link com.datastax.driver.core.Statement#isIdempotent()} | |
| 185 | + * for more information. | |
| 164 | 186 | * |
| 165 | 187 | * @return this DELETE statement. |
| 166 | 188 | */ |
| 167 | 189 | public Delete ifExists() { |
| 168 | 190 | this.ifExists = true; |
| 191 | + setNonIdempotentOps(); | |
| 169 | 192 | return this; |
| 170 | 193 | } |
| 171 | 194 | |
| @@ -189,6 +212,9 @@ | ||
| 189 | 212 | public Where and(Clause clause) { |
| 190 | 213 | clauses.add(clause); |
| 191 | 214 | statement.maybeAddRoutingKey(clause.name(), clause.firstValue()); |
| 215 | + if (!hasNonIdempotentOps() && !Utils.isIdempotent(clause)) { | |
| 216 | + statement.setNonIdempotentOps(); | |
| 217 | + } | |
| 192 | 218 | checkForBindMarkers(clause); |
| 193 | 219 | return this; |
| 194 | 220 | } |
| @@ -354,7 +380,7 @@ | ||
| 354 | 380 | * @return this in-build DELETE Selection |
| 355 | 381 | */ |
| 356 | 382 | public Selection listElt(String columnName, int idx) { |
| 357 | - columns.add(new CollectionElementSelector(columnName, idx)); | |
| 383 | + columns.add(new ListElementSelector(columnName, idx)); | |
| 358 | 384 | return this; |
| 359 | 385 | } |
| 360 | 386 | |
| @@ -367,7 +393,7 @@ | ||
| 367 | 393 | * @return this in-build DELETE Selection |
| 368 | 394 | */ |
| 369 | 395 | public Selection listElt(String columnName, BindMarker idx) { |
| 370 | - columns.add(new CollectionElementSelector(columnName, idx)); | |
| 396 | + columns.add(new ListElementSelector(columnName, idx)); | |
| 371 | 397 | return this; |
| 372 | 398 | } |
| 373 | 399 | |
| @@ -379,7 +405,7 @@ | ||
| 379 | 405 | * @return this in-build DELETE Selection |
| 380 | 406 | */ |
| 381 | 407 | public Selection setElt(String columnName, Object element) { |
| 382 | - columns.add(new CollectionElementSelector(columnName, element)); | |
| 408 | + columns.add(new SetElementSelector(columnName, element)); | |
| 383 | 409 | return this; |
| 384 | 410 | } |
| 385 | 411 | |
| @@ -392,7 +418,7 @@ | ||
| 392 | 418 | * @return this in-build DELETE Selection |
| 393 | 419 | */ |
| 394 | 420 | public Selection setElt(String columnName, BindMarker element) { |
| 395 | - columns.add(new CollectionElementSelector(columnName, element)); | |
| 421 | + columns.add(new SetElementSelector(columnName, element)); | |
| 396 | 422 | return this; |
| 397 | 423 | } |
| 398 | 424 | |
| @@ -404,7 +430,7 @@ | ||
| 404 | 430 | * @return this in-build DELETE Selection |
| 405 | 431 | */ |
| 406 | 432 | public Selection mapElt(String columnName, Object key) { |
| 407 | - columns.add(new CollectionElementSelector(columnName, key)); | |
| 433 | + columns.add(new MapElementSelector(columnName, key)); | |
| 408 | 434 | return this; |
| 409 | 435 | } |
| 410 | 436 | } |
| @@ -414,7 +440,7 @@ | ||
| 414 | 440 | * A selector can be either a column name, |
| 415 | 441 | * a list element, a set element or a map entry. |
| 416 | 442 | */ |
| 417 | - static class Selector extends Utils.Appendeable { | |
| 443 | + private static class Selector extends Utils.Appendeable { | |
| 418 | 444 | |
| 419 | 445 | private final String columnName; |
| 420 | 446 | |
| @@ -441,9 +467,9 @@ | ||
| 441 | 467 | /** |
| 442 | 468 | * A selector representing a list index, a set element or a map key in a DELETE selection clause. |
| 443 | 469 | */ |
| 444 | - static class CollectionElementSelector extends Selector { | |
| 470 | + private static class CollectionElementSelector extends Selector { | |
| 445 | 471 | |
| 446 | - private final Object key; | |
| 472 | + protected final Object key; | |
| 447 | 473 | |
| 448 | 474 | CollectionElementSelector(String columnName, Object key) { |
| 449 | 475 | super(columnName); |
| @@ -465,6 +491,36 @@ | ||
| 465 | 491 | |
| 466 | 492 | } |
| 467 | 493 | |
| 494 | + private static class ListElementSelector extends CollectionElementSelector { | |
| 495 | + | |
| 496 | + ListElementSelector(String columnName, Object key) { | |
| 497 | + super(columnName, key); | |
| 498 | + } | |
| 499 | + } | |
| 500 | + | |
| 501 | + private static class SetElementSelector extends CollectionElementSelector { | |
| 502 | + | |
| 503 | + SetElementSelector(String columnName, Object key) { | |
| 504 | + super(columnName, key); | |
| 505 | + } | |
| 506 | + } | |
| 507 | + | |
| 508 | + private static class MapElementSelector extends CollectionElementSelector { | |
| 509 | + | |
| 510 | + MapElementSelector(String columnName, Object key) { | |
| 511 | + super(columnName, key); | |
| 512 | + } | |
| 513 | + } | |
| 514 | + | |
| 515 | + private boolean areIdempotent(List<Selector> selectors) { | |
| 516 | + for (Selector sel : selectors) { | |
| 517 | + if (sel instanceof ListElementSelector) { | |
| 518 | + return false; | |
| 519 | + } | |
| 520 | + } | |
| 521 | + return true; | |
| 522 | + } | |
| 523 | + | |
| 468 | 524 | /** |
| 469 | 525 | * Conditions for a DELETE statement. |
| 470 | 526 | * <p> |
| @@ -494,6 +550,7 @@ | ||
| 494 | 550 | * @return this {@code Conditions} clause. |
| 495 | 551 | */ |
| 496 | 552 | public Conditions and(Clause condition) { |
| 553 | + statement.setNonIdempotentOps(); | |
| 497 | 554 | conditions.add(condition); |
| 498 | 555 | checkForBindMarkers(condition); |
| 499 | 556 | return this; |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +18 −5
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CodecRegistry; |
| 19 | +import com.datastax.driver.core.ColumnMetadata; | |
| 19 | 20 | import com.datastax.driver.core.TableMetadata; |
| 20 | 21 | |
| 21 | 22 | import java.util.ArrayList; |
| @@ -34,14 +35,22 @@ | ||
| 34 | 35 | private boolean ifNotExists; |
| 35 | 36 | |
| 36 | 37 | Insert(String keyspace, String table) { |
| 37 | - super(keyspace); | |
| 38 | - this.table = table; | |
| 39 | - this.usings = new Options(this); | |
| 38 | + this(keyspace, table, null, null); | |
| 40 | 39 | } |
| 41 | 40 | |
| 42 | 41 | Insert(TableMetadata table) { |
| 43 | - super(table); | |
| 44 | - this.table = escapeId(table.getName()); | |
| 42 | + this(escapeId(table.getKeyspace().getName()), | |
| 43 | + escapeId(table.getName()), | |
| 44 | + Arrays.asList(new Object[table.getPartitionKey().size()]), | |
| 45 | + table.getPartitionKey()); | |
| 46 | + } | |
| 47 | + | |
| 48 | + Insert(String keyspace, | |
| 49 | + String table, | |
| 50 | + List<Object> routingKeyValues, | |
| 51 | + List<ColumnMetadata> partitionKey) { | |
| 52 | + super(keyspace, partitionKey, routingKeyValues); | |
| 53 | + this.table = table; | |
| 45 | 54 | this.usings = new Options(this); |
| 46 | 55 | } |
| 47 | 56 | |
| @@ -157,10 +166,14 @@ | ||
| 157 | 166 | * <p/> |
| 158 | 167 | * Please keep in mind that using this option has a non negligible |
| 159 | 168 | * performance impact and should be avoided when possible. |
| 169 | + * <p/> | |
| 170 | + * This will configure the statement as non-idempotent, see {@link com.datastax.driver.core.Statement#isIdempotent()} | |
| 171 | + * for more information. | |
| 160 | 172 | * |
| 161 | 173 | * @return this INSERT statement. |
| 162 | 174 | */ |
| 163 | 175 | public Insert ifNotExists() { |
| 176 | + this.setNonIdempotentOps(); | |
| 164 | 177 | this.ifNotExists = true; |
| 165 | 178 | return this; |
| 166 | 179 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +66 −1
| @@ -15,6 +15,8 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | +import com.datastax.driver.core.DataType; | |
| 19 | +import com.datastax.driver.core.Metadata; | |
| 18 | 20 | import com.datastax.driver.core.RegularStatement; |
| 19 | 21 | import com.datastax.driver.core.TableMetadata; |
| 20 | 22 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| @@ -227,9 +229,10 @@ | ||
| 227 | 229 | * |
| 228 | 230 | * @param columnName the column name to quote. |
| 229 | 231 | * @return the quoted column name. |
| 232 | + * @see Metadata#quote(String) | |
| 230 | 233 | */ |
| 231 | 234 | public static String quote(String columnName) { |
| 232 | - return '"' + columnName + '"'; | |
| 235 | + return Metadata.quote(columnName); | |
| 233 | 236 | } |
| 234 | 237 | |
| 235 | 238 | /** |
| @@ -274,6 +277,37 @@ | ||
| 274 | 277 | return new Clause.SimpleClause(name, "=", value); |
| 275 | 278 | } |
| 276 | 279 | |
| 280 | + /** | |
| 281 | + * Creates an "equal" where clause for a group of clustering columns. | |
| 282 | + * <p/> | |
| 283 | + * For instance, {@code eq(Arrays.asList("a", "b"), Arrays.asList(2, "test"))} | |
| 284 | + * will generate the CQL WHERE clause {@code (a, b) = (2, 'test') }. | |
| 285 | + * <p/> | |
| 286 | + * Please note that this variant is only supported starting with Cassandra 2.0.6. | |
| 287 | + * | |
| 288 | + * @param names the column names | |
| 289 | + * @param values the values | |
| 290 | + * @return the corresponding where clause. | |
| 291 | + * @throws IllegalArgumentException if {@code names.size() != values.size()}. | |
| 292 | + */ | |
| 293 | + public static Clause eq(List<String> names, List<?> values) { | |
| 294 | + if (names.size() != values.size()) | |
| 295 | + throw new IllegalArgumentException(String.format("The number of names (%d) and values (%d) don't match", names.size(), values.size())); | |
| 296 | + | |
| 297 | + return new Clause.CompoundClause(names, "=", values); | |
| 298 | + } | |
| 299 | + | |
| 300 | + /** | |
| 301 | + * Creates a "like" where clause stating that the provided column must be equal to the provided value. | |
| 302 | + * | |
| 303 | + * @param name the column name. | |
| 304 | + * @param value the value. | |
| 305 | + * @return the corresponding where clause. | |
| 306 | + */ | |
| 307 | + public static Clause like(String name, Object value) { | |
| 308 | + return new Clause.SimpleClause(name, " LIKE ", value); | |
| 309 | + } | |
| 310 | + | |
| 277 | 311 | /** |
| 278 | 312 | * Create an "in" where clause stating the provided column must be equal |
| 279 | 313 | * to one of the provided values. |
| @@ -298,6 +332,26 @@ | ||
| 298 | 332 | return new Clause.InClause(name, values); |
| 299 | 333 | } |
| 300 | 334 | |
| 335 | + /** | |
| 336 | + * Creates an "in" where clause for a group of clustering columns. | |
| 337 | + * <p/> | |
| 338 | + * For instance, {@code in(Arrays.asList("a", "b"), Arrays.asList(Arrays.asList(1, 2), Arrays.asList("foo", "bar")))} | |
| 339 | + * will generate the CQL WHERE clause {@code (a, b) IN ((1, 2), ('foo', 'bar')) }. | |
| 340 | + * <p/> | |
| 341 | + * Please note that this variant is only supported starting with Cassandra 2.0.9. | |
| 342 | + * | |
| 343 | + * @param names the column names | |
| 344 | + * @param values the values | |
| 345 | + * @return the corresponding where clause. | |
| 346 | + * @throws IllegalArgumentException if {@code names.size() != values.size()}. | |
| 347 | + */ | |
| 348 | + public static Clause in(List<String> names, List<List<?>> values) { | |
| 349 | + if (names.size() != values.size()) | |
| 350 | + throw new IllegalArgumentException(String.format("The number of names (%d) and values (%d) don't match", names.size(), values.size())); | |
| 351 | + | |
| 352 | + return new Clause.CompoundInClause(names, values); | |
| 353 | + } | |
| 354 | + | |
| 301 | 355 | /** |
| 302 | 356 | * Creates a "contains" where clause stating the provided column must contain |
| 303 | 357 | * the value provided. |
| @@ -955,6 +1009,17 @@ | ||
| 955 | 1009 | return new Utils.FCall(name, parameters); |
| 956 | 1010 | } |
| 957 | 1011 | |
| 1012 | + /** | |
| 1013 | + * Creates a Cast of a column using the given dataType. | |
| 1014 | + * | |
| 1015 | + * @param column the column to cast. | |
| 1016 | + * @param dataType the data type to cast to. | |
| 1017 | + * @return the casted column. | |
| 1018 | + */ | |
| 1019 | + public static Object cast(Object column, DataType dataType) { | |
| 1020 | + return new Utils.Cast(column, dataType); | |
| 1021 | + } | |
| 1022 | + | |
| 958 | 1023 | /** |
| 959 | 1024 | * Creates a {@code now()} function call. |
| 960 | 1025 | * |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +56 −80
| @@ -16,6 +16,8 @@ | ||
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CodecRegistry; |
| 19 | +import com.datastax.driver.core.ColumnMetadata; | |
| 20 | +import com.datastax.driver.core.DataType; | |
| 19 | 21 | import com.datastax.driver.core.TableMetadata; |
| 20 | 22 | |
| 21 | 23 | import java.util.ArrayList; |
| @@ -39,16 +41,26 @@ | ||
| 39 | 41 | private boolean allowFiltering; |
| 40 | 42 | |
| 41 | 43 | Select(String keyspace, String table, List<Object> columnNames, boolean isDistinct) { |
| 42 | - super(keyspace); | |
| 43 | - this.table = table; | |
| 44 | - this.isDistinct = isDistinct; | |
| 45 | - this.columnNames = columnNames; | |
| 46 | - this.where = new Where(this); | |
| 44 | + this(keyspace, table, null, null, columnNames, isDistinct); | |
| 47 | 45 | } |
| 48 | 46 | |
| 49 | 47 | Select(TableMetadata table, List<Object> columnNames, boolean isDistinct) { |
| 50 | - super(table); | |
| 51 | - this.table = escapeId(table.getName()); | |
| 48 | + this(escapeId(table.getKeyspace().getName()), | |
| 49 | + escapeId(table.getName()), | |
| 50 | + Arrays.asList(new Object[table.getPartitionKey().size()]), | |
| 51 | + table.getPartitionKey(), | |
| 52 | + columnNames, | |
| 53 | + isDistinct); | |
| 54 | + } | |
| 55 | + | |
| 56 | + Select(String keyspace, | |
| 57 | + String table, | |
| 58 | + List<Object> routingKeyValues, | |
| 59 | + List<ColumnMetadata> partitionKey, | |
| 60 | + List<Object> columnNames, | |
| 61 | + boolean isDistinct) { | |
| 62 | + super(keyspace, partitionKey, routingKeyValues); | |
| 63 | + this.table = table; | |
| 52 | 64 | this.isDistinct = isDistinct; |
| 53 | 65 | this.columnNames = columnNames; |
| 54 | 66 | this.where = new Where(this); |
| @@ -377,6 +389,34 @@ | ||
| 377 | 389 | * @return this in-build SELECT statement |
| 378 | 390 | */ |
| 379 | 391 | public abstract SelectionOrAlias fcall(String name, Object... parameters); |
| 392 | + | |
| 393 | + /** | |
| 394 | + * Creates a cast of an expression to a given CQL type. | |
| 395 | + * | |
| 396 | + * @param column the expression to cast. It can be a complex expression like a | |
| 397 | + * {@link QueryBuilder#fcall(String, Object...) function call}. | |
| 398 | + * @param targetType the target CQL type to cast to. Use static methods such as {@link DataType#text()}. | |
| 399 | + * @return this in-build SELECT statement. | |
| 400 | + */ | |
| 401 | + public SelectionOrAlias cast(Object column, DataType targetType) { | |
| 402 | + // This method should be abstract like others here. But adding an abstract method is not binary-compatible, | |
| 403 | + // so we add this dummy implementation to make Clirr happy. | |
| 404 | + throw new UnsupportedOperationException("Not implemented. This should only happen if you've written your own implementation of Selection"); | |
| 405 | + } | |
| 406 | + | |
| 407 | + /** | |
| 408 | + * Selects the provided raw expression. | |
| 409 | + * <p/> | |
| 410 | + * The provided string will be appended to the query as-is, without any form of escaping or quoting. | |
| 411 | + * | |
| 412 | + * @param rawString the raw expression to add. | |
| 413 | + * @return this in-build SELECT statement | |
| 414 | + */ | |
| 415 | + public SelectionOrAlias raw(String rawString) { | |
| 416 | + // This method should be abstract like others here. But adding an abstract method is not binary-compatible, | |
| 417 | + // so we add this dummy implementation to make Clirr happy. | |
| 418 | + throw new UnsupportedOperationException("Not implemented. This should only happen if you've written your own implementation of Selection"); | |
| 419 | + } | |
| 380 | 420 | } |
| 381 | 421 | |
| 382 | 422 | /** |
| @@ -419,12 +459,6 @@ | ||
| 419 | 459 | return this; |
| 420 | 460 | } |
| 421 | 461 | |
| 422 | - /** | |
| 423 | - * Selects all columns (i.e. "SELECT * ...") | |
| 424 | - * | |
| 425 | - * @return an in-build SELECT statement. | |
| 426 | - * @throws IllegalStateException if some columns had already been selected for this builder. | |
| 427 | - */ | |
| 428 | 462 | @Override |
| 429 | 463 | public Builder all() { |
| 430 | 464 | if (columnNames != null) |
| @@ -435,12 +469,6 @@ | ||
| 435 | 469 | return (Builder) this; |
| 436 | 470 | } |
| 437 | 471 | |
| 438 | - /** | |
| 439 | - * Selects the count of all returned rows (i.e. "SELECT count(*) ..."). | |
| 440 | - * | |
| 441 | - * @return an in-build SELECT statement. | |
| 442 | - * @throws IllegalStateException if some columns had already been selected for this builder. | |
| 443 | - */ | |
| 444 | 472 | @Override |
| 445 | 473 | public Builder countAll() { |
| 446 | 474 | if (columnNames != null) |
| @@ -452,81 +480,35 @@ | ||
| 452 | 480 | return (Builder) this; |
| 453 | 481 | } |
| 454 | 482 | |
| 455 | - /** | |
| 456 | - * Selects the provided column. | |
| 457 | - * | |
| 458 | - * @param name the new column name to add. | |
| 459 | - * @return this in-build SELECT statement | |
| 460 | - */ | |
| 461 | 483 | @Override |
| 462 | 484 | public SelectionOrAlias column(String name) { |
| 463 | 485 | return queueName(name); |
| 464 | 486 | } |
| 465 | 487 | |
| 466 | - /** | |
| 467 | - * Selects the provided raw expression. | |
| 468 | - * <p/> | |
| 469 | - * This method is used internally by the mapper module. It is not exposed on the parent class {@link Selection} to | |
| 470 | - * avoid breaking binary compatibility. This means that it is not accessible directly via the fluent API (you need | |
| 471 | - * a cast). This shouldn't be a problem for regular clients because they will use other methods of the DSL | |
| 472 | - * ({@code fcall}, etc.) rather than provide a raw string. | |
| 473 | - * | |
| 474 | - * @param rawString the raw expression to add. | |
| 475 | - * @return this in-build SELECT statement | |
| 476 | - */ | |
| 477 | - public SelectionOrAlias raw(String rawString) { | |
| 478 | - return queueName(QueryBuilder.raw(rawString)); | |
| 479 | - } | |
| 480 | - | |
| 481 | - /** | |
| 482 | - * Selects the write time of provided column. | |
| 483 | - * <p/> | |
| 484 | - * This is a shortcut for {@code fcall("writetime", QueryBuilder.column(name))}. | |
| 485 | - * | |
| 486 | - * @param name the name of the column to select the write time of. | |
| 487 | - * @return this in-build SELECT statement | |
| 488 | - */ | |
| 489 | 488 | @Override |
| 490 | 489 | public SelectionOrAlias writeTime(String name) { |
| 491 | 490 | return queueName(new Utils.FCall("writetime", new Utils.CName(name))); |
| 492 | 491 | } |
| 493 | 492 | |
| 494 | - /** | |
| 495 | - * Selects the ttl of provided column. | |
| 496 | - * <p/> | |
| 497 | - * This is a shortcut for {@code fcall("ttl", QueryBuilder.column(name))}. | |
| 498 | - * | |
| 499 | - * @param name the name of the column to select the ttl of. | |
| 500 | - * @return this in-build SELECT statement | |
| 501 | - */ | |
| 502 | 493 | @Override |
| 503 | 494 | public SelectionOrAlias ttl(String name) { |
| 504 | 495 | return queueName(new Utils.FCall("ttl", new Utils.CName(name))); |
| 505 | 496 | } |
| 506 | 497 | |
| 507 | - /** | |
| 508 | - * Creates a function call. | |
| 509 | - * <p/> | |
| 510 | - * Please note that the parameters are interpreted as values, and so | |
| 511 | - * {@code fcall("textToBlob", "foo")} will generate the string | |
| 512 | - * {@code "textToBlob('foo')"}. If you want to generate | |
| 513 | - * {@code "textToBlob(foo)"}, i.e. if the argument must be interpreted | |
| 514 | - * as a column name (in a select clause), you will need to use the | |
| 515 | - * {@link QueryBuilder#column} method, and so | |
| 516 | - * {@code fcall("textToBlob", QueryBuilder.column(foo)}. | |
| 517 | - */ | |
| 518 | 498 | @Override |
| 519 | 499 | public SelectionOrAlias fcall(String name, Object... parameters) { |
| 520 | 500 | return queueName(new Utils.FCall(name, parameters)); |
| 521 | 501 | } |
| 522 | 502 | |
| 523 | - /** | |
| 524 | - * Adds the table to select from. | |
| 525 | - * | |
| 526 | - * @param keyspace the name of the keyspace to select from. | |
| 527 | - * @param table the name of the table to select from. | |
| 528 | - * @return a newly built SELECT statement that selects from {@code keyspace.table}. | |
| 529 | - */ | |
| 503 | + public SelectionOrAlias cast(Object column, DataType targetType) { | |
| 504 | + return queueName(new Utils.Cast(column, targetType)); | |
| 505 | + } | |
| 506 | + | |
| 507 | + @Override | |
| 508 | + public SelectionOrAlias raw(String rawString) { | |
| 509 | + return queueName(QueryBuilder.raw(rawString)); | |
| 510 | + } | |
| 511 | + | |
| 530 | 512 | @Override |
| 531 | 513 | public Select from(String keyspace, String table) { |
| 532 | 514 | if (previousSelection != null) |
| @@ -534,12 +516,6 @@ | ||
| 534 | 516 | return super.from(keyspace, table); |
| 535 | 517 | } |
| 536 | 518 | |
| 537 | - /** | |
| 538 | - * Adds the table to select from. | |
| 539 | - * | |
| 540 | - * @param table the table to select from. | |
| 541 | - * @return a newly built SELECT statement that selects from {@code table}. | |
| 542 | - */ | |
| 543 | 519 | @Override |
| 544 | 520 | public Select from(TableMetadata table) { |
| 545 | 521 | if (previousSelection != null) |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java +15 −4
| @@ -16,8 +16,10 @@ | ||
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CodecRegistry; |
| 19 | +import com.datastax.driver.core.ColumnMetadata; | |
| 19 | 20 | import com.datastax.driver.core.TableMetadata; |
| 20 | 21 | |
| 22 | +import java.util.Arrays; | |
| 21 | 23 | import java.util.List; |
| 22 | 24 | |
| 23 | 25 | /** |
| @@ -28,13 +30,22 @@ | ||
| 28 | 30 | private final String table; |
| 29 | 31 | |
| 30 | 32 | Truncate(String keyspace, String table) { |
| 31 | - super(keyspace); | |
| 32 | - this.table = table; | |
| 33 | + this(keyspace, table, null, null); | |
| 33 | 34 | } |
| 34 | 35 | |
| 35 | 36 | Truncate(TableMetadata table) { |
| 36 | - super(table); | |
| 37 | - this.table = escapeId(table.getName()); | |
| 37 | + this(escapeId(table.getKeyspace().getName()), | |
| 38 | + escapeId(table.getName()), | |
| 39 | + Arrays.asList(new Object[table.getPartitionKey().size()]), | |
| 40 | + table.getPartitionKey()); | |
| 41 | + } | |
| 42 | + | |
| 43 | + Truncate(String keyspace, | |
| 44 | + String table, | |
| 45 | + List<Object> routingKeyValues, | |
| 46 | + List<ColumnMetadata> partitionKey) { | |
| 47 | + super(keyspace, partitionKey, routingKeyValues); | |
| 48 | + this.table = table; | |
| 38 | 49 | } |
| 39 | 50 | |
| 40 | 51 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +31 −11
| @@ -16,10 +16,12 @@ | ||
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CodecRegistry; |
| 19 | +import com.datastax.driver.core.ColumnMetadata; | |
| 19 | 20 | import com.datastax.driver.core.TableMetadata; |
| 20 | 21 | import com.datastax.driver.core.querybuilder.Assignment.CounterAssignment; |
| 21 | 22 | |
| 22 | 23 | import java.util.ArrayList; |
| 24 | +import java.util.Arrays; | |
| 23 | 25 | import java.util.List; |
| 24 | 26 | |
| 25 | 27 | /** |
| @@ -35,18 +37,22 @@ | ||
| 35 | 37 | private boolean ifExists; |
| 36 | 38 | |
| 37 | 39 | Update(String keyspace, String table) { |
| 38 | - super(keyspace); | |
| 39 | - this.table = table; | |
| 40 | - this.assignments = new Assignments(this); | |
| 41 | - this.where = new Where(this); | |
| 42 | - this.usings = new Options(this); | |
| 43 | - this.conditions = new Conditions(this); | |
| 44 | - this.ifExists = false; | |
| 40 | + this(keyspace, table, null, null); | |
| 45 | 41 | } |
| 46 | 42 | |
| 47 | 43 | Update(TableMetadata table) { |
| 48 | - super(table); | |
| 49 | - this.table = escapeId(table.getName()); | |
| 44 | + this(escapeId(table.getKeyspace().getName()), | |
| 45 | + escapeId(table.getName()), | |
| 46 | + Arrays.asList(new Object[table.getPartitionKey().size()]), | |
| 47 | + table.getPartitionKey()); | |
| 48 | + } | |
| 49 | + | |
| 50 | + Update(String keyspace, | |
| 51 | + String table, | |
| 52 | + List<Object> routingKeyValues, | |
| 53 | + List<ColumnMetadata> partitionKey) { | |
| 54 | + super(keyspace, partitionKey, routingKeyValues); | |
| 55 | + this.table = table; | |
| 50 | 56 | this.assignments = new Assignments(this); |
| 51 | 57 | this.where = new Where(this); |
| 52 | 58 | this.usings = new Options(this); |
| @@ -136,6 +142,9 @@ | ||
| 136 | 142 | * Adds a conditions clause (IF) to this statement. |
| 137 | 143 | * <p/> |
| 138 | 144 | * This is a shorter/more readable version for {@code onlyIf().and(condition)}. |
| 145 | + * <p/> | |
| 146 | + * This will configure the statement as non-idempotent, see {@link com.datastax.driver.core.Statement#isIdempotent()} | |
| 147 | + * for more information. | |
| 139 | 148 | * |
| 140 | 149 | * @param condition the condition to add. |
| 141 | 150 | * @return the conditions of this query to which more conditions can be added. |
| @@ -211,6 +220,9 @@ | ||
| 211 | 220 | |
| 212 | 221 | /** |
| 213 | 222 | * Adds a condition to the UPDATE statement those assignments are part of. |
| 223 | + * <p/> | |
| 224 | + * This will configure the statement as non-idempotent, see {@link com.datastax.driver.core.Statement#isIdempotent()} | |
| 225 | + * for more information. | |
| 214 | 226 | * |
| 215 | 227 | * @param condition the condition to add. |
| 216 | 228 | * @return the conditions for the UPDATE statement those assignments are part of. |
| @@ -241,6 +253,9 @@ | ||
| 241 | 253 | public Where and(Clause clause) { |
| 242 | 254 | clauses.add(clause); |
| 243 | 255 | statement.maybeAddRoutingKey(clause.name(), clause.firstValue()); |
| 256 | + if (!hasNonIdempotentOps() && !Utils.isIdempotent(clause)) { | |
| 257 | + statement.setNonIdempotentOps(); | |
| 258 | + } | |
| 244 | 259 | checkForBindMarkers(clause); |
| 245 | 260 | return this; |
| 246 | 261 | } |
| @@ -267,6 +282,9 @@ | ||
| 267 | 282 | |
| 268 | 283 | /** |
| 269 | 284 | * Adds a condition to the UPDATE statement this WHERE clause is part of. |
| 285 | + * <p/> | |
| 286 | + * This will configure the statement as non-idempotent, see {@link com.datastax.driver.core.Statement#isIdempotent()} | |
| 287 | + * for more information. | |
| 270 | 288 | * |
| 271 | 289 | * @param condition the condition to add. |
| 272 | 290 | * @return the conditions for the UPDATE statement this WHERE clause is part of. |
| @@ -279,21 +297,22 @@ | ||
| 279 | 297 | * Sets the 'IF EXISTS' option for the UPDATE statement this WHERE clause |
| 280 | 298 | * is part of. |
| 281 | 299 | * <p/> |
| 282 | - * <p> | |
| 283 | 300 | * An update with that option will report whether the statement actually |
| 284 | 301 | * resulted in data being updated. The existence check and update are |
| 285 | 302 | * done transactionally in the sense that if multiple clients attempt to |
| 286 | 303 | * update a given row with this option, then at most one may succeed. |
| 287 | 304 | * </p> |
| 288 | - * <p> | |
| 289 | 305 | * Please keep in mind that using this option has a non negligible |
| 290 | 306 | * performance impact and should be avoided when possible. |
| 291 | 307 | * </p> |
| 308 | + * This will configure the statement as non-idempotent, see {@link com.datastax.driver.core.Statement#isIdempotent()} | |
| 309 | + * for more information. | |
| 292 | 310 | * |
| 293 | 311 | * @return the UPDATE statement this WHERE clause is part of. |
| 294 | 312 | */ |
| 295 | 313 | public IfExists ifExists() { |
| 296 | 314 | statement.ifExists = true; |
| 315 | + statement.setNonIdempotentOps(); | |
| 297 | 316 | return new IfExists(statement); |
| 298 | 317 | } |
| 299 | 318 | } |
| @@ -379,6 +398,7 @@ | ||
| 379 | 398 | * @return this {@code Conditions} clause. |
| 380 | 399 | */ |
| 381 | 400 | public Conditions and(Clause condition) { |
| 401 | + statement.setNonIdempotentOps(); | |
| 382 | 402 | conditions.add(condition); |
| 383 | 403 | checkForBindMarkers(condition); |
| 384 | 404 | return this; |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +29 −4
| @@ -15,10 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CodecRegistry; | |
| 19 | -import com.datastax.driver.core.ProtocolVersion; | |
| 20 | -import com.datastax.driver.core.Token; | |
| 21 | -import com.datastax.driver.core.TypeCodec; | |
| 18 | +import com.datastax.driver.core.*; | |
| 22 | 19 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 23 | 20 | |
| 24 | 21 | import java.math.BigDecimal; |
| @@ -78,6 +75,11 @@ | ||
| 78 | 75 | appendValue(fcall.parameters[i], codecRegistry, sb, variables); |
| 79 | 76 | } |
| 80 | 77 | sb.append(')'); |
| 78 | + } else if (value instanceof Cast) { | |
| 79 | + Cast cast = (Cast) value; | |
| 80 | + sb.append("CAST("); | |
| 81 | + appendName(cast.column, codecRegistry, sb); | |
| 82 | + sb.append(" AS ").append(cast.targetType).append(")"); | |
| 81 | 83 | } else if (value instanceof CName) { |
| 82 | 84 | appendName(((CName) value).name, codecRegistry, sb); |
| 83 | 85 | } else if (value instanceof RawString) { |
| @@ -229,6 +231,9 @@ | ||
| 229 | 231 | if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue())) |
| 230 | 232 | return false; |
| 231 | 233 | } |
| 234 | + } else if (value instanceof Clause) { | |
| 235 | + Object clauseValue = ((Clause) value).firstValue(); | |
| 236 | + return isIdempotent(clauseValue); | |
| 232 | 237 | } |
| 233 | 238 | return true; |
| 234 | 239 | } |
| @@ -261,6 +266,11 @@ | ||
| 261 | 266 | Alias alias = (Alias) name; |
| 262 | 267 | appendName(alias.column, codecRegistry, sb); |
| 263 | 268 | sb.append(" AS ").append(alias.alias); |
| 269 | + } else if (name instanceof Cast) { | |
| 270 | + Cast cast = (Cast) name; | |
| 271 | + sb.append("CAST("); | |
| 272 | + appendName(cast.column, codecRegistry, sb); | |
| 273 | + sb.append(" AS ").append(cast.targetType).append(")"); | |
| 264 | 274 | } else if (name instanceof RawString) { |
| 265 | 275 | sb.append(((RawString) name).str); |
| 266 | 276 | } else { |
| @@ -423,4 +433,19 @@ | ||
| 423 | 433 | return String.format("%s AS %s", column, alias); |
| 424 | 434 | } |
| 425 | 435 | } |
| 436 | + | |
| 437 | + static class Cast { | |
| 438 | + private final Object column; | |
| 439 | + private final DataType targetType; | |
| 440 | + | |
| 441 | + Cast(Object column, DataType targetType) { | |
| 442 | + this.column = column; | |
| 443 | + this.targetType = targetType; | |
| 444 | + } | |
| 445 | + | |
| 446 | + @Override | |
| 447 | + public String toString() { | |
| 448 | + return String.format("CAST(%s AS %s)", column, targetType); | |
| 449 | + } | |
| 450 | + } | |
| 426 | 451 | } |
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +2 −9
| @@ -16,13 +16,12 @@ | ||
| 16 | 16 | package com.datastax.driver.core.schemabuilder; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CodecRegistry; |
| 19 | +import com.datastax.driver.core.Metadata; | |
| 19 | 20 | import com.datastax.driver.core.ProtocolVersion; |
| 20 | 21 | import com.datastax.driver.core.RegularStatement; |
| 21 | 22 | import com.google.common.base.Strings; |
| 22 | 23 | |
| 23 | 24 | import java.nio.ByteBuffer; |
| 24 | -import java.util.Arrays; | |
| 25 | -import java.util.List; | |
| 26 | 25 | import java.util.Map; |
| 27 | 26 | |
| 28 | 27 | /** |
| @@ -33,12 +32,6 @@ | ||
| 33 | 32 | static final String STATEMENT_START = "\n\t"; |
| 34 | 33 | static final String COLUMN_FORMATTING = "\n\t\t"; |
| 35 | 34 | |
| 36 | - static final List<String> RESERVED_KEYWORDS = Arrays.asList( | |
| 37 | - ("add,allow,alter,and,any,apply,asc,authorize,batch,begin,by,columnfamily,create,delete,desc,drop,each_quorum,from,grant,in,index,inet,infinity," + | |
| 38 | - "insert,into,keyspace,keyspaces,limit,local_one,local_quorum,modify,nan,norecursive,of,on,order,password,primary,quorum,rename,revoke,schema," + | |
| 39 | - "select,set,table,three,to,token,truncate,two,unlogged,update,use,using,where,with") | |
| 40 | - .split(",")); | |
| 41 | - | |
| 42 | 35 | private volatile String cache; |
| 43 | 36 | |
| 44 | 37 | abstract String buildInternal(); |
| @@ -104,7 +97,7 @@ | ||
| 104 | 97 | } |
| 105 | 98 | |
| 106 | 99 | static void validateNotKeyWord(String label, String message) { |
| 107 | - if (RESERVED_KEYWORDS.contains(label)) { | |
| 100 | + if (Metadata.isReservedCqlKeyword(label)) { | |
| 108 | 101 | throw new IllegalArgumentException(message); |
| 109 | 102 | } |
| 110 | 103 | } |
modified driver-core/src/main/java/com/datastax/driver/core/utils/UUIDs.java +16 −20
| @@ -141,6 +141,16 @@ | ||
| 141 | 141 | * UUID generated by this method are suitable for use with the |
| 142 | 142 | * {@code timeuuid} Cassandra type. In particular the generated UUID |
| 143 | 143 | * includes the timestamp of its generation. |
| 144 | + * <p/> | |
| 145 | + * Note that there is no way to provide your own timestamp. This is deliberate, as we feel that this does not | |
| 146 | + * conform to the UUID specification, and therefore don't want to encourage it through the API. | |
| 147 | + * If you want to do it anyway, use the following workaround: | |
| 148 | + * <pre> | |
| 149 | + * Random random = new Random(); | |
| 150 | + * UUID uuid = new UUID(UUIDs.startOf(userProvidedTimestamp).getMostSignificantBits(), random.nextLong()); | |
| 151 | + * </pre> | |
| 152 | + * If you simply need to perform a range query on a {@code timeuuid} column, use the "fake" UUID generated by | |
| 153 | + * {@link #startOf(long)} and {@link #endOf(long)}. | |
| 144 | 154 | * |
| 145 | 155 | * @return a new time-based UUID. |
| 146 | 156 | */ |
| @@ -157,14 +167,16 @@ | ||
| 157 | 167 | * <p/> |
| 158 | 168 | * The UUID created by this method <b>are not unique</b> and as such are |
| 159 | 169 | * <b>not</b> suitable for anything else than querying a specific time |
| 160 | - * range. In particular, you should not insert such UUID. | |
| 170 | + * range. In particular, you should not insert such UUID. "True" UUID from | |
| 171 | + * user-provided timestamps are not supported (see {@link #timeBased()} | |
| 172 | + * for more explanations). | |
| 161 | 173 | * <p/> |
| 162 | 174 | * Also, the timestamp to provide as parameter must be a unix timestamp (as |
| 163 | 175 | * returned by {@link System#currentTimeMillis} or {@link java.util.Date#getTime}), |
| 164 | - * not a UUID 100-nanoseconds intervals since 15 October 1582. In other | |
| 176 | + * not a UUID 100-nanoseconds interval since 15 October 1582. In other | |
| 165 | 177 | * words, given a UUID {@code uuid}, you should never do |
| 166 | 178 | * {@code startOf(uuid.timestamp())} but rather |
| 167 | - * {@code startOf(unixTimestamp(uuid.timestamp()))}. | |
| 179 | + * {@code startOf(unixTimestamp(uuid))}. | |
| 168 | 180 | * <p/> |
| 169 | 181 | * Lastly, please note that Cassandra's timeuuid sorting is not compatible |
| 170 | 182 | * with {@link UUID#compareTo} and hence the UUID created by this method |
| @@ -182,23 +194,7 @@ | ||
| 182 | 194 | * Creates a "fake" time-based UUID that sorts as the biggest possible |
| 183 | 195 | * version 1 UUID generated at the provided timestamp. |
| 184 | 196 | * <p/> |
| 185 | - * Such created UUID are useful in queries to select a time range of a | |
| 186 | - * {@code timeuuid} column. | |
| 187 | - * <p/> | |
| 188 | - * The UUID created by this method <b>are not unique</b> and as such are | |
| 189 | - * <b>not</b> suitable for anything else than querying a specific time | |
| 190 | - * range. In particular, you should not insert such UUID. | |
| 191 | - * <p/> | |
| 192 | - * Also, the timestamp to provide as parameter must be a unix timestamp (as | |
| 193 | - * returned by {@link System#currentTimeMillis} or {@link java.util.Date#getTime}), | |
| 194 | - * not a UUID 100-nanoseconds intervals since 15 October 1582. In other | |
| 195 | - * words, given a UUID {@code uuid}, you should never do | |
| 196 | - * {@code startOf(uuid.timestamp())} but rather | |
| 197 | - * {@code startOf(unixTimestamp(uuid.timestamp()))}. | |
| 198 | - * <p/> | |
| 199 | - * Lastly, please note that Cassandra's timeuuid sorting is not compatible | |
| 200 | - * with {@link UUID#compareTo} and hence the UUID created by this method | |
| 201 | - * are not necessarily upper bound for that latter method. | |
| 197 | + * See {@link #startOf(long)} for explanations about the intended usage of such UUID. | |
| 202 | 198 | * |
| 203 | 199 | * @param timestamp the unix timestamp for which the created UUID must be an |
| 204 | 200 | * upper bound. |
modified driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java +89 −0
| @@ -16,11 +16,13 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.utils.CassandraVersion; |
| 19 | +import org.testng.SkipException; | |
| 19 | 20 | import org.testng.annotations.Test; |
| 20 | 21 | |
| 21 | 22 | import static com.datastax.driver.core.Assertions.assertThat; |
| 22 | 23 | import static com.datastax.driver.core.DataType.cint; |
| 23 | 24 | import static com.datastax.driver.core.DataType.text; |
| 25 | +import static com.datastax.driver.core.TestUtils.serializeForDynamicCompositeType; | |
| 24 | 26 | |
| 25 | 27 | @CassandraVersion(major = 2.2) |
| 26 | 28 | @CCMConfig(config = "enable_user_defined_functions:true") |
| @@ -171,6 +173,93 @@ | ||
| 171 | 173 | assertThat(aggregate.toString()).isEqualTo(cqlAggregate); |
| 172 | 174 | } |
| 173 | 175 | |
| 176 | + /** | |
| 177 | + * Validates aggregates with DynamicCompositeType state types and an initcond value that is a literal, i.e.: | |
| 178 | + * 's@foo:i@32' can be appropriately parsed and generate a CQL string with the init cond as a hex string, i.e.: | |
| 179 | + * 0x80730003666f6f00806900040000002000. | |
| 180 | + * | |
| 181 | + * @jira_ticket JAVA-1046 | |
| 182 | + * @test_category metadata | |
| 183 | + * @since 3.0.1 | |
| 184 | + */ | |
| 185 | + @Test(groups = "short") | |
| 186 | + @CassandraVersion(major = 2.2) | |
| 187 | + public void should_parse_and_format_aggregate_with_composite_type_literal_initcond() { | |
| 188 | + VersionNumber ver = VersionNumber.parse(CCMBridge.getCassandraVersion()); | |
| 189 | + if (ver.getMajor() == 3) { | |
| 190 | + if ((ver.getMinor() >= 1 && ver.getMinor() < 4) || (ver.getMinor() == 0 && ver.getPatch() < 4)) { | |
| 191 | + throw new SkipException("Requires C* 2.2.X, 3.0.4+ or 3.4.X+"); | |
| 192 | + } | |
| 193 | + } | |
| 194 | + parse_and_format_aggregate_with_composite_type("ag0", "'s@foo:i@32'"); | |
| 195 | + } | |
| 196 | + | |
| 197 | + /** | |
| 198 | + * Validates aggregates with DynamicCompositeType state types and an initcond value that is a hex string | |
| 199 | + * representing the bytes for the type, i.e.: 0x80730003666f6f00806900040000002000' can be appropriately parsed | |
| 200 | + * and generates an equivalent CQL string. | |
| 201 | + * | |
| 202 | + * @jira_ticket JAVA-1046 | |
| 203 | + * @test_category metadata | |
| 204 | + * @since 3.0.1 | |
| 205 | + */ | |
| 206 | + @Test(groups = "short") | |
| 207 | + @CassandraVersion(major = 3.0, minor = 4) | |
| 208 | + public void should_parse_and_format_aggregate_with_composite_type_hex_initcond() { | |
| 209 | + VersionNumber ver = VersionNumber.parse(CCMBridge.getCassandraVersion()); | |
| 210 | + if ((ver.getMinor() >= 1 && ver.getMinor() < 4)) { | |
| 211 | + throw new SkipException("Requires 3.0.4+ or 3.4.X+"); | |
| 212 | + } | |
| 213 | + parse_and_format_aggregate_with_composite_type("ag1", "0x80730003666f6f00806900040000002000"); | |
| 214 | + } | |
| 215 | + | |
| 216 | + public void parse_and_format_aggregate_with_composite_type(String aggregateName, String initCond) { | |
| 217 | + // given | |
| 218 | + DataType custom = DataType.custom( | |
| 219 | + "org.apache.cassandra.db.marshal.DynamicCompositeType(" + | |
| 220 | + "s=>org.apache.cassandra.db.marshal.UTF8Type," + | |
| 221 | + "i=>org.apache.cassandra.db.marshal.Int32Type)"); | |
| 222 | + String cqlFunction = String.format( | |
| 223 | + "CREATE FUNCTION %s.%s_id(i %s) " + | |
| 224 | + "RETURNS NULL ON NULL INPUT " + | |
| 225 | + "RETURNS %s " + | |
| 226 | + "LANGUAGE java " + | |
| 227 | + "AS 'return i;';", keyspace, aggregateName, custom, custom); | |
| 228 | + session().execute(cqlFunction); | |
| 229 | + | |
| 230 | + String cqlAggregate = String.format( | |
| 231 | + "CREATE AGGREGATE %s.%s() " + | |
| 232 | + "SFUNC %s_id " + | |
| 233 | + "STYPE %s " + | |
| 234 | + "INITCOND %s;", keyspace, aggregateName, aggregateName, custom, initCond); | |
| 235 | + | |
| 236 | + String expectedAggregate = String.format( | |
| 237 | + "CREATE AGGREGATE %s.%s() " + | |
| 238 | + "SFUNC %s_id " + | |
| 239 | + "STYPE %s " + | |
| 240 | + "INITCOND 0x80730003666f6f00806900040000002000;", keyspace, aggregateName, aggregateName, custom); | |
| 241 | + | |
| 242 | + int agCount = 0; | |
| 243 | + | |
| 244 | + // when | |
| 245 | + session().execute(cqlAggregate); | |
| 246 | + // then | |
| 247 | + KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace); | |
| 248 | + FunctionMetadata stateFunc = keyspace.getFunction(aggregateName + "_id", custom); | |
| 249 | + AggregateMetadata aggregate = keyspace.getAggregate(aggregateName); | |
| 250 | + assertThat(aggregate).isNotNull(); | |
| 251 | + assertThat(aggregate.getSignature()).isEqualTo(aggregateName + "()"); | |
| 252 | + assertThat(aggregate.getSimpleName()).isEqualTo(aggregateName); | |
| 253 | + assertThat(aggregate.getArgumentTypes()).isEmpty(); | |
| 254 | + assertThat(aggregate.getFinalFunc()).isNull(); | |
| 255 | + assertThat(aggregate.getInitCond()).isEqualTo(serializeForDynamicCompositeType("foo", 32)); | |
| 256 | + assertThat(aggregate.getReturnType()).isEqualTo(custom); | |
| 257 | + assertThat(aggregate.getStateFunc()).isEqualTo(stateFunc); | |
| 258 | + assertThat(aggregate.getStateType()).isEqualTo(custom); | |
| 259 | + | |
| 260 | + assertThat(aggregate.toString()).isEqualTo(expectedAggregate); | |
| 261 | + } | |
| 262 | + | |
| 174 | 263 | @Override |
| 175 | 264 | public void onTestContextInitialized() { |
| 176 | 265 | execute( |
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +38 −0
| @@ -17,8 +17,11 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 19 | 19 | import com.google.common.base.Function; |
| 20 | +import com.google.common.base.Throwables; | |
| 20 | 21 | import com.google.common.collect.Lists; |
| 21 | 22 | import com.google.common.util.concurrent.*; |
| 23 | +import org.slf4j.Logger; | |
| 24 | +import org.slf4j.LoggerFactory; | |
| 22 | 25 | import org.testng.annotations.DataProvider; |
| 23 | 26 | import org.testng.annotations.Test; |
| 24 | 27 | |
| @@ -26,11 +29,14 @@ | ||
| 26 | 29 | import java.util.concurrent.*; |
| 27 | 30 | |
| 28 | 31 | import static org.assertj.core.api.Assertions.assertThat; |
| 32 | +import static org.assertj.core.api.Assertions.fail; | |
| 29 | 33 | import static org.testng.Assert.assertEquals; |
| 30 | 34 | import static org.testng.Assert.assertTrue; |
| 31 | 35 | |
| 32 | 36 | public class AsyncQueryTest extends CCMTestsSupport { |
| 33 | 37 | |
| 38 | + Logger logger = LoggerFactory.getLogger(AsyncQueryTest.class); | |
| 39 | + | |
| 34 | 40 | @DataProvider(name = "keyspace") |
| 35 | 41 | public static Object[][] keyspace() { |
| 36 | 42 | return new Object[][]{{"asyncquerytest"}, {"\"AsyncQueryTest\""}}; |
| @@ -119,6 +125,38 @@ | ||
| 119 | 125 | } |
| 120 | 126 | } |
| 121 | 127 | |
| 128 | + @Test(groups = "short") | |
| 129 | + public void should_fail_when_synchronous_call_on_io_thread() throws Exception { | |
| 130 | + final Thread sameThread = Thread.currentThread(); | |
| 131 | + for (int i = 0; i < 1000; i++) { | |
| 132 | + ResultSetFuture f = session().executeAsync("select release_version from system.local"); | |
| 133 | + ListenableFuture<Thread> f2 = Futures.transform(f, new Function<ResultSet, Thread>() { | |
| 134 | + @Override | |
| 135 | + public Thread apply(ResultSet input) { | |
| 136 | + session().execute("select release_version from system.local"); | |
| 137 | + return Thread.currentThread(); | |
| 138 | + } | |
| 139 | + }); | |
| 140 | + try { | |
| 141 | + Thread executedThread = f2.get(); | |
| 142 | + if(executedThread != sameThread) { | |
| 143 | + fail("Expected a failed future, callback was executed on " + executedThread); | |
| 144 | + } else { | |
| 145 | + // Callback was invoked on the same thread, which indicates that the future completed | |
| 146 | + // before the transform callback was registered. Try again to produce case where callback | |
| 147 | + // is called on io thread. | |
| 148 | + logger.warn("Future completed before transform callback registered, will try again."); | |
| 149 | + } | |
| 150 | + } catch (Exception e) { | |
| 151 | + assertThat(Throwables.getRootCause(e)) | |
| 152 | + .isInstanceOf(IllegalStateException.class) | |
| 153 | + .hasMessageContaining("Detected a synchronous Session call"); | |
| 154 | + return; | |
| 155 | + } | |
| 156 | + } | |
| 157 | + fail("callback was not executed on io thread in 1000 attempts, something may be wrong."); | |
| 158 | + } | |
| 159 | + | |
| 122 | 160 | private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) { |
| 123 | 161 | ListenableFuture<Session> sessionFuture = cluster().connectAsync(keyspace); |
| 124 | 162 | ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() { |
modified driver-core/src/test/java/com/datastax/driver/core/CCMAccess.java +16 −2
| @@ -203,11 +203,25 @@ | ||
| 203 | 203 | void updateNodeConfig(int n, Map<String, Object> configs); |
| 204 | 204 | |
| 205 | 205 | /** |
| 206 | - * Sets the workload for the {@code nth} host in the CCM cluster. | |
| 206 | + * Updates the {@code nth} host's dse config file in the CCM cluster. | |
| 207 | 207 | * |
| 208 | 208 | * @param n the node number (starting from 1). |
| 209 | 209 | */ |
| 210 | - void setWorkload(int n, Workload workload); | |
| 210 | + void updateDSENodeConfig(int n, String key, Object value); | |
| 211 | + | |
| 212 | + /** | |
| 213 | + * Updates the {@code nth} host's dse config file in the CCM cluster. | |
| 214 | + * | |
| 215 | + * @param n the node number (starting from 1). | |
| 216 | + */ | |
| 217 | + void updateDSENodeConfig(int n, Map<String, Object> configs); | |
| 218 | + | |
| 219 | + /** | |
| 220 | + * Sets the workload(s) for the {@code nth} host in the CCM cluster. | |
| 221 | + * | |
| 222 | + * @param n the node number (starting from 1). | |
| 223 | + */ | |
| 224 | + void setWorkload(int n, Workload... workload); | |
| 211 | 225 | |
| 212 | 226 | |
| 213 | 227 | // Methods blocking until nodes are up or down |
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +83 −41
| @@ -31,6 +31,8 @@ | ||
| 31 | 31 | import java.net.InetSocketAddress; |
| 32 | 32 | import java.util.*; |
| 33 | 33 | import java.util.concurrent.TimeUnit; |
| 34 | +import java.util.regex.Matcher; | |
| 35 | +import java.util.regex.Pattern; | |
| 34 | 36 | |
| 35 | 37 | import static com.datastax.driver.core.TestUtils.executeNoFail; |
| 36 | 38 | import static com.datastax.driver.core.TestUtils.findAvailablePort; |
| @@ -539,8 +541,27 @@ | ||
| 539 | 541 | } |
| 540 | 542 | |
| 541 | 543 | @Override |
| 542 | - public void setWorkload(int node, Workload workload) { | |
| 543 | - execute(CCM_COMMAND + " node%d setworkload %s", node, workload); | |
| 544 | + public void updateDSENodeConfig(int n, String key, Object value) { | |
| 545 | + updateDSENodeConfig(n, ImmutableMap.<String, Object>builder().put(key, value).build()); | |
| 546 | + } | |
| 547 | + | |
| 548 | + @Override | |
| 549 | + public void updateDSENodeConfig(int n, Map<String, Object> configs) { | |
| 550 | + StringBuilder confStr = new StringBuilder(); | |
| 551 | + for (Map.Entry<String, Object> entry : configs.entrySet()) { | |
| 552 | + confStr | |
| 553 | + .append(entry.getKey()) | |
| 554 | + .append(":") | |
| 555 | + .append(entry.getValue()) | |
| 556 | + .append(" "); | |
| 557 | + } | |
| 558 | + execute(CCM_COMMAND + " node%s updatedseconf %s", n, confStr); | |
| 559 | + } | |
| 560 | + | |
| 561 | + @Override | |
| 562 | + public void setWorkload(int node, Workload... workload) { | |
| 563 | + String workloadStr = Joiner.on(",").join(workload); | |
| 564 | + execute(CCM_COMMAND + " node%d setworkload %s", node, workloadStr); | |
| 544 | 565 | } |
| 545 | 566 | |
| 546 | 567 | private String execute(String command, Object... args) { |
| @@ -663,22 +684,25 @@ | ||
| 663 | 684 | * use {@link #builder()} to get an instance |
| 664 | 685 | */ |
| 665 | 686 | public static class Builder { |
| 666 | - private final String clusterName = TestUtils.generateIdentifier("cluster_"); | |
| 687 | + | |
| 688 | + public static final String RANDOM_PORT = "__RANDOM_PORT__"; | |
| 689 | + private static final Pattern RANDOM_PORT_PATTERN = Pattern.compile(RANDOM_PORT); | |
| 690 | + | |
| 667 | 691 | int[] nodes = {1}; |
| 668 | 692 | private boolean start = true; |
| 669 | 693 | private boolean isDSE = isDSE(); |
| 670 | 694 | private String version = getCassandraVersion(); |
| 671 | - private Set<String> createOptions = new HashSet<String>(getInstallArguments()); | |
| 695 | + private Set<String> createOptions = new LinkedHashSet<String>(getInstallArguments()); | |
| 672 | 696 | private Set<String> jvmArgs = new LinkedHashSet<String>(); |
| 673 | - private final Map<String, Object> cassandraConfiguration = Maps.newHashMap(); | |
| 674 | - private final Map<String, Object> dseConfiguration = Maps.newHashMap(); | |
| 675 | - // -1 means random | |
| 676 | - private int thriftPort = -1; | |
| 677 | - private int binaryPort = -1; | |
| 678 | - private int storagePort = -1; | |
| 679 | - private Map<Integer, Workload> workloads = new HashMap<Integer, Workload>(); | |
| 697 | + private final Map<String, Object> cassandraConfiguration = Maps.newLinkedHashMap(); | |
| 698 | + private final Map<String, Object> dseConfiguration = Maps.newLinkedHashMap(); | |
| 699 | + private Map<Integer, Workload[]> workloads = new HashMap<Integer, Workload[]>(); | |
| 680 | 700 | |
| 681 | 701 | private Builder() { |
| 702 | + cassandraConfiguration.put("start_rpc", false); | |
| 703 | + cassandraConfiguration.put("storage_port", RANDOM_PORT); | |
| 704 | + cassandraConfiguration.put("rpc_port", RANDOM_PORT); | |
| 705 | + cassandraConfiguration.put("native_transport_port", RANDOM_PORT); | |
| 682 | 706 | } |
| 683 | 707 | |
| 684 | 708 | /** |
| @@ -785,17 +809,17 @@ | ||
| 785 | 809 | } |
| 786 | 810 | |
| 787 | 811 | public Builder withStoragePort(int port) { |
| 788 | - storagePort = port; | |
| 812 | + cassandraConfiguration.put("storage_port", port); | |
| 789 | 813 | return this; |
| 790 | 814 | } |
| 791 | 815 | |
| 792 | 816 | public Builder withThriftPort(int port) { |
| 793 | - thriftPort = port; | |
| 817 | + cassandraConfiguration.put("rpc_port", port); | |
| 794 | 818 | return this; |
| 795 | 819 | } |
| 796 | 820 | |
| 797 | 821 | public Builder withBinaryPort(int port) { |
| 798 | - binaryPort = port; | |
| 822 | + cassandraConfiguration.put("native_transport_port", port); | |
| 799 | 823 | return this; |
| 800 | 824 | } |
| 801 | 825 | |
| @@ -803,20 +827,23 @@ | ||
| 803 | 827 | * Sets the DSE workload for a given node. |
| 804 | 828 | * |
| 805 | 829 | * @param node The node to set the workload for (starting with 1). |
| 806 | - * @param workload The workload (e.g. solr, spark, hadoop) | |
| 830 | + * @param workload The workload(s) (e.g. solr, spark, hadoop) | |
| 807 | 831 | * @return This builder |
| 808 | 832 | */ |
| 809 | - public Builder withWorkload(int node, Workload workload) { | |
| 833 | + public Builder withWorkload(int node, Workload... workload) { | |
| 810 | 834 | this.workloads.put(node, workload); |
| 811 | 835 | return this; |
| 812 | 836 | } |
| 813 | 837 | |
| 814 | 838 | public CCMBridge build() { |
| 815 | 839 | // be careful NOT to alter internal state (hashCode/equals) during build! |
| 816 | - int storagePort = this.storagePort == -1 ? findAvailablePort() : this.storagePort; | |
| 817 | - int thriftPort = this.thriftPort == -1 ? findAvailablePort() : this.thriftPort; | |
| 818 | - int binaryPort = this.binaryPort == -1 ? findAvailablePort() : this.binaryPort; | |
| 840 | + String clusterName = TestUtils.generateIdentifier("ccm_"); | |
| 841 | + Map<String, Object> cassandraConfiguration = randomizePorts(this.cassandraConfiguration); | |
| 842 | + Map<String, Object> dseConfiguration = randomizePorts(this.dseConfiguration); | |
| 819 | 843 | VersionNumber version = VersionNumber.parse(this.version); |
| 844 | + int storagePort = Integer.parseInt(cassandraConfiguration.get("storage_port").toString()); | |
| 845 | + int thriftPort = Integer.parseInt(cassandraConfiguration.get("rpc_port").toString()); | |
| 846 | + int binaryPort = Integer.parseInt(cassandraConfiguration.get("native_transport_port").toString()); | |
| 820 | 847 | final CCMBridge ccm = new CCMBridge(clusterName, isDSE, version, storagePort, thriftPort, binaryPort, joinJvmArgs()); |
| 821 | 848 | Runtime.getRuntime().addShutdownHook(new Thread() { |
| 822 | 849 | @Override |
| @@ -824,17 +851,12 @@ | ||
| 824 | 851 | ccm.close(); |
| 825 | 852 | } |
| 826 | 853 | }); |
| 827 | - ccm.execute(buildCreateCommand()); | |
| 854 | + ccm.execute(buildCreateCommand(clusterName)); | |
| 828 | 855 | updateNodeConf(ccm); |
| 829 | - HashMap<String, Object> config = new HashMap<String, Object>(cassandraConfiguration); | |
| 830 | - config.put("start_rpc", false); | |
| 831 | - config.put("storage_port", storagePort); | |
| 832 | - config.put("rpc_port", thriftPort); | |
| 833 | - config.put("native_transport_port", binaryPort); | |
| 834 | - ccm.updateConfig(config); | |
| 856 | + ccm.updateConfig(cassandraConfiguration); | |
| 835 | 857 | if (!dseConfiguration.isEmpty()) |
| 836 | 858 | ccm.updateDSEConfig(dseConfiguration); |
| 837 | - for (Map.Entry<Integer, Workload> entry : workloads.entrySet()) { | |
| 859 | + for (Map.Entry<Integer, Workload[]> entry : workloads.entrySet()) { | |
| 838 | 860 | ccm.setWorkload(entry.getKey(), entry.getValue()); |
| 839 | 861 | } |
| 840 | 862 | if (start) |
| @@ -855,12 +877,12 @@ | ||
| 855 | 877 | StringBuilder allJvmArgs = new StringBuilder(""); |
| 856 | 878 | for (String jvmArg : jvmArgs) { |
| 857 | 879 | allJvmArgs.append(" --jvm_arg="); |
| 858 | - allJvmArgs.append(jvmArg); | |
| 880 | + allJvmArgs.append(randomizePorts(jvmArg)); | |
| 859 | 881 | } |
| 860 | 882 | return allJvmArgs.toString(); |
| 861 | 883 | } |
| 862 | 884 | |
| 863 | - private String buildCreateCommand() { | |
| 885 | + private String buildCreateCommand(String clusterName) { | |
| 864 | 886 | StringBuilder result = new StringBuilder(CCM_COMMAND + " create"); |
| 865 | 887 | result.append(" ").append(clusterName); |
| 866 | 888 | result.append(" -i ").append(TestUtils.IP_PREFIX); |
| @@ -874,7 +896,7 @@ | ||
| 874 | 896 | result.append(node); |
| 875 | 897 | } |
| 876 | 898 | } |
| 877 | - result.append(" ").append(Joiner.on(" ").join(createOptions)); | |
| 899 | + result.append(" ").append(Joiner.on(" ").join(randomizePorts(createOptions))); | |
| 878 | 900 | return result.toString(); |
| 879 | 901 | } |
| 880 | 902 | |
| @@ -892,7 +914,7 @@ | ||
| 892 | 914 | for (int i = 0; i < nodesInDc; i++) { |
| 893 | 915 | int jmxPort = findAvailablePort(); |
| 894 | 916 | int debugPort = findAvailablePort(); |
| 895 | - logger.trace("Node {} in cluster {} using JMX port {} and debug port {}", n, clusterName, jmxPort, debugPort); | |
| 917 | + logger.trace("Node {} in cluster {} using JMX port {} and debug port {}", n, ccm.getClusterName(), jmxPort, debugPort); | |
| 896 | 918 | File nodeConf = new File(ccm.getNodeDir(n), "node.conf"); |
| 897 | 919 | File nodeConf2 = new File(ccm.getNodeDir(n), "node.conf.tmp"); |
| 898 | 920 | BufferedReader br = closer.register(new BufferedReader(new FileReader(nodeConf))); |
| @@ -927,6 +949,36 @@ | ||
| 927 | 949 | } |
| 928 | 950 | } |
| 929 | 951 | |
| 952 | + private Set<String> randomizePorts(Set<String> set) { | |
| 953 | + Set<String> randomized = new LinkedHashSet<String>(); | |
| 954 | + for (String value : set) { | |
| 955 | + randomized.add(randomizePorts(value)); | |
| 956 | + } | |
| 957 | + return randomized; | |
| 958 | + } | |
| 959 | + | |
| 960 | + private Map<String, Object> randomizePorts(Map<String, Object> map) { | |
| 961 | + Map<String, Object> randomized = new HashMap<String, Object>(); | |
| 962 | + for (Map.Entry<String, Object> entry : map.entrySet()) { | |
| 963 | + Object value = entry.getValue(); | |
| 964 | + if (value instanceof CharSequence) { | |
| 965 | + value = randomizePorts((CharSequence) value); | |
| 966 | + } | |
| 967 | + randomized.put(entry.getKey(), value); | |
| 968 | + } | |
| 969 | + return randomized; | |
| 970 | + } | |
| 971 | + | |
| 972 | + private String randomizePorts(CharSequence str) { | |
| 973 | + Matcher matcher = RANDOM_PORT_PATTERN.matcher(str); | |
| 974 | + StringBuffer sb = new StringBuffer(); | |
| 975 | + while (matcher.find()) { | |
| 976 | + matcher.appendReplacement(sb, Integer.toString(TestUtils.findAvailablePort())); | |
| 977 | + } | |
| 978 | + matcher.appendTail(sb); | |
| 979 | + return sb.toString(); | |
| 980 | + } | |
| 981 | + | |
| 930 | 982 | @Override |
| 931 | 983 | @SuppressWarnings("SimplifiableIfStatement") |
| 932 | 984 | public boolean equals(Object o) { |
| @@ -936,9 +988,6 @@ | ||
| 936 | 988 | if (o == null || getClass() != o.getClass()) return false; |
| 937 | 989 | Builder builder = (Builder) o; |
| 938 | 990 | if (isDSE != builder.isDSE) return false; |
| 939 | - if (thriftPort != builder.thriftPort) return false; | |
| 940 | - if (binaryPort != builder.binaryPort) return false; | |
| 941 | - if (storagePort != builder.storagePort) return false; | |
| 942 | 991 | if (!Arrays.equals(nodes, builder.nodes)) return false; |
| 943 | 992 | if (!createOptions.equals(builder.createOptions)) return false; |
| 944 | 993 | if (!jvmArgs.equals(builder.jvmArgs)) return false; |
| @@ -959,17 +1008,10 @@ | ||
| 959 | 1008 | result = 31 * result + cassandraConfiguration.hashCode(); |
| 960 | 1009 | result = 31 * result + dseConfiguration.hashCode(); |
| 961 | 1010 | result = 31 * result + workloads.hashCode(); |
| 962 | - result = 31 * result + thriftPort; | |
| 963 | - result = 31 * result + binaryPort; | |
| 964 | - result = 31 * result + storagePort; | |
| 965 | 1011 | result = 31 * result + version.hashCode(); |
| 966 | 1012 | return result; |
| 967 | 1013 | } |
| 968 | 1014 | |
| 969 | - @Override | |
| 970 | - public String toString() { | |
| 971 | - return String.format("%s (%s nodes)", clusterName, weight()); | |
| 972 | - } | |
| 973 | 1015 | } |
| 974 | 1016 | |
| 975 | 1017 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CCMCache.java +37 −8
| @@ -22,6 +22,7 @@ | ||
| 22 | 22 | |
| 23 | 23 | import java.io.File; |
| 24 | 24 | import java.net.InetSocketAddress; |
| 25 | +import java.util.Iterator; | |
| 25 | 26 | import java.util.Map; |
| 26 | 27 | import java.util.concurrent.ExecutionException; |
| 27 | 28 | import java.util.concurrent.atomic.AtomicInteger; |
| @@ -190,7 +191,17 @@ | ||
| 190 | 191 | } |
| 191 | 192 | |
| 192 | 193 | @Override |
| 193 | - public void setWorkload(int n, Workload workload) { | |
| 194 | + public void updateDSENodeConfig(int n, String key, Object value) { | |
| 195 | + ccm.updateDSENodeConfig(n, key, value); | |
| 196 | + } | |
| 197 | + | |
| 198 | + @Override | |
| 199 | + public void updateDSENodeConfig(int n, Map<String, Object> configs) { | |
| 200 | + ccm.updateDSENodeConfig(n, configs); | |
| 201 | + } | |
| 202 | + | |
| 203 | + @Override | |
| 204 | + public void setWorkload(int n, Workload... workload) { | |
| 194 | 205 | ccm.setWorkload(n, workload); |
| 195 | 206 | } |
| 196 | 207 | |
| @@ -247,20 +258,23 @@ | ||
| 247 | 258 | */ |
| 248 | 259 | private static final LoadingCache<CCMBridge.Builder, CachedCCMAccess> CACHE; |
| 249 | 260 | |
| 261 | + // The amount of memory one CCM node takes in MB. | |
| 262 | + private static final int ONE_CCM_NODE_MB = 800; | |
| 263 | + | |
| 250 | 264 | static { |
| 251 | 265 | long maximumWeight; |
| 252 | 266 | String numberOfNodes = System.getProperty("ccm.maxNumberOfNodes"); |
| 253 | 267 | if (numberOfNodes == null) { |
| 254 | 268 | long freeMemoryMB = TestUtils.getFreeMemoryMB(); |
| 255 | - if (freeMemoryMB < 1000) | |
| 256 | - LOGGER.warn("Available memory below 1GB: {}MB, CCM clusters might fail to start", freeMemoryMB); | |
| 269 | + if (freeMemoryMB < ONE_CCM_NODE_MB) | |
| 270 | + LOGGER.warn("Not enough available memory: {} MB, CCM clusters might fail to start", freeMemoryMB); | |
| 257 | 271 | // CCM nodes are started with -Xms500M -Xmx500M |
| 258 | 272 | // and allocate up to 100MB non-heap memory in the general case, |
| 259 | 273 | // to be conservative we treat 1 "slot" as 800Mb. |
| 260 | - // We leave 2 slots out to avoid starving system memory, | |
| 274 | + // We leave 3 slots out to avoid starving system memory, | |
| 261 | 275 | // and we pick a value with a minimum of 1 slot and a maximum of 8 slots. |
| 262 | - // For example, an 8GB VM with ~6.5GB currently available heap will yield 6 slots ((6500/800) - 2 = 6). | |
| 263 | - long slotsAvailable = (freeMemoryMB / 800) - 2; | |
| 276 | + // For example, an 8GB VM with ~6.5GB currently available heap will yield 5 slots ((6500/800) - 3 = 5). | |
| 277 | + long slotsAvailable = (freeMemoryMB / ONE_CCM_NODE_MB) - 3; | |
| 264 | 278 | maximumWeight = Math.min(8, Math.max(1, slotsAvailable)); |
| 265 | 279 | } else { |
| 266 | 280 | maximumWeight = Integer.parseInt(numberOfNodes); |
| @@ -272,6 +286,7 @@ | ||
| 272 | 286 | .maximumWeight(maximumWeight) |
| 273 | 287 | .weigher(new CCMAccessWeigher()) |
| 274 | 288 | .removalListener(new CCMAccessRemovalListener()) |
| 289 | + .recordStats() | |
| 275 | 290 | .build(new CCMAccessLoader()); |
| 276 | 291 | } |
| 277 | 292 | |
| @@ -304,8 +319,22 @@ | ||
| 304 | 319 | } |
| 305 | 320 | |
| 306 | 321 | private static void logCache() { |
| 307 | - if (LOGGER.isDebugEnabled()) | |
| 308 | - LOGGER.debug("Free memory: {}, Cache {}", TestUtils.getFreeMemoryMB(), CACHE.asMap().keySet()); | |
| 322 | + if (LOGGER.isDebugEnabled()) { | |
| 323 | + LOGGER.debug("Free memory: {} MB", TestUtils.getFreeMemoryMB()); | |
| 324 | + StringBuilder sb = new StringBuilder(); | |
| 325 | + Iterator<Map.Entry<CCMBridge.Builder, CachedCCMAccess>> iterator = CACHE.asMap().entrySet().iterator(); | |
| 326 | + while (iterator.hasNext()) { | |
| 327 | + Map.Entry<CCMBridge.Builder, CachedCCMAccess> entry = iterator.next(); | |
| 328 | + sb.append(entry.getValue().getClusterName()) | |
| 329 | + .append(" (") | |
| 330 | + .append(entry.getKey().weight()) | |
| 331 | + .append(")"); | |
| 332 | + if (iterator.hasNext()) | |
| 333 | + sb.append(", "); | |
| 334 | + } | |
| 335 | + LOGGER.debug("Cache contents: {{}}", sb.toString()); | |
| 336 | + LOGGER.debug("Cache stats: {}", CACHE.stats()); | |
| 337 | + } | |
| 309 | 338 | } |
| 310 | 339 | |
| 311 | 340 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CCMConfig.java +4 −1
| @@ -24,6 +24,9 @@ | ||
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | 26 | * The configuration to use when running tests with {@link CCMTestsSupport}. |
| 27 | + * <p/> | |
| 28 | + * This annotation can be used at the class level, or at the method level if you annotate the class with | |
| 29 | + * {@code @CreateCCM(PER_METHOD)}. | |
| 27 | 30 | */ |
| 28 | 31 | @Retention(RUNTIME) |
| 29 | 32 | @Target({TYPE, METHOD}) |
| @@ -135,7 +138,7 @@ | ||
| 135 | 138 | * |
| 136 | 139 | * @return The workloads to assign to each node. |
| 137 | 140 | */ |
| 138 | - CCMAccess.Workload[] workloads() default {}; | |
| 141 | + CCMWorkload[] workloads() default {}; | |
| 139 | 142 | |
| 140 | 143 | /** |
| 141 | 144 | * Returns {@code true} if a {@link CCMBridge} instance should be automatically created, {@code false} otherwise. |
modified driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java +43 −32
| @@ -213,7 +213,17 @@ | ||
| 213 | 213 | } |
| 214 | 214 | |
| 215 | 215 | @Override |
| 216 | - public void setWorkload(int node, Workload workload) { | |
| 216 | + public void updateDSENodeConfig(int n, String key, Object value) { | |
| 217 | + throw new UnsupportedOperationException("This CCM cluster is read-only"); | |
| 218 | + } | |
| 219 | + | |
| 220 | + @Override | |
| 221 | + public void updateDSENodeConfig(int n, Map<String, Object> configs) { | |
| 222 | + throw new UnsupportedOperationException("This CCM cluster is read-only"); | |
| 223 | + } | |
| 224 | + | |
| 225 | + @Override | |
| 226 | + public void setWorkload(int node, Workload... workload) { | |
| 217 | 227 | throw new UnsupportedOperationException("This CCM cluster is read-only"); |
| 218 | 228 | } |
| 219 | 229 | |
| @@ -351,17 +361,17 @@ | ||
| 351 | 361 | return args; |
| 352 | 362 | } |
| 353 | 363 | |
| 354 | - private List<Workload> workloads() { | |
| 364 | + private List<Workload[]> workloads() { | |
| 355 | 365 | int total = 0; |
| 356 | 366 | for (int perDc : numberOfNodes()) |
| 357 | 367 | total += perDc; |
| 358 | - List<Workload> workloads = new ArrayList<Workload>(Collections.<Workload>nCopies(total, null)); | |
| 368 | + List<Workload[]> workloads = new ArrayList<Workload[]>(Collections.<Workload[]>nCopies(total, null)); | |
| 359 | 369 | for (int i = annotations.size() - 1; i >= 0; i--) { |
| 360 | 370 | CCMConfig ann = annotations.get(i); |
| 361 | - Workload[] annWorkloads = ann.workloads(); | |
| 371 | + CCMWorkload[] annWorkloads = ann.workloads(); | |
| 362 | 372 | for (int j = 0; j < annWorkloads.length; j++) { |
| 363 | - Workload workload = annWorkloads[j]; | |
| 364 | - workloads.set(j, workload); | |
| 373 | + CCMWorkload nodeWorkloads = annWorkloads[j]; | |
| 374 | + workloads.set(j, nodeWorkloads.value()); | |
| 365 | 375 | } |
| 366 | 376 | } |
| 367 | 377 | return workloads; |
| @@ -417,32 +427,32 @@ | ||
| 417 | 427 | ccmBuilder = ccmProvider(testInstance); |
| 418 | 428 | if (ccmBuilder == null) { |
| 419 | 429 | ccmBuilder = CCMBridge.builder().withNodes(numberOfNodes()).notStarted(); |
| 420 | - if (version() != null) | |
| 421 | - ccmBuilder.withVersion(version()); | |
| 422 | - if (dse()) | |
| 423 | - ccmBuilder.withDSE(); | |
| 424 | - if (ssl()) | |
| 425 | - ccmBuilder.withSSL(); | |
| 426 | - if (auth()) | |
| 427 | - ccmBuilder.withAuth(); | |
| 428 | - for (Map.Entry<String, Object> entry : config().entrySet()) { | |
| 429 | - ccmBuilder.withCassandraConfiguration(entry.getKey(), entry.getValue()); | |
| 430 | - } | |
| 431 | - for (Map.Entry<String, Object> entry : dseConfig().entrySet()) { | |
| 432 | - ccmBuilder.withDSEConfiguration(entry.getKey(), entry.getValue()); | |
| 433 | - } | |
| 434 | - for (String option : startOptions()) { | |
| 435 | - ccmBuilder.withCreateOptions(option); | |
| 436 | - } | |
| 437 | - for (String arg : jvmArgs()) { | |
| 438 | - ccmBuilder.withJvmArgs(arg); | |
| 439 | - } | |
| 440 | - List<Workload> workloads = workloads(); | |
| 441 | - for (int i = 0; i < workloads.size(); i++) { | |
| 442 | - Workload workload = workloads.get(i); | |
| 443 | - if (workload != null) | |
| 444 | - ccmBuilder.withWorkload(i + 1, workload); | |
| 445 | - } | |
| 430 | + } | |
| 431 | + if (version() != null) | |
| 432 | + ccmBuilder.withVersion(version()); | |
| 433 | + if (dse()) | |
| 434 | + ccmBuilder.withDSE(); | |
| 435 | + if (ssl()) | |
| 436 | + ccmBuilder.withSSL(); | |
| 437 | + if (auth()) | |
| 438 | + ccmBuilder.withAuth(); | |
| 439 | + for (Map.Entry<String, Object> entry : config().entrySet()) { | |
| 440 | + ccmBuilder.withCassandraConfiguration(entry.getKey(), entry.getValue()); | |
| 441 | + } | |
| 442 | + for (Map.Entry<String, Object> entry : dseConfig().entrySet()) { | |
| 443 | + ccmBuilder.withDSEConfiguration(entry.getKey(), entry.getValue()); | |
| 444 | + } | |
| 445 | + for (String option : startOptions()) { | |
| 446 | + ccmBuilder.withCreateOptions(option); | |
| 447 | + } | |
| 448 | + for (String arg : jvmArgs()) { | |
| 449 | + ccmBuilder.withJvmArgs(arg); | |
| 450 | + } | |
| 451 | + List<Workload[]> workloads = workloads(); | |
| 452 | + for (int i = 0; i < workloads.size(); i++) { | |
| 453 | + Workload[] workload = workloads.get(i); | |
| 454 | + if (workload != null) | |
| 455 | + ccmBuilder.withWorkload(i + 1, workload); | |
| 446 | 456 | } |
| 447 | 457 | } |
| 448 | 458 | return ccmBuilder; |
| @@ -760,6 +770,7 @@ | ||
| 760 | 770 | } |
| 761 | 771 | } |
| 762 | 772 | } |
| 773 | + | |
| 763 | 774 | /** |
| 764 | 775 | * Signals that the test has encountered an unexpected error. |
| 765 | 776 | * <p/> |
added driver-core/src/test/java/com/datastax/driver/core/CCMWorkload.java +37 −0
| @@ -0,0 +1,37 @@ | ||
| 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.lang.annotation.ElementType; | |
| 19 | +import java.lang.annotation.Retention; | |
| 20 | +import java.lang.annotation.RetentionPolicy; | |
| 21 | +import java.lang.annotation.Target; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * A set of workloads to assign to a specific node. | |
| 25 | + */ | |
| 26 | +@Retention(RetentionPolicy.RUNTIME) | |
| 27 | +@Target(ElementType.ANNOTATION_TYPE) | |
| 28 | +public @interface CCMWorkload { | |
| 29 | + | |
| 30 | + /** | |
| 31 | + * The workloads to assign to a specific node. | |
| 32 | + * | |
| 33 | + * @return The workloads to assign to a specifc node. | |
| 34 | + */ | |
| 35 | + CCMAccess.Workload[] value() default {}; | |
| 36 | + | |
| 37 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +3 −2
| @@ -34,6 +34,7 @@ | ||
| 34 | 34 | import java.net.UnknownHostException; |
| 35 | 35 | import java.util.List; |
| 36 | 36 | import java.util.Map; |
| 37 | +import java.util.UUID; | |
| 37 | 38 | import java.util.concurrent.TimeUnit; |
| 38 | 39 | import java.util.concurrent.TimeoutException; |
| 39 | 40 | |
| @@ -139,8 +140,7 @@ | ||
| 139 | 140 | } |
| 140 | 141 | assertThat(cluster).host(failingHost.address).isReconnectingFromDown(); |
| 141 | 142 | } |
| 142 | - assertThat(cluster).host(missingHostAddress).isNull(); | |
| 143 | - | |
| 143 | + assertThat(TestUtils.findHost(cluster, missingHostAddress)).isNull(); | |
| 144 | 144 | } finally { |
| 145 | 145 | if (cluster != null) |
| 146 | 146 | cluster.close(); |
| @@ -276,6 +276,7 @@ | ||
| 276 | 276 | .put("rack", "rack1") |
| 277 | 277 | .put("release_version", "2.0.1") |
| 278 | 278 | .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++))) |
| 279 | + .put("host_id", UUID.randomUUID()) | |
| 279 | 280 | .build()); |
| 280 | 281 | } |
| 281 | 282 |
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +8 −9
| @@ -49,10 +49,9 @@ | ||
| 49 | 49 | createKeyspace = false, |
| 50 | 50 | config = { |
| 51 | 51 | // tests fail often with write or read timeouts |
| 52 | - "hinted_handoff_enabled:true", | |
| 53 | 52 | "phi_convict_threshold:5", |
| 54 | - "read_request_timeout_in_ms:100000", | |
| 55 | - "write_request_timeout_in_ms:100000" | |
| 53 | + "read_request_timeout_in_ms:200000", | |
| 54 | + "write_request_timeout_in_ms:200000" | |
| 56 | 55 | } |
| 57 | 56 | ) |
| 58 | 57 | public class ConsistencyTest extends AbstractPoliciesTest { |
| @@ -61,40 +60,40 @@ | ||
| 61 | 60 | |
| 62 | 61 | private Cluster.Builder tokenAwareRoundRobin() { |
| 63 | 62 | return Cluster.builder() |
| 64 | - .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 63 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000)) | |
| 65 | 64 | .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); |
| 66 | 65 | } |
| 67 | 66 | |
| 68 | 67 | private Cluster.Builder tokenAwareRoundRobinNoShuffle() { |
| 69 | 68 | return Cluster.builder() |
| 70 | - .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 69 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000)) | |
| 71 | 70 | .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)); |
| 72 | 71 | } |
| 73 | 72 | |
| 74 | 73 | private Cluster.Builder tokenAwareRoundRobinDowngrading() { |
| 75 | 74 | return Cluster.builder() |
| 76 | - .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 75 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000)) | |
| 77 | 76 | .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())) |
| 78 | 77 | .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); |
| 79 | 78 | } |
| 80 | 79 | |
| 81 | 80 | private Cluster.Builder tokenAwareRoundRobinNoShuffleDowngrading() { |
| 82 | 81 | return Cluster.builder() |
| 83 | - .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 82 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000)) | |
| 84 | 83 | .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)) |
| 85 | 84 | .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); |
| 86 | 85 | } |
| 87 | 86 | |
| 88 | 87 | private Cluster.Builder roundRobinDowngrading() { |
| 89 | 88 | return Cluster.builder() |
| 90 | - .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 89 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000)) | |
| 91 | 90 | .withLoadBalancingPolicy(new RoundRobinPolicy()) |
| 92 | 91 | .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); |
| 93 | 92 | } |
| 94 | 93 | |
| 95 | 94 | private Cluster.Builder tokenAwareDCAwareRoundRobinNoShuffleDowngrading() { |
| 96 | 95 | return Cluster.builder() |
| 97 | - .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 96 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000)) | |
| 98 | 97 | .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build(), false)) |
| 99 | 98 | .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); |
| 100 | 99 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +108 −0
| @@ -20,8 +20,10 @@ | ||
| 20 | 20 | import com.google.common.base.Function; |
| 21 | 21 | import com.google.common.collect.HashMultiset; |
| 22 | 22 | import com.google.common.collect.Maps; |
| 23 | +import org.apache.log4j.Level; | |
| 23 | 24 | import org.slf4j.Logger; |
| 24 | 25 | import org.slf4j.LoggerFactory; |
| 26 | +import org.testng.annotations.DataProvider; | |
| 25 | 27 | import org.testng.annotations.Test; |
| 26 | 28 | |
| 27 | 29 | import java.net.InetAddress; |
| @@ -199,7 +201,113 @@ | ||
| 199 | 201 | } finally { |
| 200 | 202 | scassandras.stop(); |
| 201 | 203 | } |
| 204 | + } | |
| 205 | + | |
| 206 | + @DataProvider | |
| 207 | + public static Object[][] disallowedNullColumnsInPeerData() { | |
| 208 | + return new Object[][]{ | |
| 209 | + {"host_id"}, | |
| 210 | + {"data_center"}, | |
| 211 | + {"rack"}, | |
| 212 | + {"tokens"}, | |
| 213 | + {"host_id,data_center,rack,tokens"} | |
| 214 | + }; | |
| 215 | + } | |
| 216 | + | |
| 217 | + /** | |
| 218 | + * Validates that if the com.datastax.driver.EXTENDED_PEER_CHECK system property is set to true that a peer | |
| 219 | + * with null values for host_id, data_center, rack, or tokens is ignored. | |
| 220 | + * | |
| 221 | + * @test_category host:metadata | |
| 222 | + * @jira_ticket JAVA-852 | |
| 223 | + * @since 2.1.10 | |
| 224 | + */ | |
| 225 | + @Test(groups = "isolated", dataProvider = "disallowedNullColumnsInPeerData") | |
| 226 | + @CCMConfig(createCcm = false) | |
| 227 | + public void should_ignore_peer_if_extended_peer_check_is_enabled(String columns) { | |
| 228 | + System.setProperty("com.datastax.driver.EXTENDED_PEER_CHECK", "true"); | |
| 229 | + run_with_null_peer_info(columns, false); | |
| 230 | + } | |
| 231 | + | |
| 232 | + /** | |
| 233 | + * Validates that a peer with null values for host_id, data_center, rack, or tokens is ignored. | |
| 234 | + * | |
| 235 | + * @test_category host:metadata | |
| 236 | + * @jira_ticket JAVA-852 | |
| 237 | + * @since 2.1.10 | |
| 238 | + */ | |
| 239 | + @Test(groups = "short", dataProvider = "disallowedNullColumnsInPeerData") | |
| 240 | + @CCMConfig(createCcm = false) | |
| 241 | + public void should_ignore_and_warn_peers_with_null_entries_by_default(String columns) { | |
| 242 | + run_with_null_peer_info(columns, false); | |
| 243 | + } | |
| 244 | + | |
| 245 | + static void run_with_null_peer_info(String columns, boolean expectPeer2) { | |
| 246 | + // given: A cluster with peer 2 having a null rack. | |
| 247 | + ScassandraCluster.ScassandraClusterBuilder builder = ScassandraCluster.builder() | |
| 248 | + .withNodes(3); | |
| 249 | + | |
| 250 | + StringBuilder columnDataBuilder = new StringBuilder(); | |
| 251 | + for (String column : columns.split(",")) { | |
| 252 | + builder = builder.forcePeerInfo(1, 2, column, null); | |
| 253 | + columnDataBuilder.append(String.format("%s=null, ", column)); | |
| 254 | + } | |
| 255 | + | |
| 256 | + String columnData = columnDataBuilder.toString(); | |
| 257 | + if (columnData.endsWith(", ")) { | |
| 258 | + columnData = columnData.substring(0, columnData.length() - 2); | |
| 259 | + } | |
| 260 | + | |
| 261 | + ScassandraCluster scassandraCluster = builder.build(); | |
| 262 | + | |
| 263 | + Cluster cluster = Cluster.builder() | |
| 264 | + .addContactPoints(scassandraCluster.address(1).getAddress()) | |
| 265 | + .withPort(scassandraCluster.getBinaryPort()) | |
| 266 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 267 | + .build(); | |
| 268 | + | |
| 269 | + // Capture logs to ensure appropriate warnings are logged. | |
| 270 | + org.apache.log4j.Logger cLogger = org.apache.log4j.Logger.getLogger("com.datastax.driver.core"); | |
| 271 | + Level originalLevel = cLogger.getLevel(); | |
| 272 | + if (originalLevel != null && !originalLevel.isGreaterOrEqual(Level.WARN)) { | |
| 273 | + cLogger.setLevel(Level.WARN); | |
| 274 | + } | |
| 275 | + MemoryAppender logs = new MemoryAppender(); | |
| 276 | + cLogger.addAppender(logs); | |
| 202 | 277 | |
| 278 | + try { | |
| 279 | + scassandraCluster.init(); | |
| 280 | + | |
| 281 | + // when: Initializing a cluster instance and grabbing metadata. | |
| 282 | + cluster.init(); | |
| 283 | + | |
| 284 | + InetAddress node2Address = scassandraCluster.address(2).getAddress(); | |
| 285 | + String expectedError = String.format("Found invalid row in system.peers: [peer=%s, %s]. " + | |
| 286 | + "This is likely a gossip or snitch issue, this host will be ignored.", node2Address, columnData); | |
| 287 | + String log = logs.get(); | |
| 288 | + // then: A peer with a null rack should not show up in host metadata, unless allowed via system property. | |
| 289 | + if (expectPeer2) { | |
| 290 | + assertThat(cluster.getMetadata().getAllHosts()) | |
| 291 | + .hasSize(3) | |
| 292 | + .extractingResultOf("getAddress") | |
| 293 | + .contains(node2Address); | |
| 294 | + | |
| 295 | + assertThat(log).doesNotContain(expectedError); | |
| 296 | + } else { | |
| 297 | + assertThat(cluster.getMetadata().getAllHosts()) | |
| 298 | + .hasSize(2) | |
| 299 | + .extractingResultOf("getAddress") | |
| 300 | + .doesNotContain(node2Address); | |
| 301 | + | |
| 302 | + assertThat(log) | |
| 303 | + .containsOnlyOnce(expectedError); | |
| 304 | + } | |
| 305 | + } finally { | |
| 306 | + cLogger.removeAppender(logs); | |
| 307 | + cLogger.setLevel(originalLevel); | |
| 308 | + cluster.close(); | |
| 309 | + scassandraCluster.stop(); | |
| 310 | + } | |
| 203 | 311 | } |
| 204 | 312 | |
| 205 | 313 | static class QueryPlanCountingPolicy extends DelegatingLoadBalancingPolicy { |
modified driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java +3 −14
| @@ -15,13 +15,10 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 19 | 18 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| 20 | 19 | import com.datastax.driver.core.utils.CassandraVersion; |
| 21 | -import com.google.common.base.Throwables; | |
| 22 | 20 | import com.google.common.collect.ImmutableMap; |
| 23 | 21 | import org.apache.log4j.Logger; |
| 24 | -import org.assertj.core.api.iterable.Extractor; | |
| 25 | 22 | import org.testng.annotations.BeforeMethod; |
| 26 | 23 | import org.testng.annotations.Test; |
| 27 | 24 | |
| @@ -246,17 +243,9 @@ | ||
| 246 | 243 | statement.setOutgoingPayload(payload1); |
| 247 | 244 | v3session.execute(statement); |
| 248 | 245 | fail("Should not send custom payloads with protocol V3"); |
| 249 | - } catch (NoHostAvailableException nhae) { | |
| 250 | - assertThat(nhae.getErrors().values()) | |
| 251 | - .extracting(new Extractor<Throwable, Throwable>() { | |
| 252 | - @Override | |
| 253 | - public Throwable extract(Throwable input) { | |
| 254 | - return Throwables.getRootCause(input); | |
| 255 | - } | |
| 256 | - }) | |
| 257 | - .hasOnlyElementsOfType(UnsupportedFeatureException.class) | |
| 258 | - .extracting("message") | |
| 259 | - .containsOnly("Unsupported feature with the native protocol V3 (which is currently in use): Custom payloads are only supported since native protocol V4"); | |
| 246 | + } catch (UnsupportedFeatureException e) { | |
| 247 | + assertThat(e.getMessage()).isEqualTo( | |
| 248 | + "Unsupported feature with the native protocol V3 (which is currently in use): Custom payloads are only supported since native protocol V4"); | |
| 260 | 249 | } |
| 261 | 250 | } |
| 262 | 251 |
modified driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java +2 −69
| @@ -26,6 +26,8 @@ | ||
| 26 | 26 | import static com.datastax.driver.core.Assertions.assertThat; |
| 27 | 27 | import static com.datastax.driver.core.DataType.cint; |
| 28 | 28 | import static com.datastax.driver.core.DataType.custom; |
| 29 | +import static com.datastax.driver.core.TestUtils.serializeForCompositeType; | |
| 30 | +import static com.datastax.driver.core.TestUtils.serializeForDynamicCompositeType; | |
| 29 | 31 | |
| 30 | 32 | /** |
| 31 | 33 | * Test we "support" custom types. |
| @@ -185,73 +187,4 @@ | ||
| 185 | 187 | assertThat(value.getBytes("c1")).isEqualTo(serializeForDynamicCompositeType("hello", 93)); |
| 186 | 188 | assertThat(value.getLong("c2")).isEqualTo(400); |
| 187 | 189 | } |
| 188 | - | |
| 189 | - | |
| 190 | - private ByteBuffer serializeForDynamicCompositeType(Object... params) { | |
| 191 | - List<ByteBuffer> l = new ArrayList<ByteBuffer>(); | |
| 192 | - int size = 0; | |
| 193 | - for (Object p : params) { | |
| 194 | - if (p instanceof Integer) { | |
| 195 | - ByteBuffer elt = ByteBuffer.allocate(2 + 2 + 4 + 1); | |
| 196 | - elt.putShort((short) (0x8000 | 'i')); | |
| 197 | - elt.putShort((short) 4); | |
| 198 | - elt.putInt((Integer) p); | |
| 199 | - elt.put((byte) 0); | |
| 200 | - elt.flip(); | |
| 201 | - size += elt.remaining(); | |
| 202 | - l.add(elt); | |
| 203 | - } else if (p instanceof String) { | |
| 204 | - ByteBuffer bytes = ByteBuffer.wrap(((String) p).getBytes()); | |
| 205 | - ByteBuffer elt = ByteBuffer.allocate(2 + 2 + bytes.remaining() + 1); | |
| 206 | - elt.putShort((short) (0x8000 | 's')); | |
| 207 | - elt.putShort((short) bytes.remaining()); | |
| 208 | - elt.put(bytes); | |
| 209 | - elt.put((byte) 0); | |
| 210 | - elt.flip(); | |
| 211 | - size += elt.remaining(); | |
| 212 | - l.add(elt); | |
| 213 | - } else { | |
| 214 | - throw new RuntimeException(); | |
| 215 | - } | |
| 216 | - } | |
| 217 | - ByteBuffer res = ByteBuffer.allocate(size); | |
| 218 | - for (ByteBuffer bb : l) | |
| 219 | - res.put(bb); | |
| 220 | - res.flip(); | |
| 221 | - return res; | |
| 222 | - } | |
| 223 | - | |
| 224 | - private ByteBuffer serializeForCompositeType(Object... params) { | |
| 225 | - | |
| 226 | - List<ByteBuffer> l = new ArrayList<ByteBuffer>(); | |
| 227 | - int size = 0; | |
| 228 | - for (Object p : params) { | |
| 229 | - if (p instanceof Integer) { | |
| 230 | - ByteBuffer elt = ByteBuffer.allocate(2 + 4 + 1); | |
| 231 | - elt.putShort((short) 4); | |
| 232 | - elt.putInt((Integer) p); | |
| 233 | - elt.put((byte) 0); | |
| 234 | - elt.flip(); | |
| 235 | - size += elt.remaining(); | |
| 236 | - l.add(elt); | |
| 237 | - } else if (p instanceof String) { | |
| 238 | - ByteBuffer bytes = ByteBuffer.wrap(((String) p).getBytes()); | |
| 239 | - ByteBuffer elt = ByteBuffer.allocate(2 + bytes.remaining() + 1); | |
| 240 | - elt.putShort((short) bytes.remaining()); | |
| 241 | - elt.put(bytes); | |
| 242 | - elt.put((byte) 0); | |
| 243 | - elt.flip(); | |
| 244 | - size += elt.remaining(); | |
| 245 | - l.add(elt); | |
| 246 | - } else { | |
| 247 | - throw new RuntimeException(); | |
| 248 | - } | |
| 249 | - } | |
| 250 | - ByteBuffer res = ByteBuffer.allocate(size); | |
| 251 | - for (ByteBuffer bb : l) | |
| 252 | - res.put(bb); | |
| 253 | - res.flip(); | |
| 254 | - return res; | |
| 255 | - } | |
| 256 | - | |
| 257 | 190 | } |
modified driver-core/src/test/java/com/datastax/driver/core/DataProviders.java +1 −1
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | @Override |
| 34 | 34 | public boolean apply(ConsistencyLevel input) { |
| 35 | 35 | // filter out serial CLs. |
| 36 | - return !input.equals(ConsistencyLevel.SERIAL) && !input.equals(ConsistencyLevel.LOCAL_SERIAL); | |
| 36 | + return !input.isSerial(); | |
| 37 | 37 | } |
| 38 | 38 | }).iterator(); |
| 39 | 39 |
modified driver-core/src/test/java/com/datastax/driver/core/DseCCMClusterTest.java +13 −1
| @@ -17,6 +17,8 @@ | ||
| 17 | 17 | |
| 18 | 18 | import org.testng.annotations.Test; |
| 19 | 19 | |
| 20 | +import static com.datastax.driver.core.CCMAccess.Workload.*; | |
| 21 | + | |
| 20 | 22 | /** |
| 21 | 23 | * A simple test to validate DSE setups. |
| 22 | 24 | * <p/> |
| @@ -68,11 +70,21 @@ | ||
| 68 | 70 | * A correct example is as follows: {@code /usr/bin:/usr/local/bin:/bin:/usr/sbin:$JAVA_HOME/bin:$PATH}. |
| 69 | 71 | */ |
| 70 | 72 | @Test(enabled = false) |
| 71 | -@CCMConfig(dse = true, version = "4.8.3") | |
| 73 | +@CCMConfig( | |
| 74 | + dse = true, | |
| 75 | + numberOfNodes = 3, | |
| 76 | + version = "4.8.3", | |
| 77 | + workloads = { | |
| 78 | + @CCMWorkload(solr), | |
| 79 | + @CCMWorkload({spark, solr}), | |
| 80 | + @CCMWorkload({cassandra, spark}) | |
| 81 | + } | |
| 82 | +) | |
| 72 | 83 | public class DseCCMClusterTest extends CCMTestsSupport { |
| 73 | 84 | |
| 74 | 85 | @Test(groups = "short") |
| 75 | 86 | public void should_conenct_to_dse() throws InterruptedException { |
| 87 | + | |
| 76 | 88 | } |
| 77 | 89 | |
| 78 | 90 | } |
added driver-core/src/test/java/com/datastax/driver/core/ExtendedPeerCheckDisabledTest.java +36 −0
| @@ -0,0 +1,36 @@ | ||
| 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 | +public class ExtendedPeerCheckDisabledTest { | |
| 21 | + | |
| 22 | + /** | |
| 23 | + * Validates that if the com.datastax.driver.EXTENDED_PEER_CHECK system property is set to false that a peer | |
| 24 | + * with null values for host_id, data_center, rack, tokens is not ignored. | |
| 25 | + * | |
| 26 | + * @test_category host:metadata | |
| 27 | + * @jira_ticket JAVA-852 | |
| 28 | + * @since 2.1.10 | |
| 29 | + */ | |
| 30 | + @Test(groups = "isolated", dataProvider = "disallowedNullColumnsInPeerData", dataProviderClass = ControlConnectionTest.class) | |
| 31 | + @CCMConfig(createCcm = false) | |
| 32 | + public void should_use_peer_if_extended_peer_check_is_disabled(String columns) { | |
| 33 | + System.setProperty("com.datastax.driver.EXTENDED_PEER_CHECK", "false"); | |
| 34 | + ControlConnectionTest.run_with_null_peer_info(columns, true); | |
| 35 | + } | |
| 36 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataTest.java +39 −1
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | import org.testng.annotations.Test; |
| 20 | 20 | |
| 21 | 21 | import static com.datastax.driver.core.Assertions.assertThat; |
| 22 | -import static com.datastax.driver.core.DataType.cint; | |
| 22 | +import static com.datastax.driver.core.DataType.*; | |
| 23 | 23 | import static org.assertj.core.api.Assertions.entry; |
| 24 | 24 | |
| 25 | 25 | @CassandraVersion(major = 2.2) |
| @@ -123,6 +123,44 @@ | ||
| 123 | 123 | assertThat(function.toString()).isEqualTo(cqlFunction); |
| 124 | 124 | } |
| 125 | 125 | |
| 126 | + /** | |
| 127 | + * Ensures that functions whose arguments contain complex types such as | |
| 128 | + * tuples and collections, and nested combinations thereof, are | |
| 129 | + * correctly parsed. | |
| 130 | + * | |
| 131 | + * @jira_ticket JAVA-1137 | |
| 132 | + */ | |
| 133 | + @Test(groups = "short") | |
| 134 | + public void should_parse_and_format_functions_with_complex_arguments() { | |
| 135 | + // given | |
| 136 | + String cql = String.format("CREATE FUNCTION %s.complex(x tuple<tuple<int>, map<int, int>>) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return 42;';", keyspace); | |
| 137 | + // when | |
| 138 | + session().execute(cql); | |
| 139 | + // then | |
| 140 | + KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace); | |
| 141 | + DataType argumentType = cluster().getMetadata().newTupleType(cluster().getMetadata().newTupleType(cint()), map(cint(), cint())); | |
| 142 | + FunctionMetadata function = keyspace.getFunction("complex", argumentType); | |
| 143 | + assertThat(function).isNotNull(); | |
| 144 | + assertThat(function.getKeyspace()).isEqualTo(keyspace); | |
| 145 | + assertThat(function.getSignature()).isEqualTo("complex(tuple<tuple<int>, map<int, int>>)"); | |
| 146 | + assertThat(function.getSimpleName()).isEqualTo("complex"); | |
| 147 | + assertThat(function.getReturnType()).isEqualTo(cint()); | |
| 148 | + assertThat(function.getArguments()) | |
| 149 | + .containsEntry("x", argumentType); | |
| 150 | + assertThat(function.getLanguage()).isEqualTo("java"); | |
| 151 | + assertThat(function.getBody()).isEqualTo("return 42;"); | |
| 152 | + assertThat(function.isCalledOnNullInput()).isFalse(); | |
| 153 | + assertThat(function.toString()) | |
| 154 | + .isEqualTo(cql); | |
| 155 | + assertThat(function.exportAsString()) | |
| 156 | + .isEqualTo(String.format("CREATE FUNCTION %s.complex(\n" | |
| 157 | + + " x tuple<tuple<int>, map<int, int>>)\n" | |
| 158 | + + "RETURNS NULL ON NULL INPUT\n" | |
| 159 | + + "RETURNS int\n" | |
| 160 | + + "LANGUAGE java\n" | |
| 161 | + + "AS 'return 42;';", this.keyspace)); | |
| 162 | + } | |
| 163 | + | |
| 126 | 164 | @Override |
| 127 | 165 | public void onTestContextInitialized() { |
| 128 | 166 | execute( |
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +24 −3
| @@ -21,9 +21,11 @@ | ||
| 21 | 21 | import org.assertj.core.api.AbstractAssert; |
| 22 | 22 | |
| 23 | 23 | import java.net.InetAddress; |
| 24 | +import java.util.concurrent.Callable; | |
| 24 | 25 | import java.util.concurrent.CountDownLatch; |
| 25 | 26 | import java.util.concurrent.TimeUnit; |
| 26 | 27 | |
| 28 | +import static com.datastax.driver.core.ConditionChecker.check; | |
| 27 | 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 28 | 30 | import static org.assertj.core.api.Assertions.fail; |
| 29 | 31 | |
| @@ -73,9 +75,18 @@ | ||
| 73 | 75 | } |
| 74 | 76 | |
| 75 | 77 | public HostAssert isNotReconnectingFromDown() { |
| 76 | - assertThat(actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone()) | |
| 77 | - .isFalse(); | |
| 78 | - return this; | |
| 78 | + // Ensure that host is not attempting a reconnect. Because of JAVA-970 we cannot | |
| 79 | + // be sure that there is a race and another pool is created before the host is marked down so we | |
| 80 | + // check to see it stops after 30 seconds. | |
| 81 | + // TODO: Change this to check only once if JAVA-970 is fixed. | |
| 82 | + check().before(30, TimeUnit.SECONDS).that(new Callable<Boolean>() { | |
| 83 | + @Override | |
| 84 | + public Boolean call() throws Exception { | |
| 85 | + // Whether or not host is down and reconnection attempt is in progress. | |
| 86 | + return actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone(); | |
| 87 | + } | |
| 88 | + }).becomesFalse(); | |
| 89 | + return this.isDown(); | |
| 79 | 90 | } |
| 80 | 91 | |
| 81 | 92 | public HostAssert comesUpWithin(long duration, TimeUnit unit) { |
| @@ -150,6 +161,16 @@ | ||
| 150 | 161 | return this; |
| 151 | 162 | } |
| 152 | 163 | |
| 164 | + public HostAssert hasDseGraph() { | |
| 165 | + assertThat(actual.isDseGraphEnabled()).isTrue(); | |
| 166 | + return this; | |
| 167 | + } | |
| 168 | + | |
| 169 | + public HostAssert hasNoDseGraph() { | |
| 170 | + assertThat(actual.isDseGraphEnabled()).isFalse(); | |
| 171 | + return this; | |
| 172 | + } | |
| 173 | + | |
| 153 | 174 | public HostAssert hasListenAddress(InetAddress address) { |
| 154 | 175 | assertThat(actual.getListenAddress()).isNotNull().isEqualTo(address); |
| 155 | 176 | return this; |
modified driver-core/src/test/java/com/datastax/driver/core/HostMetadataIntegrationTest.java +79 −1
| @@ -80,7 +80,7 @@ | ||
| 80 | 80 | * @test_category host:metadata |
| 81 | 81 | * @jira_ticket JAVA-1042 |
| 82 | 82 | */ |
| 83 | - @Test(groups = "short'") | |
| 83 | + @Test(groups = "short") | |
| 84 | 84 | public void should_parse_dse_workload_and_version_if_available() { |
| 85 | 85 | // given: A 5 node cluster with all nodes having a workload and dse_version except node 2. |
| 86 | 86 | ScassandraCluster scassandraCluster = ScassandraCluster.builder() |
| @@ -206,6 +206,84 @@ | ||
| 206 | 206 | } |
| 207 | 207 | } |
| 208 | 208 | |
| 209 | + /** | |
| 210 | + * Validates that {@link Host#isDseGraphEnabled()} returns the value defined in the <code>graph</code> columns if | |
| 211 | + * it is present in <code>system.local</code> or <code>system.peers</code> otherwise it returns false. | |
| 212 | + * | |
| 213 | + * @test_category host:metadata | |
| 214 | + * @jira_ticket JAVA-1171 | |
| 215 | + */ | |
| 216 | + @Test(groups = "short") | |
| 217 | + public void should_parse_dse_graph_if_available() { | |
| 218 | + // given: A 3 node cluster with all nodes having a graph value except node 2. | |
| 219 | + ScassandraCluster scassandraCluster = ScassandraCluster.builder() | |
| 220 | + .withIpPrefix(TestUtils.IP_PREFIX) | |
| 221 | + .withNodes(3) | |
| 222 | + .forcePeerInfo(1, 1, "graph", true) | |
| 223 | + .forcePeerInfo(1, 3, "graph", false) | |
| 224 | + .build(); | |
| 225 | + | |
| 226 | + Cluster cluster = Cluster.builder() | |
| 227 | + .addContactPoints(scassandraCluster.address(1).getAddress()) | |
| 228 | + .withPort(scassandraCluster.getBinaryPort()) | |
| 229 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 230 | + .build(); | |
| 231 | + | |
| 232 | + try { | |
| 233 | + scassandraCluster.init(); | |
| 234 | + // when: initializing a cluster instance. | |
| 235 | + cluster.init(); | |
| 236 | + | |
| 237 | + // then: | |
| 238 | + // - node 1 should have graph. | |
| 239 | + // - node 2 and node 3 should not have graph. | |
| 240 | + assertThat(cluster).host(1).hasDseGraph(); | |
| 241 | + assertThat(cluster).host(2).hasNoDseGraph(); | |
| 242 | + assertThat(cluster).host(3).hasNoDseGraph(); | |
| 243 | + } finally { | |
| 244 | + cluster.close(); | |
| 245 | + scassandraCluster.stop(); | |
| 246 | + } | |
| 247 | + } | |
| 248 | + | |
| 249 | + /** | |
| 250 | + * Validates that {@link Host#isDseGraphEnabled()} returns false if the <code>graph</code> column is not present | |
| 251 | + * in <code>system.local</code> for the control host. | |
| 252 | + * | |
| 253 | + * @test_category host:metadata | |
| 254 | + * @jira_ticket JAVA-1171 | |
| 255 | + */ | |
| 256 | + @Test(groups = "short") | |
| 257 | + public void should_not_parse_dse_graph_if_not_present_in_local_table() { | |
| 258 | + // given: A cluster with node 1 (control host) not having graph set, and node 2 with it set. | |
| 259 | + ScassandraCluster scassandraCluster = ScassandraCluster.builder() | |
| 260 | + .withIpPrefix(TestUtils.IP_PREFIX) | |
| 261 | + .withNodes(2) | |
| 262 | + .forcePeerInfo(1, 2, "graph", true) | |
| 263 | + .build(); | |
| 264 | + | |
| 265 | + Cluster cluster = Cluster.builder() | |
| 266 | + .addContactPoints(scassandraCluster.address(1).getAddress()) | |
| 267 | + .withPort(scassandraCluster.getBinaryPort()) | |
| 268 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 269 | + .build(); | |
| 270 | + | |
| 271 | + try { | |
| 272 | + scassandraCluster.init(); | |
| 273 | + // when: initializing a cluster instance. | |
| 274 | + cluster.init(); | |
| 275 | + | |
| 276 | + // then: | |
| 277 | + // - node 1 should have no graph. | |
| 278 | + // - node 2 should have graph. | |
| 279 | + assertThat(cluster).host(1).hasNoDseGraph(); | |
| 280 | + assertThat(cluster).host(2).hasDseGraph(); | |
| 281 | + } finally { | |
| 282 | + cluster.close(); | |
| 283 | + scassandraCluster.stop(); | |
| 284 | + } | |
| 285 | + } | |
| 286 | + | |
| 209 | 287 | /** |
| 210 | 288 | * Validates that {@link Host#getBroadcastAddress()} is set for all hosts (control host or not) in the default |
| 211 | 289 | * case of a cluster, as the broadcast address is derived from <code>broadcast_address</code> in |
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +2 −2
| @@ -20,7 +20,6 @@ | ||
| 20 | 20 | import com.google.common.collect.Lists; |
| 21 | 21 | import org.testng.annotations.Test; |
| 22 | 22 | |
| 23 | -import java.net.InetAddress; | |
| 24 | 23 | import java.net.InetSocketAddress; |
| 25 | 24 | |
| 26 | 25 | import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; |
| @@ -63,9 +62,10 @@ | ||
| 63 | 62 | .build()); |
| 64 | 63 | Session session = cluster.connect(); |
| 65 | 64 | String deleteStmt = String.format("DELETE rpc_address FROM system.peers WHERE peer = '%s'", |
| 66 | - InetAddress.getByName(TestUtils.IP_PREFIX + "2").getHostName()); | |
| 65 | + ccm().addressOfNode(2).getHostName()); | |
| 67 | 66 | session.execute(deleteStmt); |
| 68 | 67 | session.close(); |
| 68 | + cluster.close(); | |
| 69 | 69 | } |
| 70 | 70 | |
| 71 | 71 | } |
modified driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +26 −0
| @@ -112,6 +112,27 @@ | ||
| 112 | 112 | } |
| 113 | 113 | } |
| 114 | 114 | |
| 115 | + /** | |
| 116 | + * Validates that {@link PagingState} can be reused with a wrapped Statement. | |
| 117 | + * | |
| 118 | + * @test_category paging | |
| 119 | + * @expected_result {@link ResultSet} from the query with the provided {@link PagingState} starts from the | |
| 120 | + * subsequent row from the first query. | |
| 121 | + */ | |
| 122 | + @Test(groups = "short") | |
| 123 | + public void should_use_state_with_wrapped_statement() { | |
| 124 | + Statement st = new TestWrapper(new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY))); | |
| 125 | + ResultSet result = session().execute(st.setFetchSize(20)); | |
| 126 | + int pageSize = result.getAvailableWithoutFetching(); | |
| 127 | + String savedPagingStateString = result.getExecutionInfo().getPagingState().toString(); | |
| 128 | + | |
| 129 | + st = new TestWrapper(new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY))); | |
| 130 | + result = session().execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString))); | |
| 131 | + | |
| 132 | + //We have the result starting from the next page we stopped | |
| 133 | + assertThat(result.one().getInt("v")).isEqualTo(pageSize); | |
| 134 | + } | |
| 135 | + | |
| 115 | 136 | /** |
| 116 | 137 | * Validates that {@link PagingState} can be reused with the same {@link BoundStatement}. |
| 117 | 138 | * |
| @@ -224,5 +245,10 @@ | ||
| 224 | 245 | assertThat(result.one().getInt("v")).isEqualTo(pageSize); |
| 225 | 246 | } |
| 226 | 247 | |
| 248 | + static class TestWrapper extends StatementWrapper { | |
| 249 | + TestWrapper(Statement wrapped) { | |
| 250 | + super(wrapped); | |
| 251 | + } | |
| 252 | + } | |
| 227 | 253 | } |
| 228 | 254 |
added driver-core/src/test/java/com/datastax/driver/core/ProtocolV1Test.java +79 −0
| @@ -0,0 +1,79 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.exceptions.UnsupportedFeatureException; | |
| 19 | +import org.testng.annotations.Test; | |
| 20 | + | |
| 21 | +import static com.datastax.driver.core.ProtocolVersion.V1; | |
| 22 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 23 | + | |
| 24 | +/** | |
| 25 | + * Tests targeting protocol v1 specifically. | |
| 26 | + */ | |
| 27 | +@CCMConfig(version = "1.2.19") | |
| 28 | +public class ProtocolV1Test extends CCMTestsSupport { | |
| 29 | + | |
| 30 | + @Override | |
| 31 | + public Cluster.Builder createClusterBuilder() { | |
| 32 | + return super.createClusterBuilder() | |
| 33 | + .withProtocolVersion(V1); | |
| 34 | + } | |
| 35 | + | |
| 36 | + /** | |
| 37 | + * Validates that a simple query with no variables is correctly executed. | |
| 38 | + * @jira_ticket JAVA-1132 | |
| 39 | + */ | |
| 40 | + @Test(groups = "short") | |
| 41 | + public void should_execute_query_with_no_variables() throws Exception { | |
| 42 | + session().execute("select * from system.local"); | |
| 43 | + } | |
| 44 | + | |
| 45 | + /** | |
| 46 | + * Validates that a simple query with variables is not allowed with protocol V1. | |
| 47 | + * (Values in protocol V1 are only allowed in prepared statements). | |
| 48 | + * @jira_ticket JAVA-1132 | |
| 49 | + */ | |
| 50 | + @Test(groups = "short") | |
| 51 | + public void should_not_execute_query_with_variables() throws Exception { | |
| 52 | + try { | |
| 53 | + session().execute(new SimpleStatement("select * from system.local where key=?", "local")); | |
| 54 | + } catch (UnsupportedFeatureException e) { | |
| 55 | + assertThat(e).hasMessageContaining("Unsupported feature with the native protocol V1 (which is currently in use): Binary values are not supported"); | |
| 56 | + } | |
| 57 | + } | |
| 58 | + | |
| 59 | + /** | |
| 60 | + * Validates that a prepared statement with no variables is correctly prepared and executed. | |
| 61 | + * @jira_ticket JAVA-1132 | |
| 62 | + */ | |
| 63 | + @Test(groups = "short") | |
| 64 | + public void should_execute_prepared_statement_with_no_variables() throws Exception { | |
| 65 | + PreparedStatement ps = session().prepare("select * from system.local"); | |
| 66 | + session().execute(ps.bind()); | |
| 67 | + } | |
| 68 | + | |
| 69 | + /** | |
| 70 | + * Validates that a prepared statement with variables is correctly prepared and executed. | |
| 71 | + * @jira_ticket JAVA-1132 | |
| 72 | + */ | |
| 73 | + @Test(groups = "short") | |
| 74 | + public void should_execute_prepared_statement_with_variables() throws Exception { | |
| 75 | + PreparedStatement ps = session().prepare("select * from system.local where key=?"); | |
| 76 | + session().execute(ps.bind("local")); | |
| 77 | + } | |
| 78 | + | |
| 79 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +3 −3
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | import com.datastax.driver.core.exceptions.*; |
| 19 | 19 | import org.apache.log4j.Level; |
| 20 | 20 | import org.apache.log4j.Logger; |
| 21 | -import org.scassandra.http.client.PrimingRequest; | |
| 21 | +import org.scassandra.http.client.Result; | |
| 22 | 22 | import org.testng.annotations.AfterMethod; |
| 23 | 23 | import org.testng.annotations.BeforeMethod; |
| 24 | 24 | import org.testng.annotations.DataProvider; |
| @@ -29,9 +29,9 @@ | ||
| 29 | 29 | import static org.apache.log4j.Level.INFO; |
| 30 | 30 | import static org.assertj.core.api.Assertions.assertThat; |
| 31 | 31 | import static org.assertj.core.api.Assertions.fail; |
| 32 | -import static org.scassandra.http.client.PrimingRequest.Result.*; | |
| 33 | 32 | import static org.scassandra.http.client.PrimingRequest.queryBuilder; |
| 34 | 33 | import static org.scassandra.http.client.PrimingRequest.then; |
| 34 | +import static org.scassandra.http.client.Result.*; | |
| 35 | 35 | |
| 36 | 36 | /** |
| 37 | 37 | * Tests for {@link QueryLogger} using Scassandra. |
| @@ -158,7 +158,7 @@ | ||
| 158 | 158 | } |
| 159 | 159 | |
| 160 | 160 | @Test(groups = "short", dataProvider = "errors") |
| 161 | - public void should_log_exception_from_the_given_result(PrimingRequest.Result result, Class<? extends Exception> expectedException, Class<? extends Exception> loggedException) throws Exception { | |
| 161 | + public void should_log_exception_from_the_given_result(Result result, Class<? extends Exception> expectedException, Class<? extends Exception> loggedException) throws Exception { | |
| 162 | 162 | // given |
| 163 | 163 | error.setLevel(DEBUG); |
| 164 | 164 | queryLogger = builder().build(); |
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +331 −13
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import com.datastax.driver.core.StatementWrapperTest.CustomStatement; | |
| 18 | 19 | import com.datastax.driver.core.exceptions.DriverException; |
| 19 | 20 | import com.datastax.driver.core.utils.CassandraVersion; |
| 20 | 21 | import com.google.common.base.Function; |
| @@ -30,8 +31,7 @@ | ||
| 30 | 31 | import org.testng.annotations.Test; |
| 31 | 32 | |
| 32 | 33 | import java.nio.ByteBuffer; |
| 33 | -import java.util.ArrayList; | |
| 34 | -import java.util.List; | |
| 34 | +import java.util.*; | |
| 35 | 35 | |
| 36 | 36 | import static com.datastax.driver.core.BatchStatement.Type.COUNTER; |
| 37 | 37 | import static com.datastax.driver.core.BatchStatement.Type.UNLOGGED; |
| @@ -377,7 +377,7 @@ | ||
| 377 | 377 | |
| 378 | 378 | @Test(groups = "short") |
| 379 | 379 | @CassandraVersion(major = 2.0) |
| 380 | - public void should_log_non_null_named_parameter() throws Exception { | |
| 380 | + public void should_log_non_null_named_parameter_bound_statements() throws Exception { | |
| 381 | 381 | // given |
| 382 | 382 | normal.setLevel(TRACE); |
| 383 | 383 | queryLogger = QueryLogger.builder() |
| @@ -403,7 +403,7 @@ | ||
| 403 | 403 | } |
| 404 | 404 | |
| 405 | 405 | @Test(groups = "short") |
| 406 | - public void should_log_non_null_positional_parameter() throws Exception { | |
| 406 | + public void should_log_non_null_positional_parameter_bound_statements() throws Exception { | |
| 407 | 407 | // given |
| 408 | 408 | normal.setLevel(TRACE); |
| 409 | 409 | queryLogger = QueryLogger.builder().build(); |
| @@ -426,7 +426,28 @@ | ||
| 426 | 426 | } |
| 427 | 427 | |
| 428 | 428 | @Test(groups = "short") |
| 429 | - public void should_log_null_parameter() throws Exception { | |
| 429 | + @CassandraVersion(major = 2.0) | |
| 430 | + public void should_log_non_null_positional_parameter_simple_statements() throws Exception { | |
| 431 | + // given | |
| 432 | + normal.setLevel(TRACE); | |
| 433 | + queryLogger = QueryLogger.builder().build(); | |
| 434 | + cluster().register(queryLogger); | |
| 435 | + // when | |
| 436 | + String query = "UPDATE test SET c_text = ? WHERE pk = ?"; | |
| 437 | + SimpleStatement ss = new SimpleStatement(query, "foo", 42); | |
| 438 | + session().execute(ss); | |
| 439 | + // then | |
| 440 | + String line = normalAppender.waitAndGet(10000); | |
| 441 | + assertThat(line) | |
| 442 | + .contains("Query completed normally") | |
| 443 | + .contains(ipOfNode(1)) | |
| 444 | + .contains(query) | |
| 445 | + .contains("42") | |
| 446 | + .contains("'foo'"); | |
| 447 | + } | |
| 448 | + | |
| 449 | + @Test(groups = "short") | |
| 450 | + public void should_log_null_parameter_bound_statements() throws Exception { | |
| 430 | 451 | // given |
| 431 | 452 | normal.setLevel(TRACE); |
| 432 | 453 | queryLogger = QueryLogger.builder().build(); |
| @@ -448,6 +469,27 @@ | ||
| 448 | 469 | .contains("c_text:NULL"); |
| 449 | 470 | } |
| 450 | 471 | |
| 472 | + @Test(groups = "short") | |
| 473 | + @CassandraVersion(major = 2.0) | |
| 474 | + public void should_log_null_parameter_simple_statements() throws Exception { | |
| 475 | + // given | |
| 476 | + normal.setLevel(TRACE); | |
| 477 | + queryLogger = QueryLogger.builder().build(); | |
| 478 | + cluster().register(queryLogger); | |
| 479 | + // when | |
| 480 | + String query = "UPDATE test SET c_text = ? WHERE pk = ?"; | |
| 481 | + SimpleStatement ss = new SimpleStatement(query, null, 42); | |
| 482 | + session().execute(ss); | |
| 483 | + // then | |
| 484 | + String line = normalAppender.waitAndGet(10000); | |
| 485 | + assertThat(line) | |
| 486 | + .contains("Query completed normally") | |
| 487 | + .contains(ipOfNode(1)) | |
| 488 | + .contains(query) | |
| 489 | + .contains("42") | |
| 490 | + .contains("NULL"); | |
| 491 | + } | |
| 492 | + | |
| 451 | 493 | @Test(groups = "short") |
| 452 | 494 | @CassandraVersion(major = 3.0) |
| 453 | 495 | public void should_log_unset_parameter() throws Exception { |
| @@ -497,10 +539,38 @@ | ||
| 497 | 539 | .contains("c_text:'foo'") |
| 498 | 540 | .contains("c_int:12345"); |
| 499 | 541 | } |
| 542 | + | |
| 543 | + @Test(groups = "short") | |
| 544 | + @CassandraVersion(major = 2.0) | |
| 545 | + public void should_log_simple_statement_parameters_inside_batch_statement() throws Exception { | |
| 546 | + // given | |
| 547 | + normal.setLevel(TRACE); | |
| 548 | + queryLogger = QueryLogger.builder().build(); | |
| 549 | + cluster().register(queryLogger); | |
| 550 | + // when | |
| 551 | + String query1 = "UPDATE test SET c_text = ? WHERE pk = ?"; | |
| 552 | + String query2 = "UPDATE test SET c_int = ? WHERE pk = ?"; | |
| 553 | + BatchStatement batch = new BatchStatement(); | |
| 554 | + batch.add(new SimpleStatement(query1, "foo", 42)); | |
| 555 | + batch.add(new SimpleStatement(query2, 12345, 43)); | |
| 556 | + session().execute(batch); | |
| 557 | + // then | |
| 558 | + String line = normalAppender.waitAndGet(10000); | |
| 559 | + assertThat(line) | |
| 560 | + .contains("Query completed normally") | |
| 561 | + .contains(ipOfNode(1)) | |
| 562 | + .contains(query1) | |
| 563 | + .contains(query2) | |
| 564 | + .contains("42") | |
| 565 | + .contains("43") | |
| 566 | + .contains("'foo'") | |
| 567 | + .contains("12345"); | |
| 568 | + } | |
| 569 | + | |
| 500 | 570 | // Test different CQL types |
| 501 | 571 | |
| 502 | 572 | @Test(groups = "short") |
| 503 | - public void should_log_all_parameter_types() throws Exception { | |
| 573 | + public void should_log_all_parameter_types_bound_statements() throws Exception { | |
| 504 | 574 | // given |
| 505 | 575 | normal.setLevel(TRACE); |
| 506 | 576 | queryLogger = QueryLogger.builder() |
| @@ -525,6 +595,37 @@ | ||
| 525 | 595 | } |
| 526 | 596 | } |
| 527 | 597 | |
| 598 | + @Test(groups = "short") | |
| 599 | + @CassandraVersion(major = 2.0) | |
| 600 | + public void should_log_all_parameter_types_simple_statements() throws Exception { | |
| 601 | + // given | |
| 602 | + normal.setLevel(TRACE); | |
| 603 | + queryLogger = QueryLogger.builder() | |
| 604 | + .withMaxParameterValueLength(Integer.MAX_VALUE) | |
| 605 | + .build(); | |
| 606 | + cluster().register(queryLogger); | |
| 607 | + // when | |
| 608 | + String query = "UPDATE test SET " + assignments + " WHERE pk = 42"; | |
| 609 | + SimpleStatement ss = new SimpleStatement(query, values.toArray()); | |
| 610 | + session().execute(ss); | |
| 611 | + // then | |
| 612 | + String line = normalAppender.waitAndGet(10000); | |
| 613 | + assertThat(line) | |
| 614 | + .contains("Query completed normally") | |
| 615 | + .contains(ipOfNode(1)) | |
| 616 | + .contains(query); | |
| 617 | + CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry(); | |
| 618 | + for (DataType type : dataTypes) { | |
| 619 | + TypeCodec<Object> codec; | |
| 620 | + if (type.equals(DataType.time())) { | |
| 621 | + codec = codecRegistry.codecFor(DataType.bigint()); | |
| 622 | + } else { | |
| 623 | + codec = codecRegistry.codecFor(type); | |
| 624 | + } | |
| 625 | + assertThat(line).contains(codec.format(getFixedValue(type))); | |
| 626 | + } | |
| 627 | + } | |
| 628 | + | |
| 528 | 629 | // Tests for truncation of query strings and parameter values |
| 529 | 630 | |
| 530 | 631 | @Test(groups = "short") |
| @@ -596,7 +697,7 @@ | ||
| 596 | 697 | |
| 597 | 698 | @CassandraVersion(major = 2.0) |
| 598 | 699 | @Test(groups = "short") |
| 599 | - public void should_truncate_parameter_when_max_length_exceeded() throws Exception { | |
| 700 | + public void should_truncate_parameter_when_max_length_exceeded_bound_statements() throws Exception { | |
| 600 | 701 | // given |
| 601 | 702 | normal.setLevel(TRACE); |
| 602 | 703 | queryLogger = QueryLogger.builder() |
| @@ -619,8 +720,30 @@ | ||
| 619 | 720 | .doesNotContain("123456"); |
| 620 | 721 | } |
| 621 | 722 | |
| 723 | + @CassandraVersion(major = 2.0) | |
| 724 | + @Test(groups = "short") | |
| 725 | + public void should_truncate_parameter_when_max_length_exceeded_simple_statements() throws Exception { | |
| 726 | + // given | |
| 727 | + normal.setLevel(TRACE); | |
| 728 | + queryLogger = QueryLogger.builder() | |
| 729 | + .withMaxParameterValueLength(5) | |
| 730 | + .build(); | |
| 731 | + cluster().register(queryLogger); | |
| 732 | + // when | |
| 733 | + String query = "UPDATE test SET c_int = ? WHERE pk = ?"; | |
| 734 | + SimpleStatement ss = new SimpleStatement(query, 123456, 42); | |
| 735 | + session().execute(ss); | |
| 736 | + // then | |
| 737 | + String line = normalAppender.waitAndGet(10000); | |
| 738 | + assertThat(line) | |
| 739 | + .contains("Query completed normally") | |
| 740 | + .contains(ipOfNode(1)) | |
| 741 | + .contains("12345" + TRUNCATED_OUTPUT) | |
| 742 | + .doesNotContain("123456"); | |
| 743 | + } | |
| 744 | + | |
| 622 | 745 | @Test(groups = "short") |
| 623 | - public void should_truncate_blob_parameter_when_max_length_exceeded() throws Exception { | |
| 746 | + public void should_truncate_blob_parameter_when_max_length_exceeded_bound_statements() throws Exception { | |
| 624 | 747 | // given |
| 625 | 748 | normal.setLevel(TRACE); |
| 626 | 749 | queryLogger = QueryLogger.builder() |
| @@ -640,11 +763,33 @@ | ||
| 640 | 763 | .contains("Query completed normally") |
| 641 | 764 | .contains(ipOfNode(1)) |
| 642 | 765 | .contains("c_blob:0x0102" + TRUNCATED_OUTPUT) |
| 643 | - .doesNotContain("123456"); | |
| 766 | + .doesNotContain("0x010203"); | |
| 767 | + } | |
| 768 | + | |
| 769 | + @Test(groups = "short") | |
| 770 | + @CassandraVersion(major = 2.0) | |
| 771 | + public void should_truncate_blob_parameter_when_max_length_exceeded_simple_statements() throws Exception { | |
| 772 | + // given | |
| 773 | + normal.setLevel(TRACE); | |
| 774 | + queryLogger = QueryLogger.builder() | |
| 775 | + .withMaxParameterValueLength(6) | |
| 776 | + .build(); | |
| 777 | + cluster().register(queryLogger); | |
| 778 | + // when | |
| 779 | + String query = "UPDATE test SET c_blob = ? WHERE pk = ?"; | |
| 780 | + SimpleStatement ss = new SimpleStatement(query, ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1, 2, 3))), 42); | |
| 781 | + session().execute(ss); | |
| 782 | + // then | |
| 783 | + String line = normalAppender.waitAndGet(10000); | |
| 784 | + assertThat(line) | |
| 785 | + .contains("Query completed normally") | |
| 786 | + .contains(ipOfNode(1)) | |
| 787 | + .contains("0x0102" + TRUNCATED_OUTPUT) | |
| 788 | + .doesNotContain("0x010203"); | |
| 644 | 789 | } |
| 645 | 790 | |
| 646 | 791 | @Test(groups = "short") |
| 647 | - public void should_not_truncate_parameter_when_max_length_unlimited() throws Exception { | |
| 792 | + public void should_not_truncate_parameter_when_max_length_unlimited_bound_statements() throws Exception { | |
| 648 | 793 | // given |
| 649 | 794 | normal.setLevel(TRACE); |
| 650 | 795 | queryLogger = QueryLogger.builder() |
| @@ -668,7 +813,29 @@ | ||
| 668 | 813 | } |
| 669 | 814 | |
| 670 | 815 | @Test(groups = "short") |
| 671 | - public void should_not_log_exceeding_number_of_parameters() throws Exception { | |
| 816 | + @CassandraVersion(major = 2.0) | |
| 817 | + public void should_not_truncate_parameter_when_max_length_unlimited_simple_statements() throws Exception { | |
| 818 | + // given | |
| 819 | + normal.setLevel(TRACE); | |
| 820 | + queryLogger = QueryLogger.builder() | |
| 821 | + .withMaxParameterValueLength(-1) | |
| 822 | + .build(); | |
| 823 | + cluster().register(queryLogger); | |
| 824 | + // when | |
| 825 | + String query = "UPDATE test SET c_int = ? WHERE pk = ?"; | |
| 826 | + SimpleStatement ss = new SimpleStatement(query, 123456, 42); | |
| 827 | + session().execute(ss); | |
| 828 | + // then | |
| 829 | + String line = normalAppender.waitAndGet(10000); | |
| 830 | + assertThat(line) | |
| 831 | + .contains("Query completed normally") | |
| 832 | + .contains(ipOfNode(1)) | |
| 833 | + .contains("123456") | |
| 834 | + .doesNotContain(TRUNCATED_OUTPUT); | |
| 835 | + } | |
| 836 | + | |
| 837 | + @Test(groups = "short") | |
| 838 | + public void should_not_log_exceeding_number_of_parameters_bound_statements() throws Exception { | |
| 672 | 839 | // given |
| 673 | 840 | normal.setLevel(TRACE); |
| 674 | 841 | queryLogger = QueryLogger.builder() |
| @@ -694,7 +861,56 @@ | ||
| 694 | 861 | |
| 695 | 862 | @Test(groups = "short") |
| 696 | 863 | @CassandraVersion(major = 2.0) |
| 697 | - public void should_not_log_exceeding_number_of_parameters_in_batch_statement() throws Exception { | |
| 864 | + public void should_not_log_exceeding_number_of_parameters_simple_statements() throws Exception { | |
| 865 | + // given | |
| 866 | + normal.setLevel(TRACE); | |
| 867 | + queryLogger = QueryLogger.builder() | |
| 868 | + .withMaxLoggedParameters(1) | |
| 869 | + .build(); | |
| 870 | + cluster().register(queryLogger); | |
| 871 | + // when | |
| 872 | + String query = "UPDATE test SET c_int = ? WHERE pk = ?"; | |
| 873 | + SimpleStatement ss = new SimpleStatement(query, 123456, 42); | |
| 874 | + session().execute(ss); | |
| 875 | + // then | |
| 876 | + String line = normalAppender.waitAndGet(10000); | |
| 877 | + assertThat(line) | |
| 878 | + .contains("Query completed normally") | |
| 879 | + .contains(ipOfNode(1)) | |
| 880 | + .contains("123456") | |
| 881 | + .doesNotContain("123456, 42") | |
| 882 | + .contains(FURTHER_PARAMS_OMITTED); | |
| 883 | + } | |
| 884 | + | |
| 885 | + @Test(groups = "short") | |
| 886 | + @CassandraVersion(major = 2.1) | |
| 887 | + public void should_not_log_exceeding_number_of_parameters_simple_statements_with_named_values() throws Exception { | |
| 888 | + // given | |
| 889 | + normal.setLevel(TRACE); | |
| 890 | + queryLogger = QueryLogger.builder() | |
| 891 | + .withMaxLoggedParameters(1) | |
| 892 | + .build(); | |
| 893 | + cluster().register(queryLogger); | |
| 894 | + // when | |
| 895 | + String query = "UPDATE test SET c_int = :c_int WHERE pk = :pk"; | |
| 896 | + Map<String, Object> namedValues = new LinkedHashMap<String, Object>(); | |
| 897 | + namedValues.put("c_int", 123456); | |
| 898 | + namedValues.put("pk", 42); | |
| 899 | + SimpleStatement ss = new SimpleStatement(query, namedValues); | |
| 900 | + session().execute(ss); | |
| 901 | + // then | |
| 902 | + String line = normalAppender.waitAndGet(10000); | |
| 903 | + assertThat(line) | |
| 904 | + .contains("Query completed normally") | |
| 905 | + .contains(ipOfNode(1)) | |
| 906 | + .contains("c_int:123456") | |
| 907 | + .doesNotContain("pk:42") | |
| 908 | + .contains(FURTHER_PARAMS_OMITTED); | |
| 909 | + } | |
| 910 | + | |
| 911 | + @Test(groups = "short") | |
| 912 | + @CassandraVersion(major = 2.0) | |
| 913 | + public void should_not_log_exceeding_number_of_parameters_in_batch_statement_bound_statements() throws Exception { | |
| 698 | 914 | // given |
| 699 | 915 | normal.setLevel(TRACE); |
| 700 | 916 | queryLogger = QueryLogger.builder() |
| @@ -723,7 +939,35 @@ | ||
| 723 | 939 | } |
| 724 | 940 | |
| 725 | 941 | @Test(groups = "short") |
| 726 | - public void should_log_all_parameters_when_max_unlimited() throws Exception { | |
| 942 | + @CassandraVersion(major = 2.0) | |
| 943 | + public void should_not_log_exceeding_number_of_parameters_in_batch_statement_simple_statements() throws Exception { | |
| 944 | + // given | |
| 945 | + normal.setLevel(TRACE); | |
| 946 | + queryLogger = QueryLogger.builder() | |
| 947 | + .withMaxLoggedParameters(1) | |
| 948 | + .build(); | |
| 949 | + cluster().register(queryLogger); | |
| 950 | + // when | |
| 951 | + String query1 = "UPDATE test SET c_text = ? WHERE pk = ?"; | |
| 952 | + String query2 = "UPDATE test SET c_int = ? WHERE pk = ?"; | |
| 953 | + BatchStatement batch = new BatchStatement(); | |
| 954 | + batch.add(new SimpleStatement(query1, "foo", 42)); | |
| 955 | + batch.add(new SimpleStatement(query2, 12345, 43)); | |
| 956 | + session().execute(batch); | |
| 957 | + // then | |
| 958 | + String line = normalAppender.waitAndGet(10000); | |
| 959 | + assertThat(line) | |
| 960 | + .contains("Query completed normally") | |
| 961 | + .contains(ipOfNode(1)) | |
| 962 | + .contains(query1) | |
| 963 | + .contains(query2) | |
| 964 | + .contains("'foo'") | |
| 965 | + .doesNotContain("42, 12345, 43") | |
| 966 | + .contains(FURTHER_PARAMS_OMITTED); | |
| 967 | + } | |
| 968 | + | |
| 969 | + @Test(groups = "short") | |
| 970 | + public void should_log_all_parameters_when_max_unlimited_bound_statements() throws Exception { | |
| 727 | 971 | // given |
| 728 | 972 | normal.setLevel(TRACE); |
| 729 | 973 | queryLogger = QueryLogger.builder() |
| @@ -746,6 +990,80 @@ | ||
| 746 | 990 | .contains("pk:42"); |
| 747 | 991 | } |
| 748 | 992 | |
| 993 | + @Test(groups = "short") | |
| 994 | + @CassandraVersion(major = 2.0) | |
| 995 | + public void should_log_all_parameters_when_max_unlimited_simple_statements() throws Exception { | |
| 996 | + // given | |
| 997 | + normal.setLevel(TRACE); | |
| 998 | + queryLogger = QueryLogger.builder() | |
| 999 | + .withMaxLoggedParameters(-1) | |
| 1000 | + .build(); | |
| 1001 | + cluster().register(queryLogger); | |
| 1002 | + // when | |
| 1003 | + String query = "UPDATE test SET c_int = ? WHERE pk = ?"; | |
| 1004 | + SimpleStatement ss = new SimpleStatement(query, 123456, 42); | |
| 1005 | + session().execute(ss); | |
| 1006 | + // then | |
| 1007 | + String line = normalAppender.waitAndGet(10000); | |
| 1008 | + assertThat(line) | |
| 1009 | + .contains("Query completed normally") | |
| 1010 | + .contains(ipOfNode(1)) | |
| 1011 | + .contains("123456") | |
| 1012 | + .contains("42"); | |
| 1013 | + } | |
| 1014 | + | |
| 1015 | + @Test(groups = "short") | |
| 1016 | + @CassandraVersion(major = 2.1) | |
| 1017 | + public void should_log_all_parameters_when_max_unlimited_simple_statements_with_named_values() throws Exception { | |
| 1018 | + // given | |
| 1019 | + normal.setLevel(TRACE); | |
| 1020 | + queryLogger = QueryLogger.builder() | |
| 1021 | + .withMaxLoggedParameters(-1) | |
| 1022 | + .build(); | |
| 1023 | + cluster().register(queryLogger); | |
| 1024 | + // when | |
| 1025 | + String query = "UPDATE test SET c_int = :c_int WHERE pk = :pk"; | |
| 1026 | + Map<String, Object> namedValues = new HashMap<String, Object>(); | |
| 1027 | + namedValues.put("c_int", 123456); | |
| 1028 | + namedValues.put("pk", 42); | |
| 1029 | + SimpleStatement ss = new SimpleStatement(query, namedValues); | |
| 1030 | + session().execute(ss); | |
| 1031 | + // then | |
| 1032 | + String line = normalAppender.waitAndGet(10000); | |
| 1033 | + assertThat(line) | |
| 1034 | + .contains("Query completed normally") | |
| 1035 | + .contains(ipOfNode(1)) | |
| 1036 | + .contains("123456") | |
| 1037 | + .contains("42"); | |
| 1038 | + } | |
| 1039 | + | |
| 1040 | + @CassandraVersion(major = 2.0) | |
| 1041 | + @Test(groups = "short") | |
| 1042 | + public void should_log_wrapped_bound_statement() throws Exception { | |
| 1043 | + // given | |
| 1044 | + normal.setLevel(TRACE); | |
| 1045 | + queryLogger = QueryLogger.builder() | |
| 1046 | + .withConstantThreshold(Long.MAX_VALUE) | |
| 1047 | + .withMaxQueryStringLength(Integer.MAX_VALUE) | |
| 1048 | + .build(); | |
| 1049 | + cluster().register(queryLogger); | |
| 1050 | + // when | |
| 1051 | + String query = "UPDATE test SET c_text = :param1 WHERE pk = :param2"; | |
| 1052 | + PreparedStatement ps = session().prepare(query); | |
| 1053 | + BoundStatement bs = ps.bind(); | |
| 1054 | + bs.setString("param1", "foo"); | |
| 1055 | + bs.setInt("param2", 42); | |
| 1056 | + session().execute(new CustomStatement(bs)); | |
| 1057 | + // then | |
| 1058 | + String line = normalAppender.waitAndGet(10000); | |
| 1059 | + assertThat(line) | |
| 1060 | + .contains("Query completed normally") | |
| 1061 | + .contains(ipOfNode(1)) | |
| 1062 | + .contains(query) | |
| 1063 | + .contains("param2:42") | |
| 1064 | + .contains("param1:'foo'"); | |
| 1065 | + } | |
| 1066 | + | |
| 749 | 1067 | @Override |
| 750 | 1068 | public void onTestContextInitialized() { |
| 751 | 1069 | execute("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")"); |
modified driver-core/src/test/java/com/datastax/driver/core/ReadTimeoutTest.java +6 −0
| @@ -58,4 +58,10 @@ | ||
| 58 | 58 | Statement statement = new SimpleStatement(query).setReadTimeoutMillis(200); |
| 59 | 59 | session.execute(statement); |
| 60 | 60 | } |
| 61 | + | |
| 62 | + @Test(groups = "short") | |
| 63 | + public void should_disable_timeout_if_set_to_zero_at_statement_level() { | |
| 64 | + Statement statement = new SimpleStatement(query).setReadTimeoutMillis(0); | |
| 65 | + session.execute(statement); | |
| 66 | + } | |
| 61 | 67 | } |
added driver-core/src/test/java/com/datastax/driver/core/ReusedStreamIdTest.java +154 −0
| @@ -0,0 +1,154 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 19 | +import com.google.common.util.concurrent.FutureCallback; | |
| 20 | +import com.google.common.util.concurrent.Futures; | |
| 21 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 22 | +import org.slf4j.Logger; | |
| 23 | +import org.slf4j.LoggerFactory; | |
| 24 | +import org.testng.annotations.Test; | |
| 25 | + | |
| 26 | +import java.util.List; | |
| 27 | +import java.util.Random; | |
| 28 | +import java.util.concurrent.CountDownLatch; | |
| 29 | +import java.util.concurrent.Semaphore; | |
| 30 | +import java.util.concurrent.TimeUnit; | |
| 31 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 32 | + | |
| 33 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 34 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 35 | +import static org.testng.Assert.fail; | |
| 36 | + | |
| 37 | +@CreateCCM(PER_METHOD) | |
| 38 | +public class ReusedStreamIdTest extends CCMTestsSupport { | |
| 39 | + | |
| 40 | + static Logger logger = LoggerFactory.getLogger(ReusedStreamIdTest.class); | |
| 41 | + | |
| 42 | + @SuppressWarnings("unused") | |
| 43 | + public Cluster.Builder createClusterLowReadTimeout() { | |
| 44 | + // Low Read Timeout to trigger retry behavior. | |
| 45 | + return Cluster.builder().withSocketOptions(new SocketOptions().setReadTimeoutMillis(1000)); | |
| 46 | + } | |
| 47 | + | |
| 48 | + /** | |
| 49 | + * Ensures that if activity tied to future completion blocks netty io threads that this does not cause the | |
| 50 | + * driver to possibly invoke the wrong handler for a response, as described in JAVA-1179. | |
| 51 | + * <p/> | |
| 52 | + * This is accomplished by setting up a 2 node cluster and setting a low read timeout (1 second). The test | |
| 53 | + * submits 10 concurrent requests repeatedly for up to 500 queries and on completion of each request may block | |
| 54 | + * in a callback randomly (25% of the time) for 1 second, causing a retry on the next host to trigger. If a new | |
| 55 | + * stream id is not allocated on the retry, its possible it could use an already used stream id and cause the driver | |
| 56 | + * to invoke the wrong handlers for a response. The test checks for this by ensuring that the column returned in a | |
| 57 | + * response matches the one queried. If the column received does not match, the test fails. In cases where this | |
| 58 | + * bug is present, it should be detected within 10 seconds. | |
| 59 | + * | |
| 60 | + * @jira_ticket JAVA-1179 | |
| 61 | + * @test_category queries:async_callback | |
| 62 | + */ | |
| 63 | + @Test(groups = "long") | |
| 64 | + @CCMConfig(numberOfNodes = 2, clusterProvider = "createClusterLowReadTimeout") | |
| 65 | + public void should_not_receive_wrong_response_when_callbacks_block_io_thread() { | |
| 66 | + int concurrency = 10; | |
| 67 | + final Semaphore semaphore = new Semaphore(concurrency); | |
| 68 | + // RNG to determine sleep times. | |
| 69 | + final Random random = new Random(); | |
| 70 | + | |
| 71 | + try { | |
| 72 | + // Use the system.local table and alternate between columns that are queried. | |
| 73 | + List<ColumnMetadata> columnsToGrab = cluster().getMetadata().getKeyspace("system").getTable("local").getColumns(); | |
| 74 | + assertThat(columnsToGrab.size()).isGreaterThan(1); | |
| 75 | + | |
| 76 | + final CountDownLatch errorTrigger = new CountDownLatch(1); | |
| 77 | + | |
| 78 | + long start = System.currentTimeMillis(); | |
| 79 | + // 500 iterations will take roughly 1 minute. | |
| 80 | + int iterations = 500; | |
| 81 | + final AtomicInteger completed = new AtomicInteger(0); | |
| 82 | + | |
| 83 | + for (int i = 1; i <= iterations; i++) { | |
| 84 | + try { | |
| 85 | + if (errorTrigger.getCount() == 0) { | |
| 86 | + fail(String.format("Error triggered at or before %d of %d requests after %dms.", i, iterations, | |
| 87 | + System.currentTimeMillis() - start)); | |
| 88 | + } | |
| 89 | + semaphore.acquire(); | |
| 90 | + final String column = columnsToGrab.get(i % columnsToGrab.size()).getName(); | |
| 91 | + String query = String.format("select %s from system.local", column); | |
| 92 | + ResultSetFuture future = session().executeAsync(query); | |
| 93 | + | |
| 94 | + Futures.addCallback(future, new FutureCallback<ResultSet>() { | |
| 95 | + @Override | |
| 96 | + public void onSuccess(ResultSet result) { | |
| 97 | + semaphore.release(); | |
| 98 | + // Expect the column that you queried to be present, if its not we got the wrong response | |
| 99 | + // back. | |
| 100 | + int columnIndex = result.getColumnDefinitions().getIndexOf(column); | |
| 101 | + if (columnIndex == -1) { | |
| 102 | + logger.error("Got response without column {}, got columns {} from Host {}.", column, | |
| 103 | + result.getColumnDefinitions(), result.getExecutionInfo().getQueriedHost()); | |
| 104 | + errorTrigger.countDown(); | |
| 105 | + return; | |
| 106 | + } | |
| 107 | + completed.incrementAndGet(); | |
| 108 | + // Block netty io thread 25% of the time. | |
| 109 | + int num = random.nextInt(1); | |
| 110 | + if (num == 0) { | |
| 111 | + // Sleep exactly one second, should trigger retry. | |
| 112 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); | |
| 113 | + } | |
| 114 | + } | |
| 115 | + | |
| 116 | + @Override | |
| 117 | + public void onFailure(Throwable t) { | |
| 118 | + semaphore.release(); | |
| 119 | + // NHAEs are inevitable because of low query timeouts and blocked threads. | |
| 120 | + if (!(t instanceof NoHostAvailableException)) { | |
| 121 | + logger.error("Unexpected error encountered.", t); | |
| 122 | + errorTrigger.countDown(); | |
| 123 | + } | |
| 124 | + } | |
| 125 | + }); | |
| 126 | + } catch (InterruptedException e) { | |
| 127 | + fail("Test interrupted", e); | |
| 128 | + } | |
| 129 | + if (i % (iterations / 10) == 0) { | |
| 130 | + logger.info("Submitted {} of {} requests. ({} completed successfully)", i, iterations, completed.get()); | |
| 131 | + } | |
| 132 | + } | |
| 133 | + | |
| 134 | + // Wait for 10 seconds for any remaining requests to possibly trigger an error, its likely | |
| 135 | + // that if we get to this point this will not happen. | |
| 136 | + Uninterruptibles.awaitUninterruptibly(errorTrigger, 10, TimeUnit.SECONDS); | |
| 137 | + if (errorTrigger.getCount() == 0) { | |
| 138 | + fail(String.format("Error triggered after %dms.", System.currentTimeMillis() - start)); | |
| 139 | + } | |
| 140 | + // Sanity check to ensure that at least some requests succeeded, we expect some failures if both | |
| 141 | + // hosts timeout as its likely they could be blocked on the event loop. | |
| 142 | + assertThat(completed.get()).isGreaterThan(0); | |
| 143 | + } finally { | |
| 144 | + try { | |
| 145 | + // Acquire all permits to make sure all inflight requests complete. | |
| 146 | + if (!semaphore.tryAcquire(concurrency, 10, TimeUnit.SECONDS)) { | |
| 147 | + fail("Could not acquire all permits within 10 seconds of completion."); | |
| 148 | + } | |
| 149 | + } catch (InterruptedException e) { | |
| 150 | + fail("Interrupted.", e); | |
| 151 | + } | |
| 152 | + } | |
| 153 | + } | |
| 154 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +56 −41
| @@ -15,11 +15,8 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import com.beust.jcommander.internal.Lists; | |
| 19 | -import com.beust.jcommander.internal.Maps; | |
| 20 | -import com.google.common.collect.ImmutableList; | |
| 21 | -import com.google.common.collect.ImmutableMap; | |
| 22 | -import com.google.common.collect.ImmutableSet; | |
| 18 | +import com.datastax.driver.core.utils.UUIDs; | |
| 19 | +import com.google.common.collect.*; | |
| 23 | 20 | import org.scassandra.Scassandra; |
| 24 | 21 | import org.scassandra.ScassandraFactory; |
| 25 | 22 | import org.scassandra.http.client.PrimingClient; |
| @@ -55,6 +52,8 @@ | ||
| 55 | 52 | |
| 56 | 53 | private final List<Map<String, ?>> keyspaceRows; |
| 57 | 54 | |
| 55 | + private static final java.util.UUID schemaVersion = UUIDs.random(); | |
| 56 | + | |
| 58 | 57 | |
| 59 | 58 | private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos; |
| 60 | 59 | |
| @@ -263,7 +262,7 @@ | ||
| 263 | 262 | // Offset DCs by dc * 100 to ensure unique tokens. |
| 264 | 263 | int offset = (dc - 1) * 100; |
| 265 | 264 | int dcNodeCount = nodes(dc).size(); |
| 266 | - List<Long> tokens = Lists.newArrayList(dcNodeCount); | |
| 265 | + List<Long> tokens = Lists.newArrayListWithExpectedSize(dcNodeCount); | |
| 267 | 266 | for (int i = 0; i < dcNodeCount; i++) { |
| 268 | 267 | tokens.add((i * ((long) Math.pow(2, 64) / dcNodeCount) + offset)); |
| 269 | 268 | } |
| @@ -287,42 +286,45 @@ | ||
| 287 | 286 | if (node == peer) { // prime system.local. |
| 288 | 287 | metadata = SELECT_LOCAL; |
| 289 | 288 | query = "SELECT * FROM system.local WHERE key='local'"; |
| 290 | - ImmutableMap.Builder<String, Object> rowBuilder = ImmutableMap.<String, Object>builder() | |
| 291 | - .put("key", "local") | |
| 292 | - .put("bootstrapped", "COMPLETED") | |
| 293 | - .put("broadcast_address", address) | |
| 294 | - .put("cluster_name", "scassandra") | |
| 295 | - .put("cql_version", "3.2.0") | |
| 296 | - .put("data_center", datacenter(dc)) | |
| 297 | - .put("listen_address", getPeerInfo(dc, n + 1, "listen_address", address)) | |
| 298 | - .put("partitioner", "org.apache.cassandra.dht.Murmur3Partitioner") | |
| 299 | - .put("rack", "rack1") | |
| 300 | - .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8")) | |
| 301 | - .put("tokens", ImmutableSet.of(tokens.get(n))); | |
| 289 | + | |
| 290 | + row = Maps.newHashMap(); | |
| 291 | + addPeerInfo(row, dc, n + 1, "key", "local"); | |
| 292 | + addPeerInfo(row, dc, n + 1, "bootstrapped", "COMPLETED"); | |
| 293 | + addPeerInfo(row, dc, n + 1, "broadcast_address", address); | |
| 294 | + addPeerInfo(row, dc, n + 1, "cluster_name", "scassandra"); | |
| 295 | + addPeerInfo(row, dc, n + 1, "cql_version", "3.2.0"); | |
| 296 | + addPeerInfo(row, dc, n + 1, "data_center", datacenter(dc)); | |
| 297 | + addPeerInfo(row, dc, n + 1, "listen_address", getPeerInfo(dc, n + 1, "listen_address", address)); | |
| 298 | + addPeerInfo(row, dc, n + 1, "partitioner", "org.apache.cassandra.dht.Murmur3Partitioner"); | |
| 299 | + addPeerInfo(row, dc, n + 1, "rack", getPeerInfo(dc, n + 1, "rack", "rack1")); | |
| 300 | + addPeerInfo(row, dc, n + 1, "release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8")); | |
| 301 | + addPeerInfo(row, dc, n + 1, "tokens", ImmutableSet.of(tokens.get(n))); | |
| 302 | + addPeerInfo(row, dc, n + 1, "schema_version", schemaVersion); | |
| 303 | + addPeerInfo(row, dc, n + 1, "graph", false); | |
| 302 | 304 | |
| 303 | 305 | // These columns might not always be present, we don't have to specify them in the scassandra |
| 304 | 306 | // column metadata as it will default them to text columns. |
| 305 | - rowBuilder = addInfoIfExists(rowBuilder, dc, n + 1, "dse_version"); | |
| 306 | - rowBuilder = addInfoIfExists(rowBuilder, dc, n + 1, "workload"); | |
| 307 | - | |
| 308 | - row = rowBuilder.build(); | |
| 307 | + addPeerInfoIfExists(row, dc, n + 1, "dse_version"); | |
| 308 | + addPeerInfoIfExists(row, dc, n + 1, "workload"); | |
| 309 | 309 | } else { // prime system.peers. |
| 310 | 310 | query = "SELECT * FROM system.peers WHERE peer='" + address + "'"; |
| 311 | 311 | metadata = SELECT_PEERS; |
| 312 | - ImmutableMap.Builder<String, Object> rowBuilder = ImmutableMap.<String, Object>builder() | |
| 313 | - .put("peer", address) | |
| 314 | - .put("rpc_address", address) | |
| 315 | - .put("data_center", datacenter(dc)) | |
| 316 | - .put("rack", "rack1") | |
| 317 | - .put("release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8")) | |
| 318 | - .put("tokens", ImmutableSet.of(Long.toString(tokens.get(n)))); | |
| 319 | - | |
| 320 | - rowBuilder = addInfoIfExists(rowBuilder, dc, n + 1, "listen_address"); | |
| 321 | - rowBuilder = addInfoIfExists(rowBuilder, dc, n + 1, "dse_version"); | |
| 322 | - rowBuilder = addInfoIfExists(rowBuilder, dc, n + 1, "workload"); | |
| 323 | - | |
| 324 | - row = rowBuilder.build(); | |
| 325 | - rows.add(rowBuilder.build()); | |
| 312 | + row = Maps.newHashMap(); | |
| 313 | + addPeerInfo(row, dc, n + 1, "peer", address); | |
| 314 | + addPeerInfo(row, dc, n + 1, "rpc_address", address); | |
| 315 | + addPeerInfo(row, dc, n + 1, "data_center", datacenter(dc)); | |
| 316 | + addPeerInfo(row, dc, n + 1, "rack", getPeerInfo(dc, n + 1, "rack", "rack1")); | |
| 317 | + addPeerInfo(row, dc, n + 1, "release_version", getPeerInfo(dc, n + 1, "release_version", "2.1.8")); | |
| 318 | + addPeerInfo(row, dc, n + 1, "tokens", ImmutableSet.of(Long.toString(tokens.get(n)))); | |
| 319 | + addPeerInfo(row, dc, n + 1, "host_id", UUIDs.random()); | |
| 320 | + addPeerInfo(row, dc, n + 1, "schema_version", schemaVersion); | |
| 321 | + addPeerInfo(row, dc, n + 1, "graph", false); | |
| 322 | + | |
| 323 | + addPeerInfoIfExists(row, dc, n + 1, "listen_address"); | |
| 324 | + addPeerInfoIfExists(row, dc, n + 1, "dse_version"); | |
| 325 | + addPeerInfoIfExists(row, dc, n + 1, "workload"); | |
| 326 | + | |
| 327 | + rows.add(row); | |
| 326 | 328 | } |
| 327 | 329 | client.prime(PrimingRequest.queryBuilder() |
| 328 | 330 | .withQuery(query) |
| @@ -364,16 +366,24 @@ | ||
| 364 | 366 | .build()); |
| 365 | 367 | } |
| 366 | 368 | |
| 367 | - private ImmutableMap.Builder<String, Object> addInfoIfExists(ImmutableMap.Builder<String, Object> builder, int dc, int node, String property) { | |
| 369 | + private void addPeerInfo(Map<String, Object> input, int dc, int node, String property, Object defaultValue) { | |
| 370 | + Object peerInfo = getPeerInfo(dc, node, property, defaultValue); | |
| 371 | + if (peerInfo != null) { | |
| 372 | + input.put(property, peerInfo); | |
| 373 | + } | |
| 374 | + } | |
| 375 | + | |
| 376 | + private void addPeerInfoIfExists(Map<String, Object> input, int dc, int node, String property) { | |
| 368 | 377 | Map<Integer, Map<String, Object>> forDc = forcedPeerInfos.get(dc); |
| 369 | 378 | if (forDc == null) |
| 370 | - return builder; | |
| 379 | + return; | |
| 371 | 380 | |
| 372 | 381 | Map<String, Object> forNode = forDc.get(node); |
| 373 | 382 | if (forNode == null) |
| 374 | - return builder; | |
| 383 | + return; | |
| 375 | 384 | |
| 376 | - return (forNode.containsKey(property)) ? builder.put(property, forNode.get(property)) : builder; | |
| 385 | + if (forNode.containsKey(property)) | |
| 386 | + input.put(property, forNode.get(property)); | |
| 377 | 387 | } |
| 378 | 388 | |
| 379 | 389 | private Object getPeerInfo(int dc, int node, String property, Object defaultValue) { |
| @@ -397,7 +407,10 @@ | ||
| 397 | 407 | column("rack", TEXT), |
| 398 | 408 | column("release_version", TEXT), |
| 399 | 409 | column("tokens", set(TEXT)), |
| 400 | - column("listen_address", INET) | |
| 410 | + column("listen_address", INET), | |
| 411 | + column("host_id", UUID), | |
| 412 | + column("graph", BOOLEAN), | |
| 413 | + column("schema_version", UUID) | |
| 401 | 414 | }; |
| 402 | 415 | |
| 403 | 416 | static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_LOCAL = { |
| @@ -412,6 +425,8 @@ | ||
| 412 | 425 | column("rack", TEXT), |
| 413 | 426 | column("release_version", TEXT), |
| 414 | 427 | column("tokens", set(TEXT)), |
| 428 | + column("graph", BOOLEAN), | |
| 429 | + column("schema_version", UUID) | |
| 415 | 430 | }; |
| 416 | 431 | |
| 417 | 432 | static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_CLUSTER_NAME = { |
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +59 −23
| @@ -15,18 +15,17 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import com.datastax.driver.core.exceptions.SyntaxError; | |
| 18 | 19 | import com.datastax.driver.core.utils.CassandraVersion; |
| 20 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 19 | 21 | import org.testng.annotations.Test; |
| 20 | 22 | |
| 21 | 23 | import java.util.List; |
| 22 | 24 | import java.util.Locale; |
| 23 | -import java.util.concurrent.CountDownLatch; | |
| 24 | -import java.util.concurrent.ExecutorService; | |
| 25 | -import java.util.concurrent.Executors; | |
| 26 | -import java.util.concurrent.TimeUnit; | |
| 25 | +import java.util.concurrent.*; | |
| 27 | 26 | |
| 27 | +import static com.datastax.driver.core.Assertions.*; | |
| 28 | 28 | import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; |
| 29 | -import static org.testng.Assert.*; | |
| 30 | 29 | |
| 31 | 30 | /** |
| 32 | 31 | * Simple test of the Sessions methods against a one node cluster. |
| @@ -47,11 +46,11 @@ | ||
| 47 | 46 | } |
| 48 | 47 | |
| 49 | 48 | @Test(groups = "short") |
| 50 | - public void executeTest() throws Exception { | |
| 49 | + public void should_execute_simple_statements() throws Exception { | |
| 51 | 50 | // Simple calls to all versions of the execute/executeAsync methods |
| 52 | 51 | String key = "execute_test"; |
| 53 | 52 | ResultSet rs = session().execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE1, key, "foo", 42, 24.03f)); |
| 54 | - assertTrue(rs.isExhausted()); | |
| 53 | + assertThat(rs.isExhausted()).isTrue(); | |
| 55 | 54 | |
| 56 | 55 | // execute |
| 57 | 56 | checkExecuteResultSet(session().execute(String.format(TestUtils.SELECT_ALL_FORMAT, TABLE1)), key); |
| @@ -63,12 +62,12 @@ | ||
| 63 | 62 | } |
| 64 | 63 | |
| 65 | 64 | @Test(groups = "short") |
| 66 | - public void executePreparedTest() throws Exception { | |
| 65 | + public void should_execute_prepared_statements() throws Exception { | |
| 67 | 66 | // Simple calls to all versions of the execute/executeAsync methods for prepared statements |
| 68 | 67 | // Note: the goal is only to exercice the Session methods, PreparedStatementTest have better prepared statement tests. |
| 69 | 68 | String key = "execute_prepared_test"; |
| 70 | 69 | ResultSet rs = session().execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE2, key, "foo", 42, 24.03f)); |
| 71 | - assertTrue(rs.isExhausted()); | |
| 70 | + assertThat(rs.isExhausted()).isTrue(); | |
| 72 | 71 | |
| 73 | 72 | PreparedStatement p = session().prepare(String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = ?", TABLE2)); |
| 74 | 73 | BoundStatement bs = p.bind(key); |
| @@ -83,17 +82,17 @@ | ||
| 83 | 82 | } |
| 84 | 83 | |
| 85 | 84 | private static void checkExecuteResultSet(ResultSet rs, String key) { |
| 86 | - assertTrue(!rs.isExhausted()); | |
| 85 | + assertThat(rs.isExhausted()).isFalse(); | |
| 87 | 86 | Row row = rs.one(); |
| 88 | - assertTrue(rs.isExhausted()); | |
| 89 | - assertEquals(row.getString("k"), key); | |
| 90 | - assertEquals(row.getString("t"), "foo"); | |
| 91 | - assertEquals(row.getInt("i"), 42); | |
| 92 | - assertEquals(row.getFloat("f"), 24.03f, 0.1f); | |
| 87 | + assertThat(rs.isExhausted()).isTrue(); | |
| 88 | + assertThat(row.getString("k")).isEqualTo(key); | |
| 89 | + assertThat(row.getString("t")).isEqualTo("foo"); | |
| 90 | + assertThat(row.getInt("i")).isEqualTo(42); | |
| 91 | + assertThat(row.getFloat("f")).isEqualTo(24.03f, offset(0.1f)); | |
| 93 | 92 | } |
| 94 | 93 | |
| 95 | 94 | @Test(groups = "short") |
| 96 | - public void executePreparedCounterTest() throws Exception { | |
| 95 | + public void should_execute_prepared_counter_statement() throws Exception { | |
| 97 | 96 | PreparedStatement p = session().prepare("UPDATE " + COUNTER_TABLE + " SET c = c + ? WHERE k = ?"); |
| 98 | 97 | |
| 99 | 98 | session().execute(p.bind(1L, "row")); |
| @@ -101,8 +100,8 @@ | ||
| 101 | 100 | |
| 102 | 101 | ResultSet rs = session().execute("SELECT * FROM " + COUNTER_TABLE); |
| 103 | 102 | List<Row> rows = rs.all(); |
| 104 | - assertEquals(rows.size(), 1); | |
| 105 | - assertEquals(rows.get(0).getLong("c"), 2L); | |
| 103 | + assertThat(rows).hasSize(1); | |
| 104 | + assertThat(rows.get(0).getLong("c")).isEqualTo(2L); | |
| 106 | 105 | } |
| 107 | 106 | |
| 108 | 107 | /** |
| @@ -113,7 +112,7 @@ | ||
| 113 | 112 | * @expected_result session established and queries made successfully using it. |
| 114 | 113 | */ |
| 115 | 114 | @Test(groups = "short") |
| 116 | - public void session_should_function_with_snappy_compression() throws Exception { | |
| 115 | + public void should_function_with_snappy_compression() throws Exception { | |
| 117 | 116 | compressionTest(ProtocolOptions.Compression.SNAPPY); |
| 118 | 117 | } |
| 119 | 118 | |
| @@ -126,7 +125,7 @@ | ||
| 126 | 125 | */ |
| 127 | 126 | @Test(groups = "short") |
| 128 | 127 | @CassandraVersion(major = 2.0) |
| 129 | - public void session_should_function_with_lz4_compression() throws Exception { | |
| 128 | + public void should_function_with_lz4_compression() throws Exception { | |
| 130 | 129 | compressionTest(ProtocolOptions.Compression.LZ4); |
| 131 | 130 | } |
| 132 | 131 | |
| @@ -138,7 +137,7 @@ | ||
| 138 | 137 | // Simple calls to all versions of the execute/executeAsync methods |
| 139 | 138 | String key = "execute_compressed_test_" + compression; |
| 140 | 139 | ResultSet rs = compressedSession.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE3, key, "foo", 42, 24.03f)); |
| 141 | - assertTrue(rs.isExhausted()); | |
| 140 | + assertThat(rs.isExhausted()).isTrue(); | |
| 142 | 141 | |
| 143 | 142 | String SELECT_ALL = String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = '%s'", TABLE3, key); |
| 144 | 143 | |
| @@ -159,7 +158,7 @@ | ||
| 159 | 158 | * Checks for deadlocks when a session shutdown races with the initialization of the cluster (JAVA-418). |
| 160 | 159 | */ |
| 161 | 160 | @Test(groups = "short") |
| 162 | - public void closeDuringClusterInitTest() throws InterruptedException { | |
| 161 | + public void should_close_properly_when_racing_with_cluster_init() throws InterruptedException { | |
| 163 | 162 | for (int i = 0; i < 500; i++) { |
| 164 | 163 | |
| 165 | 164 | // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster |
| @@ -206,7 +205,7 @@ | ||
| 206 | 205 | |
| 207 | 206 | executor.shutdown(); |
| 208 | 207 | boolean normalShutdown = executor.awaitTermination(5, TimeUnit.SECONDS); |
| 209 | - assertTrue(normalShutdown); | |
| 208 | + assertThat(normalShutdown).isTrue(); | |
| 210 | 209 | |
| 211 | 210 | } finally { |
| 212 | 211 | // The deadlock occurred here before JAVA-418 |
| @@ -214,4 +213,41 @@ | ||
| 214 | 213 | } |
| 215 | 214 | } |
| 216 | 215 | } |
| 216 | + | |
| 217 | + /** | |
| 218 | + * Ensures that if an attempt is made to create a {@link Session} via {@link Cluster#connect} with an invalid | |
| 219 | + * keyspace that the returned exception is decorated with an indication to check that your keyspace name is valid | |
| 220 | + * and includes the original {@link SyntaxError}. | |
| 221 | + */ | |
| 222 | + @Test(groups = "short") | |
| 223 | + public void should_give_explicit_error_message_when_keyspace_name_invalid() { | |
| 224 | + try { | |
| 225 | + cluster().connect("%!;"); | |
| 226 | + fail("Expected a SyntaxError"); | |
| 227 | + } catch (SyntaxError e) { | |
| 228 | + assertThat(e.getMessage()) | |
| 229 | + .contains("Error executing \"USE %!;\"") | |
| 230 | + .contains("Check that your keyspace name is valid"); | |
| 231 | + } | |
| 232 | + } | |
| 233 | + | |
| 234 | + /** | |
| 235 | + * Ensures that if an attempt is made to create a {@link Session} via {@link Cluster#connectAsync} with an invalid | |
| 236 | + * keyspace that the returned exception is decorated with an indication to check that your keyspace name is valid | |
| 237 | + * and includes the original {@link SyntaxError}. | |
| 238 | + */ | |
| 239 | + @Test(groups = "short") | |
| 240 | + public void should_give_explicit_error_message_when_keyspace_name_invalid_async() { | |
| 241 | + ListenableFuture<Session> sessionFuture = cluster().connectAsync(""); | |
| 242 | + try { | |
| 243 | + sessionFuture.get(); | |
| 244 | + } catch (ExecutionException e) { | |
| 245 | + assertThat(e.getCause()).isInstanceOf(SyntaxError.class); | |
| 246 | + assertThat(e.getCause().getMessage()) | |
| 247 | + .contains("no viable alternative at input '<EOF>'") | |
| 248 | + .contains("Check that your keyspace name is valid"); | |
| 249 | + } catch (Exception e) { | |
| 250 | + fail("Did not expect Exception", e); | |
| 251 | + } | |
| 252 | + } | |
| 217 | 253 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +39 −0
| @@ -18,7 +18,9 @@ | ||
| 18 | 18 | import org.testng.annotations.Test; |
| 19 | 19 | |
| 20 | 20 | import java.util.Collections; |
| 21 | +import java.util.HashMap; | |
| 21 | 22 | import java.util.List; |
| 23 | +import java.util.Map; | |
| 22 | 24 | |
| 23 | 25 | import static org.assertj.core.api.Assertions.assertThat; |
| 24 | 26 | |
| @@ -47,6 +49,43 @@ | ||
| 47 | 49 | assertThat(actual).isSameAs(expected); |
| 48 | 50 | } |
| 49 | 51 | |
| 52 | + @Test(groups = "unit", expectedExceptions = {IllegalStateException.class}) | |
| 53 | + public void should_throw_ISE_if_getObject_called_on_statement_without_named_values() { | |
| 54 | + new SimpleStatement("doesn't matter").getObject("name"); | |
| 55 | + } | |
| 56 | + | |
| 57 | + @Test(groups = "unit") | |
| 58 | + public void should_return_null_if_getObject_called_on_statement_with_wrong_name() { | |
| 59 | + Map<String, Object> namedVales = new HashMap<String, Object>(); | |
| 60 | + namedVales.put("name", new Object()); | |
| 61 | + Object actual = new SimpleStatement("doesn't matter", namedVales).getObject("wrong name"); | |
| 62 | + assertThat(actual).isNull(); | |
| 63 | + } | |
| 64 | + | |
| 65 | + @Test(groups = "unit") | |
| 66 | + public void should_return_object_with_name() { | |
| 67 | + Object expected = new Object(); | |
| 68 | + String valueName = "name"; | |
| 69 | + Map<String, Object> namedVales = new HashMap<String, Object>(); | |
| 70 | + namedVales.put(valueName, expected); | |
| 71 | + Object actual = new SimpleStatement("doesn't matter", namedVales).getObject(valueName); | |
| 72 | + assertThat(actual).isSameAs(expected); | |
| 73 | + } | |
| 74 | + | |
| 75 | + @Test(groups = "unit", expectedExceptions = {IllegalStateException.class}) | |
| 76 | + public void should_throw_ISE_if_getValueNames_called_on_statement_without_named_values() { | |
| 77 | + new SimpleStatement("doesn't matter").getValueNames(); | |
| 78 | + } | |
| 79 | + | |
| 80 | + @Test(groups = "unit") | |
| 81 | + public void should_return_named_value() { | |
| 82 | + Object expected = new Object(); | |
| 83 | + Map<String, Object> namedValues = new HashMap<String, Object>(); | |
| 84 | + namedValues.put("name", expected); | |
| 85 | + Object actual = new SimpleStatement("doesn't matter", namedValues).getObject("name"); | |
| 86 | + assertThat(actual).isEqualTo(expected); | |
| 87 | + } | |
| 88 | + | |
| 50 | 89 | @Test(groups = "unit") |
| 51 | 90 | public void should_return_number_of_values() { |
| 52 | 91 | assertThat( |
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +5 −3
| @@ -21,7 +21,9 @@ | ||
| 21 | 21 | import com.datastax.driver.core.policies.SpeculativeExecutionPolicy; |
| 22 | 22 | import com.google.common.collect.ImmutableList; |
| 23 | 23 | import com.google.common.collect.ImmutableMap; |
| 24 | +import org.scassandra.http.client.Consistency; | |
| 24 | 25 | import org.scassandra.http.client.PrimingRequest; |
| 26 | +import org.scassandra.http.client.Result; | |
| 25 | 27 | import org.testng.annotations.AfterMethod; |
| 26 | 28 | import org.testng.annotations.BeforeMethod; |
| 27 | 29 | import org.testng.annotations.Test; |
| @@ -101,14 +103,14 @@ | ||
| 101 | 103 | // will retry once on this node: |
| 102 | 104 | scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder() |
| 103 | 105 | .withQuery("mock query") |
| 104 | - .withConsistency(PrimingRequest.Consistency.TWO) | |
| 105 | - .withResult(PrimingRequest.Result.read_request_timeout) | |
| 106 | + .withConsistency(Consistency.TWO) | |
| 107 | + .withResult(Result.read_request_timeout) | |
| 106 | 108 | .build() |
| 107 | 109 | ); |
| 108 | 110 | |
| 109 | 111 | scassandras.node(1).primingClient().prime(PrimingRequest.queryBuilder() |
| 110 | 112 | .withQuery("mock query") |
| 111 | - .withConsistency(PrimingRequest.Consistency.ONE) | |
| 113 | + .withConsistency(Consistency.ONE) | |
| 112 | 114 | .withRows(row("result", "result1")) |
| 113 | 115 | .build() |
| 114 | 116 | ); |
modified driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +17 −0
| @@ -155,6 +155,23 @@ | ||
| 155 | 155 | update("foo").with(set("v", Lists.newArrayList(now()))).where(eq("k", 1)), |
| 156 | 156 | update("foo").with(set("v", Lists.newArrayList(uuid()))).where(eq("k", 1)), |
| 157 | 157 | |
| 158 | + delete().from("foo").where(lt("k", fcall("now"))), | |
| 159 | + delete().from("foo").where(lt("k", now())), | |
| 160 | + update("foo").where(eq("k", fcall("now"))), | |
| 161 | + delete().listElt("a", 1).from("test_coll"), | |
| 162 | + | |
| 163 | + // LWT | |
| 164 | + update("foo").where(eq("is", "charlie?")).ifExists(), | |
| 165 | + update("foo").where(eq("good", "drivers")).onlyIf(contains("developers", "datastax")), | |
| 166 | + update("foo").onlyIf().and(contains("developers", "datastax")).where(eq("good", "drivers")), | |
| 167 | + update("foo").onlyIf(contains("developers", "datastax")).with(set("v", 0)), | |
| 168 | + update("foo").with(set("v", 0)).onlyIf(contains("hello", "world")), | |
| 169 | + | |
| 170 | + insertInto("foo").value("k", 1).value("v", Sets.newHashSet(now())).ifNotExists(), | |
| 171 | + | |
| 172 | + delete().from("foo").where(eq("k", 2)).ifExists(), | |
| 173 | + delete().from("foo").onlyIf(eq("k", 2)), | |
| 174 | + | |
| 158 | 175 | // raw() calls |
| 159 | 176 | |
| 160 | 177 | insertInto("foo").value("k", 1).value("v", raw("foo()")), |
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +59 −0
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.DriverException; |
| 19 | 19 | import com.datastax.driver.core.policies.*; |
| 20 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 20 | 21 | import org.testng.annotations.Test; |
| 21 | 22 | |
| 22 | 23 | import java.util.Iterator; |
| @@ -26,10 +27,18 @@ | ||
| 26 | 27 | |
| 27 | 28 | public class StatementWrapperTest extends CCMTestsSupport { |
| 28 | 29 | |
| 30 | + private static final String INSERT_QUERY = "insert into test (k, v) values (?, ?)"; | |
| 31 | + private static final String SELECT_QUERY = "select * from test where k = ?"; | |
| 32 | + | |
| 29 | 33 | CustomLoadBalancingPolicy loadBalancingPolicy = new CustomLoadBalancingPolicy(); |
| 30 | 34 | CustomSpeculativeExecutionPolicy speculativeExecutionPolicy = new CustomSpeculativeExecutionPolicy(); |
| 31 | 35 | CustomRetryPolicy retryPolicy = new CustomRetryPolicy(); |
| 32 | 36 | |
| 37 | + @Override | |
| 38 | + public void onTestContextInitialized() { | |
| 39 | + execute("create table test (k text primary key, v int)"); | |
| 40 | + } | |
| 41 | + | |
| 33 | 42 | @Override |
| 34 | 43 | public Cluster.Builder createClusterBuilder() { |
| 35 | 44 | return Cluster.builder() |
| @@ -78,6 +87,56 @@ | ||
| 78 | 87 | assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(1); |
| 79 | 88 | } |
| 80 | 89 | |
| 90 | + @CassandraVersion(major = 2.0) | |
| 91 | + @Test(groups = "short") | |
| 92 | + public void should_execute_wrapped_simple_statement() { | |
| 93 | + session().execute(new CustomStatement(new SimpleStatement(INSERT_QUERY, "key_simple", 1))); | |
| 94 | + | |
| 95 | + ResultSet rs = session().execute(new CustomStatement(new SimpleStatement(SELECT_QUERY, "key_simple"))); | |
| 96 | + assertThat(rs.one().getInt("v")).isEqualTo(1); | |
| 97 | + } | |
| 98 | + | |
| 99 | + @Test(groups = "short") | |
| 100 | + public void should_execute_wrapped_bound_statement() { | |
| 101 | + PreparedStatement preparedStatement = session().prepare(new SimpleStatement(INSERT_QUERY)); | |
| 102 | + session().execute(new CustomStatement(preparedStatement.bind("key_bound", 1))); | |
| 103 | + | |
| 104 | + preparedStatement = session().prepare(new SimpleStatement(SELECT_QUERY)); | |
| 105 | + ResultSet rs = session().execute(new CustomStatement(preparedStatement.bind("key_bound"))); | |
| 106 | + assertThat(rs.one().getInt("v")).isEqualTo(1); | |
| 107 | + } | |
| 108 | + | |
| 109 | + @CassandraVersion(major = 2.0) | |
| 110 | + @Test(groups = "short") | |
| 111 | + public void should_execute_wrapped_batch_statement() { | |
| 112 | + BatchStatement batchStatement = new BatchStatement(); | |
| 113 | + batchStatement.add(new SimpleStatement(INSERT_QUERY, "key_batch", 1)); | |
| 114 | + | |
| 115 | + session().execute(new CustomStatement(batchStatement)); | |
| 116 | + | |
| 117 | + ResultSet rs = session().execute(SELECT_QUERY, "key_batch"); | |
| 118 | + assertThat(rs.one().getInt("v")).isEqualTo(1); | |
| 119 | + } | |
| 120 | + | |
| 121 | + @CassandraVersion(major = 2.0) | |
| 122 | + @Test(groups = "short") | |
| 123 | + public void should_add_wrapped_batch_statement_to_batch_statement() { | |
| 124 | + BatchStatement batchStatementForWrapping = new BatchStatement(); | |
| 125 | + batchStatementForWrapping.add(new SimpleStatement(INSERT_QUERY, "key1", 1)); | |
| 126 | + | |
| 127 | + BatchStatement batchStatement = new BatchStatement(); | |
| 128 | + batchStatement.add(new CustomStatement(new SimpleStatement(INSERT_QUERY, "key2", 2))); | |
| 129 | + batchStatement.add(new CustomStatement(batchStatementForWrapping)); | |
| 130 | + | |
| 131 | + session().execute(batchStatement); | |
| 132 | + | |
| 133 | + ResultSet rs = session().execute(SELECT_QUERY, "key1"); | |
| 134 | + assertThat(rs.one().getInt("v")).isEqualTo(1); | |
| 135 | + | |
| 136 | + rs = session().execute(SELECT_QUERY, "key2"); | |
| 137 | + assertThat(rs.one().getInt("v")).isEqualTo(2); | |
| 138 | + } | |
| 139 | + | |
| 81 | 140 | /** |
| 82 | 141 | * A custom wrapper that's just used to mark statements. |
| 83 | 142 | */ |
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +72 −0
| @@ -497,4 +497,76 @@ | ||
| 497 | 497 | // then the table's options should contain populated extensions. |
| 498 | 498 | assertThat(table.getOptions().getExtensions()).isEqualTo(extensions); |
| 499 | 499 | } |
| 500 | + | |
| 501 | + /** | |
| 502 | + * Validates that a table with case-sensitive column names and column names | |
| 503 | + * consisting of (quoted) reserved keywords is correctly parsed | |
| 504 | + * and that the generated CQL is valid. | |
| 505 | + * | |
| 506 | + * @jira_ticket JAVA-1064 | |
| 507 | + * @test_category metadata | |
| 508 | + */ | |
| 509 | + @Test(groups = "short") | |
| 510 | + public void should_parse_table_with_case_sensitive_column_names_and_reserved_keywords() throws Exception { | |
| 511 | + // given | |
| 512 | + String c1 = Metadata.quote("quotes go \"\" here \"\" "); | |
| 513 | + String c2 = Metadata.quote("\\x00\\x25"); | |
| 514 | + String c3 = Metadata.quote("columnfamily"); | |
| 515 | + String c4 = Metadata.quote("select"); | |
| 516 | + String c5 = Metadata.quote("who''s there'? "); | |
| 517 | + String c6 = Metadata.quote("faux )"); | |
| 518 | + String c7 = Metadata.quote("COMPACT STORAGE"); | |
| 519 | + // single partition key | |
| 520 | + String cql1 = String.format("CREATE TABLE %s.\"MyTable1\" (" | |
| 521 | + + "%s text, " | |
| 522 | + + "%s text, " | |
| 523 | + + "%s text, " | |
| 524 | + + "%s text, " | |
| 525 | + + "%s text, " | |
| 526 | + + "%s text, " | |
| 527 | + + "%s text, " | |
| 528 | + + "PRIMARY KEY (%s, %s, %s, %s, %s, %s)" | |
| 529 | + + ")", keyspace, c1, c2, c3, c4, c5, c6, c7, c1, c2, c3, c4, c5, c6); | |
| 530 | + // composite partition key | |
| 531 | + String cql2 = String.format("CREATE TABLE %s.\"MyTable2\" (" | |
| 532 | + + "%s text, " | |
| 533 | + + "%s text, " | |
| 534 | + + "%s text, " | |
| 535 | + + "%s text, " | |
| 536 | + + "%s text, " | |
| 537 | + + "%s text, " | |
| 538 | + + "%s text, " | |
| 539 | + + "PRIMARY KEY ((%s, %s), %s, %s, %s, %s)" | |
| 540 | + + ")", keyspace, c1, c2, c3, c4, c5, c6, c7, c1, c2, c3, c4, c5, c6); | |
| 541 | + // when | |
| 542 | + execute(cql1, cql2); | |
| 543 | + TableMetadata table1 = cluster().getMetadata().getKeyspace(keyspace).getTable("\"MyTable1\""); | |
| 544 | + TableMetadata table2 = cluster().getMetadata().getKeyspace(keyspace).getTable("\"MyTable2\""); | |
| 545 | + // then | |
| 546 | + assertThat(table1) | |
| 547 | + .hasColumn(c1) | |
| 548 | + .hasColumn(c2) | |
| 549 | + .hasColumn(c3) | |
| 550 | + .hasColumn(c4) | |
| 551 | + .hasColumn(c5) | |
| 552 | + .hasColumn(c6) | |
| 553 | + .hasColumn(c7); | |
| 554 | + assertThat(table1.asCQLQuery()).startsWith(cql1); | |
| 555 | + assertThat(table2) | |
| 556 | + .hasColumn(c1) | |
| 557 | + .hasColumn(c2) | |
| 558 | + .hasColumn(c3) | |
| 559 | + .hasColumn(c4) | |
| 560 | + .hasColumn(c5) | |
| 561 | + .hasColumn(c6) | |
| 562 | + .hasColumn(c7); | |
| 563 | + assertThat(table2.asCQLQuery()).startsWith(cql2); | |
| 564 | + execute( | |
| 565 | + "DROP TABLE \"MyTable1\"", | |
| 566 | + "DROP TABLE \"MyTable2\"", | |
| 567 | + table1.asCQLQuery(), | |
| 568 | + table2.asCQLQuery() | |
| 569 | + ); | |
| 570 | + } | |
| 571 | + | |
| 500 | 572 | } |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +100 −35
| @@ -37,7 +37,6 @@ | ||
| 37 | 37 | import java.util.*; |
| 38 | 38 | import java.util.concurrent.*; |
| 39 | 39 | import java.util.concurrent.atomic.AtomicInteger; |
| 40 | -import java.util.concurrent.locks.ReentrantLock; | |
| 41 | 40 | |
| 42 | 41 | import static com.datastax.driver.core.ConditionChecker.check; |
| 43 | 42 | import static java.util.concurrent.TimeUnit.MINUTES; |
| @@ -672,47 +671,29 @@ | ||
| 672 | 671 | return prefix + seq.incrementAndGet(); |
| 673 | 672 | } |
| 674 | 673 | |
| 675 | - // use ports in the ephemeral range | |
| 676 | - private static int nextPort = 50000; | |
| 677 | - | |
| 678 | - private static final ReentrantLock PORT_LOCK = new ReentrantLock(); | |
| 679 | - | |
| 680 | 674 | /** |
| 681 | - * Find an available port in the ephemeral range. | |
| 675 | + * Finds an available port in the ephemeral range. | |
| 676 | + * This is loosely inspired by Apache MINA's AvailablePortFinder. | |
| 682 | 677 | * |
| 683 | 678 | * @return A local port that is currently unused. |
| 684 | 679 | */ |
| 685 | - public static int findAvailablePort() { | |
| 686 | - PORT_LOCK.lock(); | |
| 680 | + public synchronized static int findAvailablePort() throws RuntimeException { | |
| 681 | + ServerSocket ss = null; | |
| 687 | 682 | try { |
| 688 | - for (int i = 0; i < 3; i++) { | |
| 689 | - int port = nextPort; | |
| 690 | - ServerSocket s = null; | |
| 691 | - for (int j = 0; j < 100; j++) { | |
| 692 | - try { | |
| 693 | - s = new ServerSocket(port); | |
| 694 | - s.close(); | |
| 695 | - nextPort = port + 1; | |
| 696 | - return port; | |
| 697 | - } catch (IOException e) { | |
| 698 | - // ok | |
| 699 | - } finally { | |
| 700 | - port++; | |
| 701 | - if (s != null) { | |
| 702 | - try { | |
| 703 | - s.close(); | |
| 704 | - } catch (IOException e) { | |
| 705 | - // ok | |
| 706 | - } | |
| 707 | - } | |
| 708 | - } | |
| 683 | + // let the system pick an ephemeral port | |
| 684 | + ss = new ServerSocket(0); | |
| 685 | + ss.setReuseAddress(true); | |
| 686 | + return ss.getLocalPort(); | |
| 687 | + } catch (IOException e) { | |
| 688 | + throw Throwables.propagate(e); | |
| 689 | + } finally { | |
| 690 | + if (ss != null) { | |
| 691 | + try { | |
| 692 | + ss.close(); | |
| 693 | + } catch (IOException e) { | |
| 694 | + Throwables.propagate(e); | |
| 709 | 695 | } |
| 710 | - logger.warn("Could not acquire an available port after 100 attempts, sleeping for 1 minute"); | |
| 711 | - Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES); | |
| 712 | 696 | } |
| 713 | - throw new RuntimeException(String.format("Could not acquire an available port within range: %s-%s", nextPort, nextPort + 100)); | |
| 714 | - } finally { | |
| 715 | - PORT_LOCK.unlock(); | |
| 716 | 697 | } |
| 717 | 698 | } |
| 718 | 699 | |
| @@ -855,4 +836,88 @@ | ||
| 855 | 836 | return (bean.getFreePhysicalMemorySize() + bean.getFreeSwapSpaceSize()) / 1024 / 1024; |
| 856 | 837 | } |
| 857 | 838 | |
| 839 | + /** | |
| 840 | + * Helper for generating a DynamicCompositeType {@link ByteBuffer} from the given parameters. | |
| 841 | + * | |
| 842 | + * Any of params given as an Integer will be considered with a field name of 'i', any as String will | |
| 843 | + * be considered with a field name of 's'. | |
| 844 | + * | |
| 845 | + * @param params params to serialize. | |
| 846 | + * @return bytes representing a DynamicCompositeType. | |
| 847 | + */ | |
| 848 | + public static ByteBuffer serializeForDynamicCompositeType(Object... params) { | |
| 849 | + List<ByteBuffer> l = new ArrayList<ByteBuffer>(); | |
| 850 | + int size = 0; | |
| 851 | + for (Object p : params) { | |
| 852 | + if (p instanceof Integer) { | |
| 853 | + ByteBuffer elt = ByteBuffer.allocate(2 + 2 + 4 + 1); | |
| 854 | + elt.putShort((short) (0x8000 | 'i')); | |
| 855 | + elt.putShort((short) 4); | |
| 856 | + elt.putInt((Integer) p); | |
| 857 | + elt.put((byte) 0); | |
| 858 | + elt.flip(); | |
| 859 | + size += elt.remaining(); | |
| 860 | + l.add(elt); | |
| 861 | + } else if (p instanceof String) { | |
| 862 | + ByteBuffer bytes = ByteBuffer.wrap(((String) p).getBytes()); | |
| 863 | + ByteBuffer elt = ByteBuffer.allocate(2 + 2 + bytes.remaining() + 1); | |
| 864 | + elt.putShort((short) (0x8000 | 's')); | |
| 865 | + elt.putShort((short) bytes.remaining()); | |
| 866 | + elt.put(bytes); | |
| 867 | + elt.put((byte) 0); | |
| 868 | + elt.flip(); | |
| 869 | + size += elt.remaining(); | |
| 870 | + l.add(elt); | |
| 871 | + } else { | |
| 872 | + throw new RuntimeException(); | |
| 873 | + } | |
| 874 | + } | |
| 875 | + ByteBuffer res = ByteBuffer.allocate(size); | |
| 876 | + for (ByteBuffer bb : l) | |
| 877 | + res.put(bb); | |
| 878 | + res.flip(); | |
| 879 | + return res; | |
| 880 | + } | |
| 881 | + | |
| 882 | + /** | |
| 883 | + * Helper for generating a Composite {@link ByteBuffer} from the given parameters. | |
| 884 | + * | |
| 885 | + * Expects Integer and String types for parameters. | |
| 886 | + * | |
| 887 | + * @param params params to serialize. | |
| 888 | + * @return bytes representing a CompositeType | |
| 889 | + */ | |
| 890 | + public static ByteBuffer serializeForCompositeType(Object... params) { | |
| 891 | + | |
| 892 | + List<ByteBuffer> l = new ArrayList<ByteBuffer>(); | |
| 893 | + int size = 0; | |
| 894 | + for (Object p : params) { | |
| 895 | + if (p instanceof Integer) { | |
| 896 | + ByteBuffer elt = ByteBuffer.allocate(2 + 4 + 1); | |
| 897 | + elt.putShort((short) 4); | |
| 898 | + elt.putInt((Integer) p); | |
| 899 | + elt.put((byte) 0); | |
| 900 | + elt.flip(); | |
| 901 | + size += elt.remaining(); | |
| 902 | + l.add(elt); | |
| 903 | + } else if (p instanceof String) { | |
| 904 | + ByteBuffer bytes = ByteBuffer.wrap(((String) p).getBytes()); | |
| 905 | + ByteBuffer elt = ByteBuffer.allocate(2 + bytes.remaining() + 1); | |
| 906 | + elt.putShort((short) bytes.remaining()); | |
| 907 | + elt.put(bytes); | |
| 908 | + elt.put((byte) 0); | |
| 909 | + elt.flip(); | |
| 910 | + size += elt.remaining(); | |
| 911 | + l.add(elt); | |
| 912 | + } else { | |
| 913 | + throw new RuntimeException(); | |
| 914 | + } | |
| 915 | + } | |
| 916 | + ByteBuffer res = ByteBuffer.allocate(size); | |
| 917 | + for (ByteBuffer bb : l) | |
| 918 | + res.put(bb); | |
| 919 | + res.flip(); | |
| 920 | + return res; | |
| 921 | + } | |
| 922 | + | |
| 858 | 923 | } |
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +13 −0
| @@ -379,5 +379,18 @@ | ||
| 379 | 379 | .isEqualTo(range); |
| 380 | 380 | } |
| 381 | 381 | |
| 382 | + @Test(groups = "short") | |
| 383 | + public void should_create_token_from_partition_key() { | |
| 384 | + Metadata metadata = cluster().getMetadata(); | |
| 385 | + | |
| 386 | + Row row = session().execute("SELECT token(i) FROM foo WHERE i = 1").one(); | |
| 387 | + Token expected = row.getToken(0); | |
| 388 | + | |
| 389 | + ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion(); | |
| 390 | + assertThat( | |
| 391 | + metadata.newToken(TypeCodec.cint().serialize(1, protocolVersion)) | |
| 392 | + ).isEqualTo(expected); | |
| 393 | + } | |
| 394 | + | |
| 382 | 395 | protected abstract Token.Factory tokenFactory(); |
| 383 | 396 | } |
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +12 −0
| @@ -28,8 +28,11 @@ | ||
| 28 | 28 | import java.net.InetAddress; |
| 29 | 29 | import java.nio.ByteBuffer; |
| 30 | 30 | import java.util.*; |
| 31 | +import java.util.concurrent.Callable; | |
| 31 | 32 | |
| 33 | +import static com.datastax.driver.core.ConditionChecker.check; | |
| 32 | 34 | import static com.datastax.driver.core.Metadata.quote; |
| 35 | +import static java.util.concurrent.TimeUnit.MINUTES; | |
| 33 | 36 | import static org.testng.Assert.assertEquals; |
| 34 | 37 | import static org.testng.Assert.assertNotEquals; |
| 35 | 38 | |
| @@ -45,12 +48,21 @@ | ||
| 45 | 48 | private final static List<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES = |
| 46 | 49 | new ArrayList<DataType.Name>(EnumSet.of(DataType.Name.LIST, DataType.Name.SET, DataType.Name.MAP, DataType.Name.TUPLE)); |
| 47 | 50 | |
| 51 | + private final Callable<Boolean> userTableExists = new Callable<Boolean>() { | |
| 52 | + @Override | |
| 53 | + public Boolean call() throws Exception { | |
| 54 | + return cluster().getMetadata().getKeyspace(keyspace).getTable("user") != null; | |
| 55 | + } | |
| 56 | + }; | |
| 57 | + | |
| 48 | 58 | @Override |
| 49 | 59 | public void onTestContextInitialized() { |
| 50 | 60 | String type1 = "CREATE TYPE phone (alias text, number text)"; |
| 51 | 61 | String type2 = "CREATE TYPE \"\"\"User Address\"\"\" (street text, \"ZIP\"\"\" int, phones set<frozen<phone>>)"; |
| 52 | 62 | String table = "CREATE TABLE user (id int PRIMARY KEY, addr frozen<\"\"\"User Address\"\"\">)"; |
| 53 | 63 | execute(type1, type2, table); |
| 64 | + // Ci tests fail with "unconfigured columnfamily user" | |
| 65 | + check().that(userTableExists).before(5, MINUTES).becomesTrue(); | |
| 54 | 66 | } |
| 55 | 67 | |
| 56 | 68 | /** |
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java +3 −2
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | import com.google.common.collect.ImmutableMap; |
| 22 | 22 | import org.scassandra.Scassandra; |
| 23 | 23 | import org.scassandra.http.client.PrimingRequest; |
| 24 | +import org.scassandra.http.client.Result; | |
| 24 | 25 | import org.testng.annotations.*; |
| 25 | 26 | |
| 26 | 27 | import java.util.List; |
| @@ -29,7 +30,7 @@ | ||
| 29 | 30 | import static com.datastax.driver.core.ConsistencyLevel.LOCAL_ONE; |
| 30 | 31 | import static org.assertj.core.api.Assertions.assertThat; |
| 31 | 32 | import static org.assertj.core.api.Assertions.fail; |
| 32 | -import static org.scassandra.http.client.PrimingRequest.Result.*; | |
| 33 | +import static org.scassandra.http.client.Result.*; | |
| 33 | 34 | |
| 34 | 35 | public class ExceptionsScassandraTest { |
| 35 | 36 | |
| @@ -111,7 +112,7 @@ | ||
| 111 | 112 | } |
| 112 | 113 | } |
| 113 | 114 | |
| 114 | - protected void simulateError(int hostNumber, PrimingRequest.Result result) { | |
| 115 | + protected void simulateError(int hostNumber, Result result) { | |
| 115 | 116 | scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder() |
| 116 | 117 | .withQuery("mock query") |
| 117 | 118 | .withResult(result) |
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +10 −4
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | import org.scassandra.http.client.Config; |
| 28 | 28 | import org.scassandra.http.client.PrimingRequest; |
| 29 | 29 | import org.scassandra.http.client.PrimingRequest.PrimingRequestBuilder; |
| 30 | +import org.scassandra.http.client.Result; | |
| 30 | 31 | import org.testng.annotations.AfterMethod; |
| 31 | 32 | import org.testng.annotations.BeforeMethod; |
| 32 | 33 | import org.testng.annotations.DataProvider; |
| @@ -38,8 +39,8 @@ | ||
| 38 | 39 | import static org.assertj.core.api.Assertions.assertThat; |
| 39 | 40 | import static org.mockito.Matchers.*; |
| 40 | 41 | import static org.mockito.Mockito.times; |
| 41 | -import static org.scassandra.http.client.PrimingRequest.Result.overloaded; | |
| 42 | -import static org.scassandra.http.client.PrimingRequest.Result.server_error; | |
| 42 | +import static org.scassandra.http.client.Result.overloaded; | |
| 43 | +import static org.scassandra.http.client.Result.server_error; | |
| 43 | 44 | |
| 44 | 45 | /** |
| 45 | 46 | * Base class for retry policy integration tests. |
| @@ -105,11 +106,11 @@ | ||
| 105 | 106 | } |
| 106 | 107 | } |
| 107 | 108 | |
| 108 | - protected void simulateError(int hostNumber, PrimingRequest.Result result) { | |
| 109 | + protected void simulateError(int hostNumber, Result result) { | |
| 109 | 110 | simulateError(hostNumber, result, null); |
| 110 | 111 | } |
| 111 | 112 | |
| 112 | - protected void simulateError(int hostNumber, PrimingRequest.Result result, Config config) { | |
| 113 | + protected void simulateError(int hostNumber, Result result, Config config) { | |
| 113 | 114 | PrimingRequestBuilder builder = PrimingRequest.queryBuilder() |
| 114 | 115 | .withQuery("mock query") |
| 115 | 116 | .withResult(result); |
| @@ -135,6 +136,11 @@ | ||
| 135 | 136 | return query(session); |
| 136 | 137 | } |
| 137 | 138 | |
| 139 | + protected ResultSet queryWithCL(ConsistencyLevel cl) { | |
| 140 | + Statement statement = new SimpleStatement("mock query").setConsistencyLevel(cl); | |
| 141 | + return session.execute(statement); | |
| 142 | + } | |
| 143 | + | |
| 138 | 144 | protected ResultSet query(Session session) { |
| 139 | 145 | return session.execute("mock query"); |
| 140 | 146 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +4 −4
| @@ -23,13 +23,13 @@ | ||
| 23 | 23 | import org.scassandra.http.client.ClosedConnectionConfig; |
| 24 | 24 | import org.scassandra.http.client.ClosedConnectionConfig.CloseType; |
| 25 | 25 | import org.scassandra.http.client.PrimingRequest; |
| 26 | +import org.scassandra.http.client.Result; | |
| 26 | 27 | import org.testng.annotations.Test; |
| 27 | 28 | |
| 28 | 29 | import static com.datastax.driver.core.Assertions.assertThat; |
| 29 | 30 | import static org.assertj.core.api.Fail.fail; |
| 30 | -import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout; | |
| 31 | -import static org.scassandra.http.client.PrimingRequest.Result.unavailable; | |
| 32 | 31 | import static org.scassandra.http.client.PrimingRequest.then; |
| 32 | +import static org.scassandra.http.client.Result.*; | |
| 33 | 33 | |
| 34 | 34 | /** |
| 35 | 35 | * Integration test with a custom implementation, to test retry and ignore decisions. |
| @@ -105,7 +105,7 @@ | ||
| 105 | 105 | |
| 106 | 106 | |
| 107 | 107 | @Test(groups = "short", dataProvider = "serverSideErrors") |
| 108 | - public void should_rethrow_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 108 | + public void should_rethrow_on_server_side_error(Result error, Class<? extends DriverException> exception) { | |
| 109 | 109 | simulateError(1, error); |
| 110 | 110 | try { |
| 111 | 111 | query(); |
| @@ -125,7 +125,7 @@ | ||
| 125 | 125 | |
| 126 | 126 | @Test(groups = "short", dataProvider = "connectionErrors") |
| 127 | 127 | public void should_rethrow_on_connection_error(CloseType closeType) { |
| 128 | - simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 128 | + simulateError(1, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 129 | 129 | try { |
| 130 | 130 | query(); |
| 131 | 131 | fail("expected a TransportException"); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +30 −5
| @@ -21,14 +21,18 @@ | ||
| 21 | 21 | import org.scassandra.Scassandra; |
| 22 | 22 | import org.scassandra.http.client.ClosedConnectionConfig; |
| 23 | 23 | import org.scassandra.http.client.PrimingRequest; |
| 24 | +import org.scassandra.http.client.Result; | |
| 25 | +import org.scassandra.http.client.UnavailableConfig; | |
| 26 | +import org.testng.Assert; | |
| 24 | 27 | import org.testng.annotations.Test; |
| 25 | 28 | |
| 26 | 29 | import java.util.Collections; |
| 27 | 30 | |
| 28 | 31 | import static org.assertj.core.api.Assertions.assertThat; |
| 29 | 32 | import static org.assertj.core.api.Assertions.fail; |
| 30 | -import static org.scassandra.http.client.PrimingRequest.Result.*; | |
| 33 | +import static org.scassandra.http.client.Consistency.LOCAL_SERIAL; | |
| 31 | 34 | import static org.scassandra.http.client.PrimingRequest.then; |
| 35 | +import static org.scassandra.http.client.Result.*; | |
| 32 | 36 | |
| 33 | 37 | public class DefaultRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { |
| 34 | 38 | public DefaultRetryPolicyIntegrationTest() { |
| @@ -202,7 +206,7 @@ | ||
| 202 | 206 | |
| 203 | 207 | |
| 204 | 208 | @Test(groups = "short", dataProvider = "serverSideErrors") |
| 205 | - public void should_try_next_host_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 209 | + public void should_try_next_host_on_server_side_error(Result error, Class<? extends DriverException> exception) { | |
| 206 | 210 | simulateError(1, error); |
| 207 | 211 | simulateError(2, error); |
| 208 | 212 | simulateError(3, error); |
| @@ -228,9 +232,9 @@ | ||
| 228 | 232 | |
| 229 | 233 | @Test(groups = "short", dataProvider = "connectionErrors") |
| 230 | 234 | public void should_try_next_host_on_connection_error(ClosedConnectionConfig.CloseType closeType) { |
| 231 | - simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 232 | - simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 233 | - simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 235 | + simulateError(1, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 236 | + simulateError(2, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 237 | + simulateError(3, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 234 | 238 | try { |
| 235 | 239 | query(); |
| 236 | 240 | Fail.fail("expected a NoHostAvailableException"); |
| @@ -250,4 +254,25 @@ | ||
| 250 | 254 | assertQueried(2, 1); |
| 251 | 255 | assertQueried(3, 1); |
| 252 | 256 | } |
| 257 | + | |
| 258 | + @Test(groups = "short") | |
| 259 | + public void should_rethrow_on_unavailable_if_CAS() { | |
| 260 | + simulateError(1, unavailable, new UnavailableConfig(1, 0, LOCAL_SERIAL)); | |
| 261 | + simulateError(2, unavailable, new UnavailableConfig(1, 0, LOCAL_SERIAL)); | |
| 262 | + | |
| 263 | + try { | |
| 264 | + query(); | |
| 265 | + Assert.fail("expected an UnavailableException"); | |
| 266 | + } catch (UnavailableException e) { | |
| 267 | + assertThat(e.getConsistencyLevel()).isEqualTo(ConsistencyLevel.LOCAL_SERIAL); | |
| 268 | + } | |
| 269 | + | |
| 270 | + assertOnUnavailableWasCalled(2); | |
| 271 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 272 | + assertThat(errors.getUnavailables().getCount()).isEqualTo(2); | |
| 273 | + assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1); | |
| 274 | + assertQueried(1, 1); | |
| 275 | + assertQueried(2, 1); | |
| 276 | + assertQueried(3, 0); | |
| 277 | + } | |
| 253 | 278 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +53 −5
| @@ -26,8 +26,9 @@ | ||
| 26 | 26 | import org.testng.annotations.Test; |
| 27 | 27 | |
| 28 | 28 | import static org.assertj.core.api.Assertions.assertThat; |
| 29 | -import static org.scassandra.http.client.PrimingRequest.Result.*; | |
| 29 | +import static org.scassandra.http.client.Consistency.SERIAL; | |
| 30 | 30 | import static org.scassandra.http.client.PrimingRequest.then; |
| 31 | +import static org.scassandra.http.client.Result.*; | |
| 31 | 32 | import static org.scassandra.http.client.WriteTypePrime.UNLOGGED_BATCH; |
| 32 | 33 | import static org.testng.Assert.fail; |
| 33 | 34 | |
| @@ -76,6 +77,32 @@ | ||
| 76 | 77 | }; |
| 77 | 78 | } |
| 78 | 79 | |
| 80 | + /** | |
| 81 | + * Ensures that when handling a read timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is | |
| 82 | + * reattempted with {@link ConsistencyLevel#ONE} if the consistency level on the statement executed is | |
| 83 | + * {@link ConsistencyLevel#EACH_QUORUM}, even if the number of known alive replicas was 0. | |
| 84 | + * | |
| 85 | + * @jira_ticket JAVA-1005 | |
| 86 | + * @test_category retry_policy | |
| 87 | + */ | |
| 88 | + @Test(groups = "short") | |
| 89 | + public void should_retry_once_on_same_host_from_each_quorum_to_one() { | |
| 90 | + simulateError(1, read_request_timeout, new ReadTimeoutConfig(0, 3, false)); | |
| 91 | + | |
| 92 | + try { | |
| 93 | + queryWithCL(ConsistencyLevel.EACH_QUORUM); | |
| 94 | + } catch (ReadTimeoutException e) { | |
| 95 | + assertThat(e.getConsistencyLevel()).isEqualTo(ConsistencyLevel.ONE); | |
| 96 | + } | |
| 97 | + | |
| 98 | + assertOnReadTimeoutWasCalled(2); | |
| 99 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 100 | + assertThat(errors.getReadTimeouts().getCount()).isEqualTo(2); | |
| 101 | + assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(1); | |
| 102 | + assertQueried(1, 2); | |
| 103 | + assertQueried(2, 0); | |
| 104 | + assertQueried(3, 0); | |
| 105 | + } | |
| 79 | 106 | |
| 80 | 107 | /** |
| 81 | 108 | * Ensures that when handling a read timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is |
| @@ -384,7 +411,7 @@ | ||
| 384 | 411 | * @test_category retry_policy |
| 385 | 412 | */ |
| 386 | 413 | @Test(groups = "short", dataProvider = "serverSideErrors") |
| 387 | - public void should_try_next_host_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 414 | + public void should_try_next_host_on_server_side_error(Result error, Class<? extends DriverException> exception) { | |
| 388 | 415 | simulateError(1, error); |
| 389 | 416 | simulateError(2, error); |
| 390 | 417 | simulateError(3, error); |
| @@ -416,9 +443,9 @@ | ||
| 416 | 443 | */ |
| 417 | 444 | @Test(groups = "short", dataProvider = "connectionErrors") |
| 418 | 445 | public void should_try_next_host_on_connection_error(ClosedConnectionConfig.CloseType closeType) { |
| 419 | - simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 420 | - simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 421 | - simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 446 | + simulateError(1, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 447 | + simulateError(2, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 448 | + simulateError(3, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 422 | 449 | try { |
| 423 | 450 | query(); |
| 424 | 451 | Fail.fail("expected a TransportException"); |
| @@ -438,4 +465,25 @@ | ||
| 438 | 465 | assertQueried(2, 1); |
| 439 | 466 | assertQueried(3, 1); |
| 440 | 467 | } |
| 468 | + | |
| 469 | + @Test(groups = "short") | |
| 470 | + public void should_rethrow_on_unavailable_if_CAS() { | |
| 471 | + simulateError(1, unavailable, new UnavailableConfig(1, 0, SERIAL)); | |
| 472 | + simulateError(2, unavailable, new UnavailableConfig(1, 0, SERIAL)); | |
| 473 | + | |
| 474 | + try { | |
| 475 | + query(); | |
| 476 | + fail("expected an UnavailableException"); | |
| 477 | + } catch (UnavailableException e) { | |
| 478 | + assertThat(e.getConsistencyLevel()).isEqualTo(ConsistencyLevel.SERIAL); | |
| 479 | + } | |
| 480 | + | |
| 481 | + assertOnUnavailableWasCalled(2); | |
| 482 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 483 | + assertThat(errors.getUnavailables().getCount()).isEqualTo(2); | |
| 484 | + assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1); | |
| 485 | + assertQueried(1, 1); | |
| 486 | + assertQueried(2, 1); | |
| 487 | + assertQueried(3, 0); | |
| 488 | + } | |
| 441 | 489 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +6 −4
| @@ -19,13 +19,15 @@ | ||
| 19 | 19 | import com.datastax.driver.core.exceptions.*; |
| 20 | 20 | import org.assertj.core.api.Fail; |
| 21 | 21 | import org.scassandra.http.client.ClosedConnectionConfig; |
| 22 | +import org.scassandra.http.client.ClosedConnectionConfig.CloseType; | |
| 22 | 23 | import org.scassandra.http.client.PrimingRequest; |
| 24 | +import org.scassandra.http.client.Result; | |
| 23 | 25 | import org.testng.annotations.Test; |
| 24 | 26 | |
| 25 | 27 | import static org.assertj.core.api.Assertions.assertThat; |
| 26 | 28 | import static org.assertj.core.api.Assertions.fail; |
| 27 | -import static org.scassandra.http.client.PrimingRequest.Result.*; | |
| 28 | 29 | import static org.scassandra.http.client.PrimingRequest.then; |
| 30 | +import static org.scassandra.http.client.Result.*; | |
| 29 | 31 | |
| 30 | 32 | public class FallthroughRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { |
| 31 | 33 | public FallthroughRetryPolicyIntegrationTest() { |
| @@ -111,7 +113,7 @@ | ||
| 111 | 113 | |
| 112 | 114 | |
| 113 | 115 | @Test(groups = "short", dataProvider = "serverSideErrors") |
| 114 | - public void should_rethrow_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 116 | + public void should_rethrow_on_server_side_error(Result error, Class<? extends DriverException> exception) { | |
| 115 | 117 | simulateError(1, error); |
| 116 | 118 | try { |
| 117 | 119 | query(); |
| @@ -130,8 +132,8 @@ | ||
| 130 | 132 | |
| 131 | 133 | |
| 132 | 134 | @Test(groups = "short", dataProvider = "connectionErrors") |
| 133 | - public void should_rethrow_on_connection_error(ClosedConnectionConfig.CloseType closeType) { | |
| 134 | - simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 135 | + public void should_rethrow_on_connection_error(CloseType closeType) { | |
| 136 | + simulateError(1, Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 135 | 137 | try { |
| 136 | 138 | query(); |
| 137 | 139 | Fail.fail("expected a TransportException"); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java +11 −9
| @@ -20,13 +20,15 @@ | ||
| 20 | 20 | import org.assertj.core.api.Fail; |
| 21 | 21 | import org.scassandra.http.client.ClosedConnectionConfig; |
| 22 | 22 | import org.scassandra.http.client.PrimingRequest; |
| 23 | +import org.scassandra.http.client.Result; | |
| 23 | 24 | import org.testng.annotations.BeforeMethod; |
| 24 | 25 | import org.testng.annotations.Test; |
| 25 | 26 | |
| 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; |
| 27 | 28 | import static org.assertj.core.api.Assertions.fail; |
| 28 | -import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout; | |
| 29 | 29 | import static org.scassandra.http.client.PrimingRequest.then; |
| 30 | +import static org.scassandra.http.client.Result.closed_connection; | |
| 31 | +import static org.scassandra.http.client.Result.write_request_timeout; | |
| 30 | 32 | |
| 31 | 33 | /** |
| 32 | 34 | * Integration test with an IdempotenceAwareRetryPolicy. |
| @@ -124,7 +126,7 @@ | ||
| 124 | 126 | |
| 125 | 127 | |
| 126 | 128 | @Test(groups = "short", dataProvider = "serverSideErrors") |
| 127 | - public void should_not_retry_on_server_error_if_statement_non_idempotent(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 129 | + public void should_not_retry_on_server_error_if_statement_non_idempotent(Result error, Class<? extends DriverException> exception) { | |
| 128 | 130 | simulateError(1, error); |
| 129 | 131 | try { |
| 130 | 132 | query(); |
| @@ -143,7 +145,7 @@ | ||
| 143 | 145 | |
| 144 | 146 | @SuppressWarnings("UnusedParameters") |
| 145 | 147 | @Test(groups = "short", dataProvider = "serverSideErrors") |
| 146 | - public void should_retry_on_server_error_if_statement_idempotent(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 148 | + public void should_retry_on_server_error_if_statement_idempotent(Result error, Class<? extends DriverException> exception) { | |
| 147 | 149 | simulateError(1, error); |
| 148 | 150 | simulateError(2, error); |
| 149 | 151 | simulateError(3, error); |
| @@ -169,9 +171,9 @@ | ||
| 169 | 171 | |
| 170 | 172 | @Test(groups = "short", dataProvider = "connectionErrors") |
| 171 | 173 | public void should_not_retry_on_connection_error_if_statement_non_idempotent(ClosedConnectionConfig.CloseType closeType) { |
| 172 | - simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 173 | - simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 174 | - simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 174 | + simulateError(1, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 175 | + simulateError(2, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 176 | + simulateError(3, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 175 | 177 | try { |
| 176 | 178 | query(); |
| 177 | 179 | Fail.fail("expected a TransportException"); |
| @@ -193,9 +195,9 @@ | ||
| 193 | 195 | |
| 194 | 196 | @Test(groups = "short", dataProvider = "connectionErrors") |
| 195 | 197 | public void should_retry_on_connection_error_if_statement_idempotent(ClosedConnectionConfig.CloseType closeType) { |
| 196 | - simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 197 | - simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 198 | - simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 198 | + simulateError(1, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 199 | + simulateError(2, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 200 | + simulateError(3, closed_connection, new ClosedConnectionConfig(closeType)); | |
| 199 | 201 | try { |
| 200 | 202 | session.execute(new SimpleStatement("mock query").setIdempotent(true)); |
| 201 | 203 | Fail.fail("expected a TransportException"); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java +2 −2
| @@ -26,9 +26,9 @@ | ||
| 26 | 26 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 27 | 27 | import static org.assertj.core.api.Assertions.assertThat; |
| 28 | 28 | import static org.assertj.core.api.Assertions.fail; |
| 29 | -import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout; | |
| 30 | -import static org.scassandra.http.client.PrimingRequest.Result.unavailable; | |
| 31 | 29 | import static org.scassandra.http.client.PrimingRequest.queryBuilder; |
| 30 | +import static org.scassandra.http.client.Result.read_request_timeout; | |
| 31 | +import static org.scassandra.http.client.Result.unavailable; | |
| 32 | 32 | |
| 33 | 33 | public class LatencyAwarePolicyTest extends ScassandraTestBase { |
| 34 | 34 |
modified driver-core/src/test/java/com/datastax/driver/core/policies/LoggingRetryPolicyIntegrationTest.java +1 −1
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.ignore; |
| 34 | 34 | import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.tryNextHost; |
| 35 | 35 | import static org.apache.log4j.Level.INFO; |
| 36 | -import static org.scassandra.http.client.PrimingRequest.Result.*; | |
| 36 | +import static org.scassandra.http.client.Result.*; | |
| 37 | 37 | |
| 38 | 38 | /** |
| 39 | 39 | * Integration tests with LoggingRetryPolicy. |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +119 −1
| @@ -16,6 +16,8 @@ | ||
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 20 | +import org.assertj.core.api.iterable.Extractor; | |
| 19 | 21 | import org.testng.annotations.Test; |
| 20 | 22 | |
| 21 | 23 | import java.util.Date; |
| @@ -24,6 +26,7 @@ | ||
| 24 | 26 | import java.util.Set; |
| 25 | 27 | |
| 26 | 28 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 29 | +import static com.datastax.driver.core.schemabuilder.SchemaBuilder.createTable; | |
| 27 | 30 | import static org.assertj.core.api.Assertions.assertThat; |
| 28 | 31 | import static org.assertj.core.data.MapEntry.entry; |
| 29 | 32 | import static org.testng.Assert.*; |
| @@ -31,13 +34,20 @@ | ||
| 31 | 34 | public class QueryBuilderExecutionTest extends CCMTestsSupport { |
| 32 | 35 | |
| 33 | 36 | private static final String TABLE1 = "test1"; |
| 37 | + private static final String TABLE2 = "test2"; | |
| 34 | 38 | |
| 35 | 39 | @Override |
| 36 | 40 | public void onTestContextInitialized() { |
| 37 | 41 | execute( |
| 38 | 42 | String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE1), |
| 43 | + String.format("CREATE TABLE %s (k text, t text, i int, f float, PRIMARY KEY (k, t))", TABLE2), | |
| 39 | 44 | "CREATE TABLE dateTest (t timestamp PRIMARY KEY)", |
| 40 | - "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)"); | |
| 45 | + "CREATE TABLE test_coll (k int PRIMARY KEY, a list<int>, b map<int,text>, c set<text>)", | |
| 46 | + insertInto(TABLE2).value("k", "cast_t").value("t", "a").value("i", 1).value("f", 1.1).toString(), | |
| 47 | + insertInto(TABLE2).value("k", "cast_t").value("t", "b").value("i", 2).value("f", 2.5).toString(), | |
| 48 | + insertInto(TABLE2).value("k", "cast_t").value("t", "c").value("i", 3).value("f", 3.7).toString(), | |
| 49 | + insertInto(TABLE2).value("k", "cast_t").value("t", "d").value("i", 4).value("f", 5.0).toString() | |
| 50 | + ); | |
| 41 | 51 | } |
| 42 | 52 | |
| 43 | 53 | @Test(groups = "short") |
| @@ -182,4 +192,112 @@ | ||
| 182 | 192 | assertThat(actual).containsExactly(entry(2, "bar")); |
| 183 | 193 | } |
| 184 | 194 | |
| 195 | + /** | |
| 196 | + * Validates that {@link QueryBuilder} may be used to create a query that casts a column from one type to another, | |
| 197 | + * i.e.: | |
| 198 | + * <p/> | |
| 199 | + * <code>select CAST(f as int) as fint, i from table2 where k='cast_t'</code> | |
| 200 | + * <p/> | |
| 201 | + * and validates that the query executes successfully with the anticipated results. | |
| 202 | + * | |
| 203 | + * @jira_ticket JAVA-1086 | |
| 204 | + * @test_category queries:builder | |
| 205 | + * @since 3.0.1 | |
| 206 | + */ | |
| 207 | + @Test(groups = "short") | |
| 208 | + @CassandraVersion(major = 3.2) | |
| 209 | + public void should_support_cast_function_on_column() { | |
| 210 | + //when | |
| 211 | + ResultSet r = session().execute(select().cast("f", DataType.cint()).as("fint").column("i").from(TABLE2).where(eq("k", "cast_t"))); | |
| 212 | + //then | |
| 213 | + assertThat(r.getAvailableWithoutFetching()).isEqualTo(4); | |
| 214 | + for (Row row : r) { | |
| 215 | + Integer i = row.getInt("i"); | |
| 216 | + assertThat(row.getColumnDefinitions().getType("fint")).isEqualTo(DataType.cint()); | |
| 217 | + Integer f = row.getInt("fint"); | |
| 218 | + switch (i) { | |
| 219 | + case 1: | |
| 220 | + assertThat(f).isEqualTo(1); | |
| 221 | + break; | |
| 222 | + case 2: | |
| 223 | + assertThat(f).isEqualTo(2); | |
| 224 | + break; | |
| 225 | + case 3: | |
| 226 | + assertThat(f).isEqualTo(3); | |
| 227 | + break; | |
| 228 | + case 4: | |
| 229 | + assertThat(f).isEqualTo(5); | |
| 230 | + break; | |
| 231 | + default: | |
| 232 | + fail("Unexpected values: " + i + "," + f); | |
| 233 | + } | |
| 234 | + } | |
| 235 | + } | |
| 236 | + | |
| 237 | + /** | |
| 238 | + * Validates that {@link QueryBuilder} may be used to create a query that makes an aggregate function call, casting | |
| 239 | + * the column(s) that the function operates on from one type to another. | |
| 240 | + * i.e.: | |
| 241 | + * <p/> | |
| 242 | + * <code>select avg(CAST(i as float)) as iavg from table2 where k='cast_t'</code> | |
| 243 | + * <p/> | |
| 244 | + * and validates that the query executes successfully with the anticipated results. | |
| 245 | + * | |
| 246 | + * @jira_ticket JAVA-1086 | |
| 247 | + * @test_category queries:builder | |
| 248 | + * @since 3.0.1 | |
| 249 | + */ | |
| 250 | + @Test(groups = "short") | |
| 251 | + @CassandraVersion(major = 3.2) | |
| 252 | + public void should_support_fcall_on_cast_column() { | |
| 253 | + //when | |
| 254 | + ResultSet ar = session().execute(select().fcall("avg", cast(column("i"), DataType.cfloat())).as("iavg").from(TABLE2).where(eq("k", "cast_t"))); | |
| 255 | + //then | |
| 256 | + assertThat(ar.getAvailableWithoutFetching()).isEqualTo(1); | |
| 257 | + Row row = ar.one(); | |
| 258 | + assertThat(row.getColumnDefinitions().getType("iavg")).isEqualTo(DataType.cfloat()); | |
| 259 | + Float f = row.getFloat("iavg"); | |
| 260 | + // (1.0+2.0+3.0+4.0) / 4 = 2.5 | |
| 261 | + assertThat(f).isEqualTo(2.5f); | |
| 262 | + } | |
| 263 | + | |
| 264 | + /** | |
| 265 | + * Validates that {@link QueryBuilder} can construct a query using the 'LIKE' operator to retrieve data from a | |
| 266 | + * table on a column that has a SASI index, i.e.: | |
| 267 | + * <p/> | |
| 268 | + * <code>select n from s_table where n like 'Hello%'</code> | |
| 269 | + * <p/> | |
| 270 | + * | |
| 271 | + * @test_category queries:builder | |
| 272 | + * @jira_ticket JAVA-1113 | |
| 273 | + * @since 3.0.1 | |
| 274 | + */ | |
| 275 | + @Test(groups = "short") | |
| 276 | + @CassandraVersion(major = 3.6) | |
| 277 | + public void should_retrieve_using_like_operator_on_table_with_sasi_index() { | |
| 278 | + //given | |
| 279 | + String table = "s_table"; | |
| 280 | + session().execute(createTable(table).addPartitionKey("k", DataType.text()) | |
| 281 | + .addClusteringColumn("cc", DataType.cint()) | |
| 282 | + .addColumn("n", DataType.text()) | |
| 283 | + ); | |
| 284 | + session().execute(String.format( | |
| 285 | + "CREATE CUSTOM INDEX on %s (n) USING 'org.apache.cassandra.index.sasi.SASIIndex';", table)); | |
| 286 | + session().execute(insertInto(table).value("k", "a").value("cc", 0).value("n", "Hello World")); | |
| 287 | + session().execute(insertInto(table).value("k", "a").value("cc", 1).value("n", "Goodbye World")); | |
| 288 | + session().execute(insertInto(table).value("k", "b").value("cc", 2).value("n", "Hello Moon")); | |
| 289 | + | |
| 290 | + //when | |
| 291 | + BuiltStatement query = select("n").from(table).where(like("n", "Hello%")); | |
| 292 | + ResultSet r = session().execute(query); | |
| 293 | + | |
| 294 | + //then | |
| 295 | + assertThat(r.getAvailableWithoutFetching()).isEqualTo(2); | |
| 296 | + assertThat(r.all()).extracting(new Extractor<Row, String>() { | |
| 297 | + @Override | |
| 298 | + public String extract(Row input) { | |
| 299 | + return input.getString("n"); | |
| 300 | + } | |
| 301 | + }).containsOnly("Hello World", "Hello Moon"); | |
| 302 | + } | |
| 185 | 303 | } |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +81 −15
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | 19 | import com.datastax.driver.core.exceptions.CodecNotFoundException; |
| 20 | 20 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 21 | +import com.datastax.driver.core.exceptions.InvalidTypeException; | |
| 21 | 22 | import com.datastax.driver.core.utils.Bytes; |
| 22 | 23 | import com.datastax.driver.core.utils.CassandraVersion; |
| 23 | 24 | import com.google.common.collect.ImmutableList; |
| @@ -26,14 +27,19 @@ | ||
| 26 | 27 | import com.google.common.collect.Sets; |
| 27 | 28 | import org.testng.annotations.Test; |
| 28 | 29 | |
| 30 | +import java.io.PrintWriter; | |
| 31 | +import java.io.StringWriter; | |
| 29 | 32 | import java.math.BigDecimal; |
| 30 | 33 | import java.math.BigInteger; |
| 31 | 34 | import java.net.InetAddress; |
| 35 | +import java.nio.ByteBuffer; | |
| 32 | 36 | import java.util.*; |
| 33 | 37 | |
| 34 | 38 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 35 | 39 | import static org.assertj.core.api.Assertions.assertThat; |
| 36 | -import static org.testng.Assert.*; | |
| 40 | +import static org.assertj.core.api.Assertions.fail; | |
| 41 | +import static org.testng.Assert.assertEquals; | |
| 42 | +import static org.testng.Assert.assertTrue; | |
| 37 | 43 | |
| 38 | 44 | public class QueryBuilderTest { |
| 39 | 45 | |
| @@ -137,37 +143,53 @@ | ||
| 137 | 143 | select = select().from("foo").where(containsKey("e", "key1")); |
| 138 | 144 | assertEquals(select.toString(), query); |
| 139 | 145 | |
| 146 | + query = "SELECT CAST(writetime(country) AS text) FROM artists LIMIT 2;"; | |
| 147 | + select = select().cast(fcall("writetime", column("country")), DataType.text()).from("artists").limit(2); | |
| 148 | + assertEquals(select.toString(), query); | |
| 149 | + | |
| 150 | + query = "SELECT avg(CAST(v AS float)) FROM e;"; | |
| 151 | + select = select().fcall("avg", cast(column("v"), DataType.cfloat())).from("e"); | |
| 152 | + assertEquals(select.toString(), query); | |
| 153 | + | |
| 154 | + query = "SELECT CAST(writetime(country) AS text) FROM artists LIMIT 2;"; | |
| 155 | + select = select().raw("CAST(writetime(country) AS text)").from("artists").limit(2); | |
| 156 | + assertEquals(select.toString(), query); | |
| 157 | + | |
| 158 | + query = "SELECT * FROM foo WHERE e LIKE 'a%';"; | |
| 159 | + select = select().from("foo").where(like("e", "a%")); | |
| 160 | + assertEquals(select.toString(), query); | |
| 161 | + | |
| 140 | 162 | try { |
| 141 | 163 | select().countAll().from("foo").orderBy(asc("a"), desc("b")).orderBy(asc("a"), desc("b")); |
| 142 | - fail(); | |
| 164 | + fail("Expected an IllegalStateException"); | |
| 143 | 165 | } catch (IllegalStateException e) { |
| 144 | 166 | assertEquals(e.getMessage(), "An ORDER BY clause has already been provided"); |
| 145 | 167 | } |
| 146 | 168 | |
| 147 | 169 | try { |
| 148 | 170 | select().column("a").all().from("foo"); |
| 149 | - fail(); | |
| 171 | + fail("Expected an IllegalStateException"); | |
| 150 | 172 | } catch (IllegalStateException e) { |
| 151 | 173 | assertEquals(e.getMessage(), "Some columns ([a]) have already been selected."); |
| 152 | 174 | } |
| 153 | 175 | |
| 154 | 176 | try { |
| 155 | 177 | select().column("a").countAll().from("foo"); |
| 156 | - fail(); | |
| 178 | + fail("Expected an IllegalStateException"); | |
| 157 | 179 | } catch (IllegalStateException e) { |
| 158 | 180 | assertEquals(e.getMessage(), "Some columns ([a]) have already been selected."); |
| 159 | 181 | } |
| 160 | 182 | |
| 161 | 183 | try { |
| 162 | 184 | select().all().from("foo").limit(-42); |
| 163 | - fail(); | |
| 185 | + fail("Expected an IllegalArgumentException"); | |
| 164 | 186 | } catch (IllegalArgumentException e) { |
| 165 | 187 | assertEquals(e.getMessage(), "Invalid LIMIT value, must be strictly positive"); |
| 166 | 188 | } |
| 167 | 189 | |
| 168 | 190 | try { |
| 169 | 191 | select().all().from("foo").limit(42).limit(42); |
| 170 | - fail(); | |
| 192 | + fail("Expected an IllegalStateException"); | |
| 171 | 193 | } catch (IllegalStateException e) { |
| 172 | 194 | assertEquals(e.getMessage(), "A LIMIT value has already been provided"); |
| 173 | 195 | } |
| @@ -243,7 +265,7 @@ | ||
| 243 | 265 | |
| 244 | 266 | try { |
| 245 | 267 | insertInto("foo").values(new String[]{"a", "b"}, new Object[]{1, 2, 3}); |
| 246 | - fail(); | |
| 268 | + fail("Expected an IllegalArgumentException"); | |
| 247 | 269 | } catch (IllegalArgumentException e) { |
| 248 | 270 | assertEquals(e.getMessage(), "Got 2 names but 3 values"); |
| 249 | 271 | } |
| @@ -323,7 +345,7 @@ | ||
| 323 | 345 | |
| 324 | 346 | try { |
| 325 | 347 | update("foo").using(ttl(-400)); |
| 326 | - fail(); | |
| 348 | + fail("Expected an IllegalArgumentException"); | |
| 327 | 349 | } catch (IllegalArgumentException e) { |
| 328 | 350 | assertEquals(e.getMessage(), "Invalid ttl, must be positive"); |
| 329 | 351 | } |
| @@ -377,14 +399,14 @@ | ||
| 377 | 399 | |
| 378 | 400 | try { |
| 379 | 401 | delete().column("a").all().from("foo"); |
| 380 | - fail(); | |
| 402 | + fail("Expected an IllegalStateException"); | |
| 381 | 403 | } catch (IllegalStateException e) { |
| 382 | 404 | assertEquals(e.getMessage(), "Some columns ([a]) have already been selected."); |
| 383 | 405 | } |
| 384 | 406 | |
| 385 | 407 | try { |
| 386 | 408 | delete().from("foo").using(timestamp(-1240003134L)); |
| 387 | - fail(); | |
| 409 | + fail("Expected an IllegalArgumentException"); | |
| 388 | 410 | } catch (IllegalArgumentException e) { |
| 389 | 411 | assertEquals(e.getMessage(), "Invalid timestamp, must be positive"); |
| 390 | 412 | } |
| @@ -749,6 +771,10 @@ | ||
| 749 | 771 | String query; |
| 750 | 772 | Statement select; |
| 751 | 773 | |
| 774 | + query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)=('a',2);"; | |
| 775 | + select = select().all().from("foo").where(eq("k", 4)).and(eq(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2))); | |
| 776 | + assertEquals(select.toString(), query); | |
| 777 | + | |
| 752 | 778 | query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)>('a',2);"; |
| 753 | 779 | select = select().all().from("foo").where(eq("k", 4)).and(gt(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2))); |
| 754 | 780 | assertEquals(select.toString(), query); |
| @@ -761,6 +787,22 @@ | ||
| 761 | 787 | query = "SELECT * FROM foo WHERE k=4 AND (c1,c2)<=('a',2);"; |
| 762 | 788 | select = select().all().from("foo").where(eq("k", 4)).and(lte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2))); |
| 763 | 789 | assertEquals(select.toString(), query); |
| 790 | + | |
| 791 | + query = "SELECT * FROM foo WHERE k=4 AND (c1,c2) IN ((1,2),('foo','bar'));"; | |
| 792 | + List<String> names = ImmutableList.of("c1", "c2"); | |
| 793 | + List<List<?>> values = ImmutableList.<List<?>>of( | |
| 794 | + ImmutableList.of(1, 2), | |
| 795 | + ImmutableList.of("foo", "bar")); | |
| 796 | + select = select().all().from("foo").where(eq("k", 4)).and(in(names, values)); | |
| 797 | + assertEquals(select.toString(), query); | |
| 798 | + | |
| 799 | + query = "SELECT * FROM foo WHERE k=4 AND (c1,c2) IN ((1,2),?);"; | |
| 800 | + names = ImmutableList.of("c1", "c2"); | |
| 801 | + values = ImmutableList.<List<?>>of( | |
| 802 | + ImmutableList.of(1, 2), | |
| 803 | + ImmutableList.of(bindMarker())); | |
| 804 | + select = select().all().from("foo").where(eq("k", 4)).and(in(names, values)); | |
| 805 | + assertEquals(select.toString(), query); | |
| 764 | 806 | } |
| 765 | 807 | |
| 766 | 808 | @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class) |
| @@ -850,7 +892,7 @@ | ||
| 850 | 892 | public void should_quote_column_names_with_escaped_quotes() { |
| 851 | 893 | // A column name can include quotes as long as it is escaped with another set of quotes, so "foo""bar" is a valid name. |
| 852 | 894 | String query = "SELECT * FROM foo WHERE \"foo \"\" bar\"=1;"; |
| 853 | - Statement statement = select().from("foo").where(eq(quote("foo \"\" bar"), 1)); | |
| 895 | + Statement statement = select().from("foo").where(eq(quote("foo \" bar"), 1)); | |
| 854 | 896 | |
| 855 | 897 | assertThat(statement.toString()).isEqualTo(query); |
| 856 | 898 | } |
| @@ -880,7 +922,6 @@ | ||
| 880 | 922 | } |
| 881 | 923 | |
| 882 | 924 | @Test(groups = "unit") |
| 883 | - @CassandraVersion(major = 2.1) | |
| 884 | 925 | public void should_serialize_collections_of_serializable_elements() { |
| 885 | 926 | Set<UUID> set = Sets.newHashSet(UUID.randomUUID()); |
| 886 | 927 | List<Date> list = Lists.newArrayList(new Date()); |
| @@ -897,7 +938,6 @@ | ||
| 897 | 938 | } |
| 898 | 939 | |
| 899 | 940 | @Test(groups = "unit") |
| 900 | - @CassandraVersion(major = 2.1) | |
| 901 | 941 | public void should_not_attempt_to_serialize_function_calls_in_collections() { |
| 902 | 942 | BuiltStatement query = insertInto("foo").value("v", Sets.newHashSet(fcall("func", 1))); |
| 903 | 943 | assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES ({func(1)});"); |
| @@ -905,7 +945,13 @@ | ||
| 905 | 945 | } |
| 906 | 946 | |
| 907 | 947 | @Test(groups = "unit") |
| 908 | - @CassandraVersion(major = 2.1) | |
| 948 | + public void should_not_attempt_to_serialize_bind_markers_in_collections() { | |
| 949 | + BuiltStatement query = insertInto("foo").value("v", Lists.newArrayList(1, 2, bindMarker())); | |
| 950 | + assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES ([1,2,?]);"); | |
| 951 | + assertThat(query.getValues(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)).isNullOrEmpty(); | |
| 952 | + } | |
| 953 | + | |
| 954 | + @Test(groups = "unit") | |
| 909 | 955 | public void should_not_attempt_to_serialize_raw_values_in_collections() { |
| 910 | 956 | BuiltStatement query = insertInto("foo").value("v", ImmutableMap.of(1, raw("x"))); |
| 911 | 957 | assertThat(query.getQueryString()).isEqualTo("INSERT INTO foo (v) VALUES ({1:x});"); |
| @@ -913,7 +959,6 @@ | ||
| 913 | 959 | } |
| 914 | 960 | |
| 915 | 961 | @Test(groups = "unit") |
| 916 | - @CassandraVersion(major = 2.1) | |
| 917 | 962 | public void should_not_attempt_to_serialize_collections_containing_numbers() { |
| 918 | 963 | BuiltStatement query; |
| 919 | 964 | // lists |
| @@ -933,4 +978,25 @@ | ||
| 933 | 978 | assertThat(query.hasValues()).isFalse(); |
| 934 | 979 | } |
| 935 | 980 | |
| 981 | + @Test(groups = "unit") | |
| 982 | + public void should_include_original_cause_when_arguments_invalid() { | |
| 983 | + // Collection elements in protocol v2 must be at most 65535 bytes | |
| 984 | + ByteBuffer bb = ByteBuffer.allocate(65536); // too big | |
| 985 | + List<ByteBuffer> value = Lists.newArrayList(bb); | |
| 986 | + | |
| 987 | + BuiltStatement s = insertInto("foo").value("l", value); | |
| 988 | + try { | |
| 989 | + s.getValues(ProtocolVersion.V2, CodecRegistry.DEFAULT_INSTANCE); | |
| 990 | + fail("Expected an IllegalArgumentException"); | |
| 991 | + } catch (InvalidTypeException e) { | |
| 992 | + assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); | |
| 993 | + StringWriter writer = new StringWriter(); | |
| 994 | + e.getCause().printStackTrace(new PrintWriter(writer)); | |
| 995 | + String stackTrace = writer.toString(); | |
| 996 | + assertThat(stackTrace).contains( | |
| 997 | + "Native protocol version 2 supports only elements with size up to 65535 bytes - " + | |
| 998 | + "but element size is 65536 bytes"); | |
| 999 | + } | |
| 1000 | + } | |
| 1001 | + | |
| 936 | 1002 | } |
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTest.java +12 −12
| @@ -545,54 +545,54 @@ | ||
| 545 | 545 | } |
| 546 | 546 | |
| 547 | 547 | @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, |
| 548 | - expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword") | |
| 548 | + expectedExceptionsMessageRegExp = "The keyspace name 'ADD' is not allowed because it is a reserved keyword") | |
| 549 | 549 | public void should_fail_if_keyspace_name_is_a_reserved_keyword() throws Exception { |
| 550 | - createTable("add", "test") | |
| 550 | + createTable("ADD", "test") | |
| 551 | 551 | .addPartitionKey("pk", DataType.bigint()) |
| 552 | 552 | .addColumn("col", DataType.text()).getQueryString(); |
| 553 | 553 | } |
| 554 | 554 | |
| 555 | 555 | @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, |
| 556 | - expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword") | |
| 556 | + expectedExceptionsMessageRegExp = "The table name 'ADD' is not allowed because it is a reserved keyword") | |
| 557 | 557 | public void should_fail_if_table_name_is_a_reserved_keyword() throws Exception { |
| 558 | - createTable("add") | |
| 558 | + createTable("ADD") | |
| 559 | 559 | .addPartitionKey("pk", DataType.bigint()) |
| 560 | 560 | .addColumn("col", DataType.text()).getQueryString(); |
| 561 | 561 | } |
| 562 | 562 | |
| 563 | 563 | @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, |
| 564 | - expectedExceptionsMessageRegExp = "The partition key name 'add' is not allowed because it is a reserved keyword") | |
| 564 | + expectedExceptionsMessageRegExp = "The partition key name 'ADD' is not allowed because it is a reserved keyword") | |
| 565 | 565 | public void should_fail_if_partition_key_is_a_reserved_keyword() throws Exception { |
| 566 | 566 | createTable("test") |
| 567 | - .addPartitionKey("add", DataType.bigint()) | |
| 567 | + .addPartitionKey("ADD", DataType.bigint()) | |
| 568 | 568 | .addColumn("col", DataType.text()).getQueryString(); |
| 569 | 569 | } |
| 570 | 570 | |
| 571 | 571 | @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, |
| 572 | - expectedExceptionsMessageRegExp = "The clustering column name 'add' is not allowed because it is a reserved keyword") | |
| 572 | + expectedExceptionsMessageRegExp = "The clustering column name 'ADD' is not allowed because it is a reserved keyword") | |
| 573 | 573 | public void should_fail_if_clustering_key_is_a_reserved_keyword() throws Exception { |
| 574 | 574 | createTable("test") |
| 575 | 575 | .addPartitionKey("pk", DataType.bigint()) |
| 576 | - .addClusteringColumn("add", DataType.uuid()) | |
| 576 | + .addClusteringColumn("ADD", DataType.uuid()) | |
| 577 | 577 | .addColumn("col", DataType.text()).getQueryString(); |
| 578 | 578 | } |
| 579 | 579 | |
| 580 | 580 | @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, |
| 581 | - expectedExceptionsMessageRegExp = "The column name 'add' is not allowed because it is a reserved keyword") | |
| 581 | + expectedExceptionsMessageRegExp = "The column name 'ADD' is not allowed because it is a reserved keyword") | |
| 582 | 582 | public void should_fail_if_simple_column_is_a_reserved_keyword() throws Exception { |
| 583 | 583 | createTable("test") |
| 584 | 584 | .addPartitionKey("pk", DataType.bigint()) |
| 585 | 585 | .addClusteringColumn("cluster", DataType.uuid()) |
| 586 | - .addColumn("add", DataType.text()).getQueryString(); | |
| 586 | + .addColumn("ADD", DataType.text()).getQueryString(); | |
| 587 | 587 | } |
| 588 | 588 | |
| 589 | 589 | @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, |
| 590 | - expectedExceptionsMessageRegExp = "The static column name 'add' is not allowed because it is a reserved keyword") | |
| 590 | + expectedExceptionsMessageRegExp = "The static column name 'ADD' is not allowed because it is a reserved keyword") | |
| 591 | 591 | public void should_fail_if_static_column_is_a_reserved_keyword() throws Exception { |
| 592 | 592 | createTable("test") |
| 593 | 593 | .addPartitionKey("pk", DataType.bigint()) |
| 594 | 594 | .addClusteringColumn("cluster", DataType.uuid()) |
| 595 | - .addStaticColumn("add", DataType.text()) | |
| 595 | + .addStaticColumn("ADD", DataType.text()) | |
| 596 | 596 | .addColumn("col", DataType.text()).getQueryString(); |
| 597 | 597 | } |
| 598 | 598 |
added driver-examples/README.md +10 −0
| @@ -0,0 +1,10 @@ | ||
| 1 | +# DataStax Java Driver for Apache Cassandra - Examples | |
| 2 | + | |
| 3 | +This module contains examples of how to use the DataStax Java driver for | |
| 4 | +Apache Cassandra. | |
| 5 | + | |
| 6 | +## Usage | |
| 7 | + | |
| 8 | +Unless otherwise stated, all examples assume that you have a single-node Cassandra 3.0 cluster | |
| 9 | +listening on localhost:9042. | |
| 10 | + |
deleted driver-examples/osgi/README.md +0 −30
| @@ -1,30 +0,0 @@ | ||
| 1 | -# OSGi Example | |
| 2 | - | |
| 3 | -A simple example application that demonstrates using the Java Driver in | |
| 4 | -an OSGi service. | |
| 5 | - | |
| 6 | -MailboxService is an activated service that uses Cassandra to | |
| 7 | -persist a Mailbox by email address. | |
| 8 | - | |
| 9 | -## Usage | |
| 10 | - | |
| 11 | -To build the bundle and run tests execute the following maven task:: | |
| 12 | - | |
| 13 | - mvn integration-test -P short | |
| 14 | - | |
| 15 | -The short profile needs to be activated since the tests run under | |
| 16 | -this group. | |
| 17 | - | |
| 18 | -After which the bundle jar will be present in the target/ directory. | |
| 19 | - | |
| 20 | -The project includes an integration test that verifies the service can | |
| 21 | -be activated and used in an OSGi container. It also verifies that | |
| 22 | -driver-core can be used in an OSGi container in the following | |
| 23 | -configurations: | |
| 24 | - | |
| 25 | -1. Default (default classifier with all dependencies) | |
| 26 | -2. Netty-Shaded (shaded classifier with all depedencies w/o Netty) | |
| 27 | -3. Guava 15 (default classifier with Guava 15.0) | |
| 28 | -4. Guava 16 | |
| 29 | -5. Guava 17 | |
| 30 | -6. Guava 18 |
deleted driver-examples/osgi/pom.xml +0 −312
| @@ -1,312 +0,0 @@ | ||
| 1 | -<!-- | |
| 2 | - | |
| 3 | - Copyright (C) 2012-2015 DataStax Inc. | |
| 4 | - | |
| 5 | - Licensed under the Apache License, Version 2.0 (the "License"); | |
| 6 | - you may not use this file except in compliance with the License. | |
| 7 | - You may obtain a copy of the License at | |
| 8 | - | |
| 9 | - http://www.apache.org/licenses/LICENSE-2.0 | |
| 10 | - | |
| 11 | - Unless required by applicable law or agreed to in writing, software | |
| 12 | - distributed under the License is distributed on an "AS IS" BASIS, | |
| 13 | - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 14 | - See the License for the specific language governing permissions and | |
| 15 | - limitations under the License. | |
| 16 | - | |
| 17 | ---> | |
| 18 | -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 19 | - <modelVersion>4.0.0</modelVersion> | |
| 20 | - <parent> | |
| 21 | - <groupId>com.datastax.cassandra</groupId> | |
| 22 | - <artifactId>cassandra-driver-examples-parent</artifactId> | |
| 23 | - <version>3.0.1-SNAPSHOT</version> | |
| 24 | - </parent> | |
| 25 | - <artifactId>cassandra-driver-examples-osgi</artifactId> | |
| 26 | - <packaging>bundle</packaging> | |
| 27 | - <name>DataStax Java Driver for Apache Cassandra Examples - OSGi</name> | |
| 28 | - <description>An example of using DataStax Java Driver in an OSGi container.</description> | |
| 29 | - <url>https://github.com/datastax/java-driver</url> | |
| 30 | - | |
| 31 | - <properties> | |
| 32 | - <felix.version>4.6.0</felix.version> | |
| 33 | - <pax-exam.version>3.6.0</pax-exam.version> | |
| 34 | - <logback.version>1.1.3</logback.version> | |
| 35 | - <main.basedir>${project.parent.parent.basedir}</main.basedir> | |
| 36 | - </properties> | |
| 37 | - | |
| 38 | - <dependencies> | |
| 39 | - <dependency> | |
| 40 | - <groupId>com.datastax.cassandra</groupId> | |
| 41 | - <artifactId>cassandra-driver-core</artifactId> | |
| 42 | - <version>${project.parent.version}</version> | |
| 43 | - </dependency> | |
| 44 | - | |
| 45 | - <dependency> | |
| 46 | - <groupId>org.apache.felix</groupId> | |
| 47 | - <artifactId>org.apache.felix.framework</artifactId> | |
| 48 | - <version>${felix.version}</version> | |
| 49 | - </dependency> | |
| 50 | - | |
| 51 | - <dependency> | |
| 52 | - <groupId>com.datastax.cassandra</groupId> | |
| 53 | - <artifactId>cassandra-driver-core</artifactId> | |
| 54 | - <version>${project.parent.version}</version> | |
| 55 | - <type>test-jar</type> | |
| 56 | - <scope>test</scope> | |
| 57 | - </dependency> | |
| 58 | - | |
| 59 | - <dependency> | |
| 60 | - <groupId>org.ops4j.pax.exam</groupId> | |
| 61 | - <artifactId>pax-exam</artifactId> | |
| 62 | - <version>${pax-exam.version}</version> | |
| 63 | - <scope>test</scope> | |
| 64 | - </dependency> | |
| 65 | - | |
| 66 | - <dependency> | |
| 67 | - <groupId>org.ops4j.pax.exam</groupId> | |
| 68 | - <artifactId>pax-exam-testng</artifactId> | |
| 69 | - <version>${pax-exam.version}</version> | |
| 70 | - <scope>test</scope> | |
| 71 | - </dependency> | |
| 72 | - | |
| 73 | - <dependency> | |
| 74 | - <groupId>org.ops4j.pax.exam</groupId> | |
| 75 | - <artifactId>pax-exam-container-native</artifactId> | |
| 76 | - <version>${pax-exam.version}</version> | |
| 77 | - <scope>test</scope> | |
| 78 | - </dependency> | |
| 79 | - | |
| 80 | - <dependency> | |
| 81 | - <groupId>org.ops4j.pax.exam</groupId> | |
| 82 | - <artifactId>pax-exam-link-mvn</artifactId> | |
| 83 | - <version>${pax-exam.version}</version> | |
| 84 | - <scope>test</scope> | |
| 85 | - </dependency> | |
| 86 | - | |
| 87 | - <dependency> | |
| 88 | - <groupId>javax.transaction</groupId> | |
| 89 | - <artifactId>jta</artifactId> | |
| 90 | - <version>1.1</version> | |
| 91 | - <scope>test</scope> | |
| 92 | - </dependency> | |
| 93 | - | |
| 94 | - <dependency> | |
| 95 | - <groupId>com.jcabi</groupId> | |
| 96 | - <artifactId>jcabi-manifests</artifactId> | |
| 97 | - <version>1.1</version> | |
| 98 | - <scope>test</scope> | |
| 99 | - </dependency> | |
| 100 | - | |
| 101 | - <dependency> | |
| 102 | - <groupId>javax.servlet</groupId> | |
| 103 | - <artifactId>javax.servlet-api</artifactId> | |
| 104 | - <version>3.1.0</version> | |
| 105 | - <scope>test</scope> | |
| 106 | - </dependency> | |
| 107 | - | |
| 108 | - <dependency> | |
| 109 | - <groupId>javax.inject</groupId> | |
| 110 | - <artifactId>javax.inject</artifactId> | |
| 111 | - <version>1</version> | |
| 112 | - <scope>test</scope> | |
| 113 | - </dependency> | |
| 114 | - | |
| 115 | - <dependency> | |
| 116 | - <groupId>org.apache.commons</groupId> | |
| 117 | - <artifactId>commons-exec</artifactId> | |
| 118 | - <version>1.3</version> | |
| 119 | - <scope>test</scope> | |
| 120 | - </dependency> | |
| 121 | - | |
| 122 | - <dependency> | |
| 123 | - <groupId>ch.qos.logback</groupId> | |
| 124 | - <artifactId>logback-classic</artifactId> | |
| 125 | - <version>${logback.version}</version> | |
| 126 | - </dependency> | |
| 127 | - | |
| 128 | - <dependency> | |
| 129 | - <groupId>ch.qos.logback</groupId> | |
| 130 | - <artifactId>logback-core</artifactId> | |
| 131 | - <version>${logback.version}</version> | |
| 132 | - </dependency> | |
| 133 | - </dependencies> | |
| 134 | - | |
| 135 | - <build> | |
| 136 | - <plugins> | |
| 137 | - <plugin> | |
| 138 | - <groupId>org.apache.maven.plugins</groupId> | |
| 139 | - <artifactId>maven-failsafe-plugin</artifactId> | |
| 140 | - <version>2.18.1</version> | |
| 141 | - <executions> | |
| 142 | - <execution> | |
| 143 | - <goals> | |
| 144 | - <goal>integration-test</goal> | |
| 145 | - <goal>verify</goal> | |
| 146 | - </goals> | |
| 147 | - </execution> | |
| 148 | - </executions> | |
| 149 | - </plugin> | |
| 150 | - <plugin> | |
| 151 | - <groupId>org.apache.felix</groupId> | |
| 152 | - <artifactId>maven-bundle-plugin</artifactId> | |
| 153 | - <extensions>true</extensions> | |
| 154 | - <version>2.4.0</version> | |
| 155 | - <configuration> | |
| 156 | - <instructions> | |
| 157 | - <Bundle-SymbolicName>com.datastax.driver.osgi</Bundle-SymbolicName> | |
| 158 | - <Bundle-Version>${project.version}</Bundle-Version> | |
| 159 | - <Export-Package>com.datastax.driver.osgi.api,!com.datastax.driver.osgi.impl</Export-Package> | |
| 160 | - <Bundle-Activator>com.datastax.driver.osgi.impl.Activator</Bundle-Activator> | |
| 161 | - <_include>-osgi.bnd</_include> | |
| 162 | - </instructions> | |
| 163 | - <supportedProjectTypes> | |
| 164 | - <supportedProjectType>jar</supportedProjectType> | |
| 165 | - <supportedProjectType>bundle</supportedProjectType> | |
| 166 | - <supportedProjectType>pom</supportedProjectType> | |
| 167 | - </supportedProjectTypes> | |
| 168 | - </configuration> | |
| 169 | - <executions> | |
| 170 | - <execution> | |
| 171 | - <id>bundle-manifest</id> | |
| 172 | - <phase>compile</phase> | |
| 173 | - <goals> | |
| 174 | - <goal>manifest</goal> | |
| 175 | - </goals> | |
| 176 | - </execution> | |
| 177 | - </executions> | |
| 178 | - </plugin> | |
| 179 | - </plugins> | |
| 180 | - </build> | |
| 181 | - | |
| 182 | - <profiles> | |
| 183 | - <profile> | |
| 184 | - <!-- Skip test by default, short or long is required to run unit tests since pax-exam will throw exception if it encounters a | |
| 185 | - test with no matching methods. --> | |
| 186 | - <id>default</id> | |
| 187 | - <properties> | |
| 188 | - <env>default</env> | |
| 189 | - </properties> | |
| 190 | - <activation> | |
| 191 | - <activeByDefault>true</activeByDefault> | |
| 192 | - </activation> | |
| 193 | - <build> | |
| 194 | - <plugins> | |
| 195 | - <plugin> | |
| 196 | - <groupId>org.apache.maven.plugins</groupId> | |
| 197 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 198 | - <version>2.14</version> | |
| 199 | - <configuration> | |
| 200 | - </configuration> | |
| 201 | - </plugin> | |
| 202 | - <plugin> | |
| 203 | - <groupId>org.apache.maven.plugins</groupId> | |
| 204 | - <artifactId>maven-failsafe-plugin</artifactId> | |
| 205 | - <version>2.18.1</version> | |
| 206 | - <configuration> | |
| 207 | - <skip>true</skip> | |
| 208 | - </configuration> | |
| 209 | - </plugin> | |
| 210 | - </plugins> | |
| 211 | - </build> | |
| 212 | - </profile> | |
| 213 | - | |
| 214 | - <profile> | |
| 215 | - <id>short</id> | |
| 216 | - <properties> | |
| 217 | - <env>default</env> | |
| 218 | - </properties> | |
| 219 | - <build> | |
| 220 | - <plugins> | |
| 221 | - <plugin> | |
| 222 | - <groupId>org.apache.maven.plugins</groupId> | |
| 223 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 224 | - <version>2.14</version> | |
| 225 | - <configuration> | |
| 226 | - <groups>unit,short</groups> | |
| 227 | - <useFile>false</useFile> | |
| 228 | - <systemPropertyVariables> | |
| 229 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 230 | - <ipprefix>${ipprefix}</ipprefix> | |
| 231 | - </systemPropertyVariables> | |
| 232 | - </configuration> | |
| 233 | - </plugin> | |
| 234 | - <plugin> | |
| 235 | - <groupId>org.apache.maven.plugins</groupId> | |
| 236 | - <artifactId>maven-failsafe-plugin</artifactId> | |
| 237 | - <version>2.18.1</version> | |
| 238 | - <configuration> | |
| 239 | - <groups>unit,short</groups> | |
| 240 | - <useFile>false</useFile> | |
| 241 | - <systemPropertyVariables> | |
| 242 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 243 | - <ipprefix>${ipprefix}</ipprefix> | |
| 244 | - </systemPropertyVariables> | |
| 245 | - </configuration> | |
| 246 | - </plugin> | |
| 247 | - </plugins> | |
| 248 | - </build> | |
| 249 | - </profile> | |
| 250 | - | |
| 251 | - <profile> | |
| 252 | - <id>long</id> | |
| 253 | - <properties> | |
| 254 | - <env>default</env> | |
| 255 | - </properties> | |
| 256 | - <build> | |
| 257 | - <plugins> | |
| 258 | - <plugin> | |
| 259 | - <groupId>org.apache.maven.plugins</groupId> | |
| 260 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 261 | - <version>2.16</version> | |
| 262 | - <configuration> | |
| 263 | - <groups>unit,short,long</groups> | |
| 264 | - <useFile>false</useFile> | |
| 265 | - <systemPropertyVariables> | |
| 266 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 267 | - <ipprefix>${ipprefix}</ipprefix> | |
| 268 | - </systemPropertyVariables> | |
| 269 | - </configuration> | |
| 270 | - </plugin> | |
| 271 | - <plugin> | |
| 272 | - <groupId>org.apache.maven.plugins</groupId> | |
| 273 | - <artifactId>maven-failsafe-plugin</artifactId> | |
| 274 | - <version>2.18.1</version> | |
| 275 | - <configuration> | |
| 276 | - <groups>unit,short,long</groups> | |
| 277 | - <useFile>false</useFile> | |
| 278 | - <systemPropertyVariables> | |
| 279 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 280 | - <ipprefix>${ipprefix}</ipprefix> | |
| 281 | - </systemPropertyVariables> | |
| 282 | - </configuration> | |
| 283 | - </plugin> | |
| 284 | - </plugins> | |
| 285 | - </build> | |
| 286 | - </profile> | |
| 287 | - </profiles> | |
| 288 | - | |
| 289 | - <licenses> | |
| 290 | - <license> | |
| 291 | - <name>Apache 2</name> | |
| 292 | - <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> | |
| 293 | - <distribution>repo</distribution> | |
| 294 | - <comments>Apache License Version 2.0</comments> | |
| 295 | - </license> | |
| 296 | - </licenses> | |
| 297 | - | |
| 298 | - <scm> | |
| 299 | - <connection>scm:git:git@github.com:datastax/java-driver.git</connection> | |
| 300 | - <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection> | |
| 301 | - <url>https://github.com/datastax/java-driver</url> | |
| 302 | - <tag>HEAD</tag> | |
| 303 | - </scm> | |
| 304 | - | |
| 305 | - <developers> | |
| 306 | - <developer> | |
| 307 | - <name>Various</name> | |
| 308 | - <organization>DataStax</organization> | |
| 309 | - </developer> | |
| 310 | - </developers> | |
| 311 | -</project> | |
| 312 | - |
deleted driver-examples/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxException.java +0 −23
| @@ -1,23 +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.osgi.api; | |
| 17 | - | |
| 18 | -public class MailboxException extends Exception { | |
| 19 | - | |
| 20 | - public MailboxException(Throwable cause) { | |
| 21 | - super("Failure interacting with Mailbox", cause); | |
| 22 | - } | |
| 23 | -} |
deleted driver-examples/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java +0 −61
| @@ -1,61 +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.osgi.api; | |
| 17 | - | |
| 18 | -import java.util.Date; | |
| 19 | - | |
| 20 | -public class MailboxMessage { | |
| 21 | - private String recipient; | |
| 22 | - private Date date; | |
| 23 | - private String sender; | |
| 24 | - private String body; | |
| 25 | - | |
| 26 | - public MailboxMessage(String recipient, Date date, String sender, String body) { | |
| 27 | - this.recipient = recipient; | |
| 28 | - this.date = date; | |
| 29 | - this.sender = sender; | |
| 30 | - this.body = body; | |
| 31 | - } | |
| 32 | - | |
| 33 | - public String getRecipient() { | |
| 34 | - return recipient; | |
| 35 | - } | |
| 36 | - | |
| 37 | - public Date getDate() { | |
| 38 | - return date; | |
| 39 | - } | |
| 40 | - | |
| 41 | - public String getSender() { | |
| 42 | - return sender; | |
| 43 | - } | |
| 44 | - | |
| 45 | - public String getBody() { | |
| 46 | - return body; | |
| 47 | - } | |
| 48 | - | |
| 49 | - @Override | |
| 50 | - public boolean equals(Object that) { | |
| 51 | - if (that instanceof MailboxMessage) { | |
| 52 | - MailboxMessage thatM = (MailboxMessage) that; | |
| 53 | - return recipient.equals(thatM.getRecipient()) && | |
| 54 | - date.equals(thatM.getDate()) && | |
| 55 | - sender.equals(thatM.getSender()) && | |
| 56 | - body.equals(thatM.getBody()); | |
| 57 | - } else { | |
| 58 | - return false; | |
| 59 | - } | |
| 60 | - } | |
| 61 | -} |
deleted driver-examples/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxService.java +0 −45
| @@ -1,45 +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.osgi.api; | |
| 17 | - | |
| 18 | -import java.util.Collection; | |
| 19 | -import java.util.UUID; | |
| 20 | - | |
| 21 | -public interface MailboxService { | |
| 22 | - | |
| 23 | - /** | |
| 24 | - * Retrieve all messages for a given recipient. | |
| 25 | - * | |
| 26 | - * @param recipient User whose mailbox is being read. | |
| 27 | - * @return All messages in the mailbox. | |
| 28 | - */ | |
| 29 | - public Collection<MailboxMessage> getMessages(String recipient) throws MailboxException; | |
| 30 | - | |
| 31 | - /** | |
| 32 | - * Stores the given message in the appropriate mailbox. | |
| 33 | - * | |
| 34 | - * @param message Message to send. | |
| 35 | - * @return UUID generated for the message. | |
| 36 | - */ | |
| 37 | - public UUID sendMessage(MailboxMessage message) throws MailboxException; | |
| 38 | - | |
| 39 | - /** | |
| 40 | - * Deletes all mail for the given recipient. | |
| 41 | - * | |
| 42 | - * @param recipient User whose mailbox will be cleared. | |
| 43 | - */ | |
| 44 | - public void clearMailbox(String recipient) throws MailboxException; | |
| 45 | -} |
deleted driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java +0 −58
| @@ -1,58 +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.osgi.impl; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.Cluster; | |
| 19 | -import com.datastax.driver.core.Session; | |
| 20 | -import com.datastax.driver.osgi.api.MailboxService; | |
| 21 | -import org.osgi.framework.BundleActivator; | |
| 22 | -import org.osgi.framework.BundleContext; | |
| 23 | - | |
| 24 | -import java.util.Hashtable; | |
| 25 | - | |
| 26 | -public class Activator implements BundleActivator { | |
| 27 | - | |
| 28 | - private Cluster cluster; | |
| 29 | - | |
| 30 | - @Override | |
| 31 | - public void start(BundleContext context) throws Exception { | |
| 32 | - String contactPointsStr = context.getProperty("cassandra.contactpoints"); | |
| 33 | - if (contactPointsStr == null) { | |
| 34 | - contactPointsStr = "127.0.0.1"; | |
| 35 | - } | |
| 36 | - String[] contactPoints = contactPointsStr.split(","); | |
| 37 | - | |
| 38 | - String keyspace = context.getProperty("cassandra.keyspace"); | |
| 39 | - if (keyspace == null) { | |
| 40 | - keyspace = "mailbox"; | |
| 41 | - } | |
| 42 | - | |
| 43 | - cluster = Cluster.builder().addContactPoints(contactPoints).build(); | |
| 44 | - Session session = cluster.connect(); | |
| 45 | - | |
| 46 | - MailboxImpl mailbox = new MailboxImpl(session, keyspace); | |
| 47 | - mailbox.init(); | |
| 48 | - | |
| 49 | - context.registerService(MailboxService.class.getName(), mailbox, new Hashtable<String, String>()); | |
| 50 | - } | |
| 51 | - | |
| 52 | - @Override | |
| 53 | - public void stop(BundleContext context) throws Exception { | |
| 54 | - if (cluster != null) { | |
| 55 | - cluster.close(); | |
| 56 | - } | |
| 57 | - } | |
| 58 | -} |
deleted driver-examples/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java +0 −137
| @@ -1,137 +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.osgi.impl; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.*; | |
| 19 | -import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 20 | -import com.datastax.driver.core.utils.UUIDs; | |
| 21 | -import com.datastax.driver.osgi.api.MailboxException; | |
| 22 | -import com.datastax.driver.osgi.api.MailboxMessage; | |
| 23 | -import com.datastax.driver.osgi.api.MailboxService; | |
| 24 | - | |
| 25 | -import java.util.ArrayList; | |
| 26 | -import java.util.Collection; | |
| 27 | -import java.util.Date; | |
| 28 | -import java.util.UUID; | |
| 29 | - | |
| 30 | -import static com.datastax.driver.core.querybuilder.QueryBuilder.*; | |
| 31 | - | |
| 32 | -public class MailboxImpl implements MailboxService { | |
| 33 | - | |
| 34 | - private static final String TABLE = "mailbox"; | |
| 35 | - | |
| 36 | - private final Session session; | |
| 37 | - | |
| 38 | - private final String keyspace; | |
| 39 | - | |
| 40 | - private volatile boolean initialized = false; | |
| 41 | - | |
| 42 | - private PreparedStatement retrieveStatement; | |
| 43 | - | |
| 44 | - private PreparedStatement insertStatement; | |
| 45 | - | |
| 46 | - private PreparedStatement deleteStatement; | |
| 47 | - | |
| 48 | - public MailboxImpl(Session session, String keyspace) { | |
| 49 | - this.session = session; | |
| 50 | - this.keyspace = keyspace; | |
| 51 | - } | |
| 52 | - | |
| 53 | - public synchronized void init() { | |
| 54 | - if (initialized) | |
| 55 | - return; | |
| 56 | - | |
| 57 | - // Create the schema if it does not exist. | |
| 58 | - try { | |
| 59 | - session.execute("USE " + keyspace); | |
| 60 | - } catch (InvalidQueryException e) { | |
| 61 | - session.execute("CREATE KEYSPACE " + keyspace + | |
| 62 | - " with replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}"); | |
| 63 | - | |
| 64 | - session.execute("CREATE TABLE " + keyspace + "." + TABLE + " (" + | |
| 65 | - "recipient text," + | |
| 66 | - "time timeuuid," + | |
| 67 | - "sender text," + | |
| 68 | - "body text," + | |
| 69 | - "PRIMARY KEY (recipient, time))"); | |
| 70 | - } | |
| 71 | - | |
| 72 | - retrieveStatement = session.prepare(select() | |
| 73 | - .from(keyspace, TABLE) | |
| 74 | - .where(eq("recipient", bindMarker()))); | |
| 75 | - | |
| 76 | - insertStatement = session.prepare(insertInto(keyspace, TABLE) | |
| 77 | - .value("recipient", bindMarker()) | |
| 78 | - .value("time", bindMarker()) | |
| 79 | - .value("sender", bindMarker()) | |
| 80 | - .value("body", bindMarker())); | |
| 81 | - | |
| 82 | - deleteStatement = session.prepare(delete().from(keyspace, TABLE) | |
| 83 | - .where(eq("recipient", bindMarker()))); | |
| 84 | - | |
| 85 | - initialized = true; | |
| 86 | - } | |
| 87 | - | |
| 88 | - @Override | |
| 89 | - public Collection<MailboxMessage> getMessages(String recipient) throws MailboxException { | |
| 90 | - try { | |
| 91 | - BoundStatement statement = new BoundStatement(retrieveStatement); | |
| 92 | - statement.setString(0, recipient); | |
| 93 | - ResultSet result = session.execute(statement); | |
| 94 | - | |
| 95 | - Collection<MailboxMessage> messages = new ArrayList<MailboxMessage>(); | |
| 96 | - for (Row input : result) { | |
| 97 | - Date date = new Date(UUIDs.unixTimestamp(input.getUUID("time"))); | |
| 98 | - messages.add(new MailboxMessage(input.getString("recipient"), | |
| 99 | - date, | |
| 100 | - input.getString("sender"), | |
| 101 | - input.getString("body"))); | |
| 102 | - } | |
| 103 | - return messages; | |
| 104 | - } catch (Exception e) { | |
| 105 | - throw new MailboxException(e); | |
| 106 | - } | |
| 107 | - } | |
| 108 | - | |
| 109 | - @Override | |
| 110 | - public UUID sendMessage(MailboxMessage message) throws MailboxException { | |
| 111 | - try { | |
| 112 | - UUID time = UUIDs.startOf(message.getDate().getTime()); | |
| 113 | - | |
| 114 | - BoundStatement statement = new BoundStatement(insertStatement); | |
| 115 | - statement.setString(0, message.getRecipient()); | |
| 116 | - statement.setUUID(1, time); | |
| 117 | - statement.setString(2, message.getSender()); | |
| 118 | - statement.setString(3, message.getBody()); | |
| 119 | - | |
| 120 | - session.execute(statement); | |
| 121 | - return time; | |
| 122 | - } catch (Exception e) { | |
| 123 | - throw new MailboxException(e); | |
| 124 | - } | |
| 125 | - } | |
| 126 | - | |
| 127 | - @Override | |
| 128 | - public void clearMailbox(String recipient) throws MailboxException { | |
| 129 | - try { | |
| 130 | - BoundStatement statement = new BoundStatement(deleteStatement); | |
| 131 | - statement.setString(0, recipient); | |
| 132 | - session.execute(statement); | |
| 133 | - } catch (Exception e) { | |
| 134 | - throw new MailboxException(e); | |
| 135 | - } | |
| 136 | - } | |
| 137 | -} |
deleted driver-examples/osgi/src/test/java/com/datastax/driver/osgi/BundleOptions.java +0 −85
| @@ -1,85 +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.osgi; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.TestUtils; | |
| 19 | -import org.ops4j.pax.exam.Option; | |
| 20 | -import org.ops4j.pax.exam.options.CompositeOption; | |
| 21 | -import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; | |
| 22 | -import org.ops4j.pax.exam.options.UrlProvisionOption; | |
| 23 | -import org.ops4j.pax.exam.util.PathUtils; | |
| 24 | - | |
| 25 | -import static com.datastax.driver.osgi.VersionProvider.projectVersion; | |
| 26 | -import static org.ops4j.pax.exam.CoreOptions.*; | |
| 27 | - | |
| 28 | -public class BundleOptions { | |
| 29 | - | |
| 30 | - public static UrlProvisionOption driverBundle() { | |
| 31 | - return driverBundle(false); | |
| 32 | - } | |
| 33 | - | |
| 34 | - public static UrlProvisionOption driverBundle(boolean useShaded) { | |
| 35 | - String classifier = useShaded ? "-shaded" : ""; | |
| 36 | - return bundle("reference:file:" + PathUtils.getBaseDir() + "/../../driver-core/target/cassandra-driver-core-" + projectVersion() + classifier + ".jar"); | |
| 37 | - } | |
| 38 | - | |
| 39 | - public static MavenArtifactProvisionOption guavaBundle() { | |
| 40 | - return mavenBundle("com.google.guava", "guava", "16.0.1"); | |
| 41 | - } | |
| 42 | - | |
| 43 | - public static CompositeOption nettyBundles() { | |
| 44 | - final String nettyVersion = "4.0.33.Final"; | |
| 45 | - return new CompositeOption() { | |
| 46 | - | |
| 47 | - @Override | |
| 48 | - public Option[] getOptions() { | |
| 49 | - return options( | |
| 50 | - mavenBundle("io.netty", "netty-buffer", nettyVersion), | |
| 51 | - mavenBundle("io.netty", "netty-codec", nettyVersion), | |
| 52 | - mavenBundle("io.netty", "netty-common", nettyVersion), | |
| 53 | - mavenBundle("io.netty", "netty-handler", nettyVersion), | |
| 54 | - mavenBundle("io.netty", "netty-transport", nettyVersion) | |
| 55 | - ); | |
| 56 | - } | |
| 57 | - }; | |
| 58 | - } | |
| 59 | - | |
| 60 | - public static UrlProvisionOption mailboxBundle() { | |
| 61 | - return bundle("reference:file:" + PathUtils.getBaseDir() + "/target/classes"); | |
| 62 | - } | |
| 63 | - | |
| 64 | - public static CompositeOption defaultOptions() { | |
| 65 | - return new CompositeOption() { | |
| 66 | - | |
| 67 | - @Override | |
| 68 | - public Option[] getOptions() { | |
| 69 | - return options( | |
| 70 | - // Delegate javax.security.cert to the parent classloader. javax.security.cert.X509Certificate is used in | |
| 71 | - // io.netty.util.internal.EmptyArrays, but not directly by the driver. | |
| 72 | - bootDelegationPackage("javax.security.cert"), | |
| 73 | - systemProperty("cassandra.contactpoints").value(TestUtils.IP_PREFIX + 1), | |
| 74 | - systemProperty("logback.configurationFile").value("file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"), | |
| 75 | - mavenBundle("org.slf4j", "slf4j-api", "1.7.5"), | |
| 76 | - mavenBundle("ch.qos.logback", "logback-classic", "1.1.3"), | |
| 77 | - mavenBundle("ch.qos.logback", "logback-core", "1.1.3"), | |
| 78 | - mavenBundle("io.dropwizard.metrics", "metrics-core", "3.1.2"), | |
| 79 | - systemPackages("org.testng", "org.junit", "org.junit.runner", "org.junit.runner.manipulation", | |
| 80 | - "org.junit.runner.notification", "com.jcabi.manifests") | |
| 81 | - ); | |
| 82 | - } | |
| 83 | - }; | |
| 84 | - } | |
| 85 | -} |
deleted driver-examples/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java +0 −65
| @@ -1,65 +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.osgi; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 19 | -import org.testng.ITestContext; | |
| 20 | -import org.testng.ITestListener; | |
| 21 | -import org.testng.ITestResult; | |
| 22 | - | |
| 23 | -/** | |
| 24 | - * A listener that fires up a single node CCM instance on test class start and tears it | |
| 25 | - * down on test class end. | |
| 26 | - * <p/> | |
| 27 | - * This is needed for tests that use Pax-Exam since it runs some methods in the OSGi container | |
| 28 | - * which we do not want. | |
| 29 | - */ | |
| 30 | -public class CCMBridgeListener implements ITestListener { | |
| 31 | - | |
| 32 | - private CCMBridge ccm; | |
| 33 | - | |
| 34 | - @Override | |
| 35 | - public void onStart(ITestContext context) { | |
| 36 | - ccm = CCMBridge.builder().withNodes(1).withBinaryPort(9042).build(); | |
| 37 | - } | |
| 38 | - | |
| 39 | - @Override | |
| 40 | - public void onFinish(ITestContext context) { | |
| 41 | - if (ccm != null) { | |
| 42 | - ccm.remove(); | |
| 43 | - } | |
| 44 | - } | |
| 45 | - | |
| 46 | - @Override | |
| 47 | - public void onTestStart(ITestResult result) { | |
| 48 | - } | |
| 49 | - | |
| 50 | - @Override | |
| 51 | - public void onTestSuccess(ITestResult result) { | |
| 52 | - } | |
| 53 | - | |
| 54 | - @Override | |
| 55 | - public void onTestFailure(ITestResult result) { | |
| 56 | - } | |
| 57 | - | |
| 58 | - @Override | |
| 59 | - public void onTestSkipped(ITestResult result) { | |
| 60 | - } | |
| 61 | - | |
| 62 | - @Override | |
| 63 | - public void onTestFailedButWithinSuccessPercentage(ITestResult result) { | |
| 64 | - } | |
| 65 | -} |
deleted driver-examples/osgi/src/test/java/com/datastax/driver/osgi/GuavaSanityCheckNegativeIT.java +0 −100
| @@ -1,100 +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.osgi; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.Cluster; | |
| 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 | -import static org.testng.Assert.assertTrue; | |
| 28 | -import static org.testng.Assert.fail; | |
| 29 | - | |
| 30 | -/** | |
| 31 | - * This test is no longer valid since the driver bundle has the following new requirement | |
| 32 | - * for Guava: {@code [16.0.1,19)}. | |
| 33 | - */ | |
| 34 | -@Listeners({PaxExam.class}) | |
| 35 | -@Test(groups = "short", enabled = false) | |
| 36 | -public class GuavaSanityCheckNegativeIT { | |
| 37 | - | |
| 38 | - @Configuration | |
| 39 | - public Option[] guava14_0_1Config() { | |
| 40 | - return options( | |
| 41 | - driverBundle(), | |
| 42 | - nettyBundles(), | |
| 43 | - guavaBundle().version("14.0.1"), | |
| 44 | - defaultOptions() | |
| 45 | - ); | |
| 46 | - } | |
| 47 | - | |
| 48 | - @Configuration | |
| 49 | - public Option[] guava15Config() { | |
| 50 | - return options( | |
| 51 | - driverBundle(), | |
| 52 | - nettyBundles(), | |
| 53 | - guavaBundle().version("15.0"), | |
| 54 | - defaultOptions() | |
| 55 | - ); | |
| 56 | - } | |
| 57 | - | |
| 58 | - @Configuration | |
| 59 | - public Option[] guava16Config() { | |
| 60 | - return options( | |
| 61 | - driverBundle(), | |
| 62 | - nettyBundles(), | |
| 63 | - guavaBundle().version("16.0"), | |
| 64 | - defaultOptions() | |
| 65 | - ); | |
| 66 | - } | |
| 67 | - | |
| 68 | - /** | |
| 69 | - * <p> | |
| 70 | - * Validates that the driver is able to detect that the guava library in the classpath is | |
| 71 | - * less than version 16.01 and throws an {@link IllegalStateException} in this case and | |
| 72 | - * is raised as the cause of an {@link ExceptionInInitializerError} since the failure | |
| 73 | - * occurs at static initialization. | |
| 74 | - * </p> | |
| 75 | - * <p/> | |
| 76 | - * The following configurations are tried (defined via methods with the @Configuration annotation): | |
| 77 | - * <ol> | |
| 78 | - * <li>With Guava 14.0.1</li> | |
| 79 | - * <li>With Guava 15.0</li> | |
| 80 | - * <li>With Guava 16.0</li> | |
| 81 | - * </ol> | |
| 82 | - * | |
| 83 | - * @test_category packaging | |
| 84 | - * @expected_result An {@link IllegalStateException} is thrown. | |
| 85 | - * @jira_ticket JAVA-961 | |
| 86 | - * @since 3.0.0-beta1 | |
| 87 | - */ | |
| 88 | - public void should_raise_guava_version_error_if_lt_16_0_1() throws Throwable { | |
| 89 | - try { | |
| 90 | - Cluster.builder(); | |
| 91 | - fail("Expected an IllegalStateException for Guava version incompatibility"); | |
| 92 | - } catch (ExceptionInInitializerError e) { | |
| 93 | - try { | |
| 94 | - throw e.getCause(); | |
| 95 | - } catch (IllegalStateException ise) { | |
| 96 | - assertTrue(ise.getMessage().contains("Detected Guava issue #1635")); | |
| 97 | - } | |
| 98 | - } | |
| 99 | - } | |
| 100 | -} |
deleted driver-examples/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceIT.java +0 −124
| @@ -1,124 +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.osgi; | |
| 17 | - | |
| 18 | -import com.datastax.driver.osgi.api.MailboxException; | |
| 19 | -import com.datastax.driver.osgi.api.MailboxMessage; | |
| 20 | -import com.datastax.driver.osgi.api.MailboxService; | |
| 21 | -import org.ops4j.pax.exam.Configuration; | |
| 22 | -import org.ops4j.pax.exam.Option; | |
| 23 | -import org.ops4j.pax.exam.testng.listener.PaxExam; | |
| 24 | -import org.testng.annotations.Listeners; | |
| 25 | -import org.testng.annotations.Test; | |
| 26 | - | |
| 27 | -import javax.inject.Inject; | |
| 28 | -import java.util.ArrayList; | |
| 29 | -import java.util.Collection; | |
| 30 | -import java.util.GregorianCalendar; | |
| 31 | - | |
| 32 | -import static com.datastax.driver.osgi.BundleOptions.*; | |
| 33 | -import static org.ops4j.pax.exam.CoreOptions.options; | |
| 34 | -import static org.testng.Assert.assertEquals; | |
| 35 | - | |
| 36 | -@Listeners({CCMBridgeListener.class, PaxExam.class}) | |
| 37 | -@Test(groups = "short") | |
| 38 | -public class MailboxServiceIT { | |
| 39 | - @Inject | |
| 40 | - MailboxService service; | |
| 41 | - | |
| 42 | - @Configuration | |
| 43 | - public Option[] shadedConfig() { | |
| 44 | - return options( | |
| 45 | - driverBundle(true), | |
| 46 | - mailboxBundle(), | |
| 47 | - guavaBundle(), | |
| 48 | - defaultOptions() | |
| 49 | - ); | |
| 50 | - } | |
| 51 | - | |
| 52 | - @Configuration | |
| 53 | - public Option[] defaultConfig() { | |
| 54 | - return options( | |
| 55 | - driverBundle(), | |
| 56 | - mailboxBundle(), | |
| 57 | - guavaBundle(), | |
| 58 | - nettyBundles(), | |
| 59 | - defaultOptions() | |
| 60 | - ); | |
| 61 | - } | |
| 62 | - | |
| 63 | - @Configuration | |
| 64 | - public Option[] guava17Config() { | |
| 65 | - return options( | |
| 66 | - driverBundle(), | |
| 67 | - mailboxBundle(), | |
| 68 | - nettyBundles(), | |
| 69 | - guavaBundle().version("17.0"), | |
| 70 | - defaultOptions() | |
| 71 | - ); | |
| 72 | - } | |
| 73 | - | |
| 74 | - @Configuration | |
| 75 | - public Option[] guava18Config() { | |
| 76 | - return options( | |
| 77 | - driverBundle(), | |
| 78 | - mailboxBundle(), | |
| 79 | - nettyBundles(), | |
| 80 | - guavaBundle().version("18.0"), | |
| 81 | - defaultOptions() | |
| 82 | - ); | |
| 83 | - } | |
| 84 | - | |
| 85 | - /** | |
| 86 | - * <p> | |
| 87 | - * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver. Ensures that | |
| 88 | - * queries can be made through the service with the current given configuration. | |
| 89 | - * </p> | |
| 90 | - * <p/> | |
| 91 | - * The following configurations are tried (defined via methods with the @Configuration annotation): | |
| 92 | - * <ol> | |
| 93 | - * <li>Default bundle (Driver with all of it's dependencies)</li> | |
| 94 | - * <li>Shaded bundle (Driver with netty shaded)</li> | |
| 95 | - * <li>With Guava 16.0.1</li> | |
| 96 | - * <li>With Guava 17</li> | |
| 97 | - * <li>With Guava 18</li> | |
| 98 | - * </ol> | |
| 99 | - * | |
| 100 | - * @test_category packaging | |
| 101 | - * @expected_result Can create, retrieve and delete data using the mailbox service. | |
| 102 | - * @jira_ticket JAVA-620 | |
| 103 | - * @since 2.0.10, 2.1.5 | |
| 104 | - */ | |
| 105 | - public void service_api_functional() throws MailboxException { | |
| 106 | - // Insert some data into mailbox for a particular user. | |
| 107 | - String recipient = "user@datastax.com"; | |
| 108 | - | |
| 109 | - try { | |
| 110 | - Collection<MailboxMessage> inMessages = new ArrayList<MailboxMessage>(); | |
| 111 | - for (int i = 0; i < 30; i++) { | |
| 112 | - MailboxMessage message = new MailboxMessage(recipient, new GregorianCalendar(2015, 1, i).getTime(), recipient, "" + i); | |
| 113 | - inMessages.add(message); | |
| 114 | - service.sendMessage(message); | |
| 115 | - } | |
| 116 | - | |
| 117 | - Collection<MailboxMessage> messages = service.getMessages(recipient); | |
| 118 | - | |
| 119 | - assertEquals(messages, inMessages); | |
| 120 | - } finally { | |
| 121 | - service.clearMailbox(recipient); | |
| 122 | - } | |
| 123 | - } | |
| 124 | -} |
deleted driver-examples/osgi/src/test/java/com/datastax/driver/osgi/VersionProvider.java +0 −59
| @@ -1,59 +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.osgi; | |
| 17 | - | |
| 18 | -import com.jcabi.manifests.Manifests; | |
| 19 | - | |
| 20 | -import java.util.regex.Matcher; | |
| 21 | -import java.util.regex.Pattern; | |
| 22 | - | |
| 23 | -/** | |
| 24 | - * Attempts to resolve the project version from the Bundle manifest. If not present, will throw RuntimeException | |
| 25 | - * on initialization. If this happens, try building with 'mvn compile' to generate the Bundle manifest. | |
| 26 | - * <p/> | |
| 27 | - * In IntelliJ you can have compile run after make by right clicking on 'compile' in the 'Maven Projects' tool window. | |
| 28 | - */ | |
| 29 | -public class VersionProvider { | |
| 30 | - | |
| 31 | - private static final Pattern versionPattern = Pattern.compile(("(\\d+.\\d+\\.\\d+)(.*)")); | |
| 32 | - | |
| 33 | - private static final String PROJECT_VERSION; | |
| 34 | - | |
| 35 | - static { | |
| 36 | - String bundleName = Manifests.read("Bundle-SymbolicName"); | |
| 37 | - if (bundleName.equals("com.datastax.driver.osgi")) { | |
| 38 | - String bundleVersion = Manifests.read("Bundle-Version"); | |
| 39 | - Matcher matcher = versionPattern.matcher(bundleVersion); | |
| 40 | - if (matcher.matches()) { | |
| 41 | - String majorVersion = matcher.group(1); | |
| 42 | - // Replace all instances of '.' after the main version with '-' to properly | |
| 43 | - // resolve the correct version. | |
| 44 | - String rest = matcher.group(2).replaceAll("\\.", "-"); | |
| 45 | - PROJECT_VERSION = majorVersion + rest; | |
| 46 | - } else { | |
| 47 | - // This should never happen, but if we are using a non X.Y.Z version number | |
| 48 | - // we'll just back off to the bundle version. | |
| 49 | - PROJECT_VERSION = bundleVersion; | |
| 50 | - } | |
| 51 | - } else { | |
| 52 | - throw new RuntimeException("Couldn't resolve bundle manifest (try building with mvn compile)"); | |
| 53 | - } | |
| 54 | - } | |
| 55 | - | |
| 56 | - public static String projectVersion() { | |
| 57 | - return PROJECT_VERSION; | |
| 58 | - } | |
| 59 | -} |
deleted driver-examples/osgi/src/test/resources/exam.properties +0 −18
| @@ -1,18 +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 | - | |
| 17 | -pax.exam.system=test | |
| 18 | -pax.exam.logging=none | |
| No newline at the end of the file |
deleted driver-examples/osgi/src/test/resources/logback.xml +0 −27
| @@ -1,27 +0,0 @@ | ||
| 1 | -<!-- | |
| 2 | - | |
| 3 | - Copyright (C) 2012-2015 DataStax Inc. | |
| 4 | - | |
| 5 | - Licensed under the Apache License, Version 2.0 (the "License"); | |
| 6 | - you may not use this file except in compliance with the License. | |
| 7 | - You may obtain a copy of the License at | |
| 8 | - | |
| 9 | - http://www.apache.org/licenses/LICENSE-2.0 | |
| 10 | - | |
| 11 | - Unless required by applicable law or agreed to in writing, software | |
| 12 | - distributed under the License is distributed on an "AS IS" BASIS, | |
| 13 | - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 14 | - See the License for the specific language governing permissions and | |
| 15 | - limitations under the License. | |
| 16 | - | |
| 17 | ---> | |
| 18 | -<configuration> | |
| 19 | - <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> | |
| 20 | - <layout class="ch.qos.logback.classic.PatternLayout"> | |
| 21 | - <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> | |
| 22 | - </layout> | |
| 23 | - </appender> | |
| 24 | - <root level="INFO"> | |
| 25 | - <appender-ref ref="STDOUT"/> | |
| 26 | - </root> | |
| 27 | -</configuration> |
modified driver-examples/pom.xml +48 −30
| @@ -15,16 +15,17 @@ | ||
| 15 | 15 | limitations under the License. |
| 16 | 16 | |
| 17 | 17 | --> |
| 18 | -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 19 | - <modelVersion>4.0.0</modelVersion> | |
| 18 | +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
| 20 | 19 | <parent> |
| 21 | - <groupId>com.datastax.cassandra</groupId> | |
| 22 | 20 | <artifactId>cassandra-driver-parent</artifactId> |
| 21 | + <groupId>com.datastax.cassandra</groupId> | |
| 23 | 22 | <version>3.0.1-SNAPSHOT</version> |
| 24 | 23 | </parent> |
| 25 | - <artifactId>cassandra-driver-examples-parent</artifactId> | |
| 26 | - <packaging>pom</packaging> | |
| 27 | - <name>DataStax Java Driver for Apache Cassandra Examples</name> | |
| 24 | + <modelVersion>4.0.0</modelVersion> | |
| 25 | + | |
| 26 | + <artifactId>cassandra-driver-examples</artifactId> | |
| 27 | + | |
| 28 | + <name>DataStax Java Driver for Apache Cassandra - Examples</name> | |
| 28 | 29 | <description>A collection of examples to demonstrate DataStax Java Driver for Apache Cassandra.</description> |
| 29 | 30 | <url>https://github.com/datastax/java-driver</url> |
| 30 | 31 | |
| @@ -32,36 +33,26 @@ | ||
| 32 | 33 | <main.basedir>${project.parent.basedir}</main.basedir> |
| 33 | 34 | </properties> |
| 34 | 35 | |
| 35 | - <modules> | |
| 36 | - <module>stress</module> | |
| 37 | - <module>osgi</module> | |
| 38 | - </modules> | |
| 36 | + <dependencies> | |
| 39 | 37 | |
| 40 | - <licenses> | |
| 41 | - <license> | |
| 42 | - <name>Apache 2</name> | |
| 43 | - <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> | |
| 44 | - <distribution>repo</distribution> | |
| 45 | - <comments>Apache License Version 2.0</comments> | |
| 46 | - </license> | |
| 47 | - </licenses> | |
| 38 | + <dependency> | |
| 39 | + <groupId>com.datastax.cassandra</groupId> | |
| 40 | + <artifactId>cassandra-driver-core</artifactId> | |
| 41 | + <version>${project.parent.version}</version> | |
| 42 | + </dependency> | |
| 48 | 43 | |
| 49 | - <scm> | |
| 50 | - <connection>scm:git:git@github.com:datastax/java-driver.git</connection> | |
| 51 | - <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection> | |
| 52 | - <url>https://github.com/datastax/java-driver</url> | |
| 53 | - <tag>HEAD</tag> | |
| 54 | - </scm> | |
| 44 | + <dependency> | |
| 45 | + <groupId>ch.qos.logback</groupId> | |
| 46 | + <artifactId>logback-classic</artifactId> | |
| 47 | + <version>1.1.3</version> | |
| 48 | + </dependency> | |
| 55 | 49 | |
| 56 | - <developers> | |
| 57 | - <developer> | |
| 58 | - <name>Various</name> | |
| 59 | - <organization>DataStax</organization> | |
| 60 | - </developer> | |
| 61 | - </developers> | |
| 50 | + </dependencies> | |
| 62 | 51 | |
| 63 | 52 | <build> |
| 53 | + | |
| 64 | 54 | <plugins> |
| 55 | + | |
| 65 | 56 | <plugin> |
| 66 | 57 | <groupId>org.apache.maven.plugins</groupId> |
| 67 | 58 | <artifactId>maven-install-plugin</artifactId> |
| @@ -70,6 +61,7 @@ | ||
| 70 | 61 | <skip>true</skip> |
| 71 | 62 | </configuration> |
| 72 | 63 | </plugin> |
| 64 | + | |
| 73 | 65 | <plugin> |
| 74 | 66 | <groupId>org.apache.maven.plugins</groupId> |
| 75 | 67 | <artifactId>maven-deploy-plugin</artifactId> |
| @@ -78,6 +70,32 @@ | ||
| 78 | 70 | <skip>true</skip> |
| 79 | 71 | </configuration> |
| 80 | 72 | </plugin> |
| 73 | + | |
| 81 | 74 | </plugins> |
| 75 | + | |
| 82 | 76 | </build> |
| 77 | + | |
| 78 | + <licenses> | |
| 79 | + <license> | |
| 80 | + <name>Apache 2</name> | |
| 81 | + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> | |
| 82 | + <distribution>repo</distribution> | |
| 83 | + <comments>Apache License Version 2.0</comments> | |
| 84 | + </license> | |
| 85 | + </licenses> | |
| 86 | + | |
| 87 | + <scm> | |
| 88 | + <connection>scm:git:git@github.com:datastax/java-driver.git</connection> | |
| 89 | + <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection> | |
| 90 | + <url>https://github.com/datastax/java-driver</url> | |
| 91 | + <tag>HEAD</tag> | |
| 92 | + </scm> | |
| 93 | + | |
| 94 | + <developers> | |
| 95 | + <developer> | |
| 96 | + <name>Various</name> | |
| 97 | + <organization>DataStax</organization> | |
| 98 | + </developer> | |
| 99 | + </developers> | |
| 100 | + | |
| 83 | 101 | </project> |
added driver-examples/src/main/java/com/datastax/driver/examples/basic/CreateAndPopulateKeyspace.java +166 −0
| @@ -0,0 +1,166 @@ | ||
| 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.examples.basic; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.Cluster; | |
| 19 | +import com.datastax.driver.core.ResultSet; | |
| 20 | +import com.datastax.driver.core.Row; | |
| 21 | +import com.datastax.driver.core.Session; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * Creates a keyspace and tables, and loads some data into them. | |
| 25 | + * <p/> | |
| 26 | + * Preconditions: | |
| 27 | + * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT. | |
| 28 | + * <p/> | |
| 29 | + * Side effects: | |
| 30 | + * - creates a new keyspace "simplex" in the cluster. It a keyspace with this name already exists, it will be reused; | |
| 31 | + * - creates two tables "simplex.songs" and "simplex.playlists". If they exist already, they will be reused; | |
| 32 | + * - inserts a row in each table. | |
| 33 | + * | |
| 34 | + * @see <a href="http://datastax.github.io/java-driver/manual/">Java driver online manual</a> | |
| 35 | + */ | |
| 36 | +public class CreateAndPopulateKeyspace { | |
| 37 | + | |
| 38 | + static String[] CONTACT_POINTS = {"127.0.0.1"}; | |
| 39 | + static int PORT = 9042; | |
| 40 | + | |
| 41 | + public static void main(String[] args) { | |
| 42 | + | |
| 43 | + CreateAndPopulateKeyspace client = new CreateAndPopulateKeyspace(); | |
| 44 | + | |
| 45 | + try { | |
| 46 | + | |
| 47 | + client.connect(CONTACT_POINTS, PORT); | |
| 48 | + client.createSchema(); | |
| 49 | + client.loadData(); | |
| 50 | + client.querySchema(); | |
| 51 | + | |
| 52 | + } finally { | |
| 53 | + client.close(); | |
| 54 | + } | |
| 55 | + } | |
| 56 | + | |
| 57 | + private Cluster cluster; | |
| 58 | + | |
| 59 | + private Session session; | |
| 60 | + | |
| 61 | + /** | |
| 62 | + * Initiates a connection to the cluster | |
| 63 | + * specified by the given contact point. | |
| 64 | + * | |
| 65 | + * @param contactPoints the contact points to use. | |
| 66 | + * @param port the port to use. | |
| 67 | + */ | |
| 68 | + public void connect(String[] contactPoints, int port) { | |
| 69 | + | |
| 70 | + cluster = Cluster.builder() | |
| 71 | + .addContactPoints(contactPoints).withPort(port) | |
| 72 | + .build(); | |
| 73 | + | |
| 74 | + System.out.printf("Connected to cluster: %s%n", cluster.getMetadata().getClusterName()); | |
| 75 | + | |
| 76 | + session = cluster.connect(); | |
| 77 | + } | |
| 78 | + | |
| 79 | + /** | |
| 80 | + * Creates the schema (keyspace) and tables | |
| 81 | + * for this example. | |
| 82 | + */ | |
| 83 | + public void createSchema() { | |
| 84 | + | |
| 85 | + session.execute("CREATE KEYSPACE IF NOT EXISTS simplex WITH replication " + | |
| 86 | + "= {'class':'SimpleStrategy', 'replication_factor':1};"); | |
| 87 | + | |
| 88 | + session.execute( | |
| 89 | + "CREATE TABLE IF NOT EXISTS simplex.songs (" + | |
| 90 | + "id uuid PRIMARY KEY," + | |
| 91 | + "title text," + | |
| 92 | + "album text," + | |
| 93 | + "artist text," + | |
| 94 | + "tags set<text>," + | |
| 95 | + "data blob" + | |
| 96 | + ");"); | |
| 97 | + | |
| 98 | + session.execute( | |
| 99 | + "CREATE TABLE IF NOT EXISTS simplex.playlists (" + | |
| 100 | + "id uuid," + | |
| 101 | + "title text," + | |
| 102 | + "album text, " + | |
| 103 | + "artist text," + | |
| 104 | + "song_id uuid," + | |
| 105 | + "PRIMARY KEY (id, title, album, artist)" + | |
| 106 | + ");"); | |
| 107 | + } | |
| 108 | + | |
| 109 | + /** | |
| 110 | + * Inserts data into the tables. | |
| 111 | + */ | |
| 112 | + public void loadData() { | |
| 113 | + | |
| 114 | + session.execute( | |
| 115 | + "INSERT INTO simplex.songs (id, title, album, artist, tags) " + | |
| 116 | + "VALUES (" + | |
| 117 | + "756716f7-2e54-4715-9f00-91dcbea6cf50," + | |
| 118 | + "'La Petite Tonkinoise'," + | |
| 119 | + "'Bye Bye Blackbird'," + | |
| 120 | + "'Joséphine Baker'," + | |
| 121 | + "{'jazz', '2013'})" + | |
| 122 | + ";"); | |
| 123 | + | |
| 124 | + session.execute( | |
| 125 | + "INSERT INTO simplex.playlists (id, song_id, title, album, artist) " + | |
| 126 | + "VALUES (" + | |
| 127 | + "2cc9ccb7-6221-4ccb-8387-f22b6a1b354d," + | |
| 128 | + "756716f7-2e54-4715-9f00-91dcbea6cf50," + | |
| 129 | + "'La Petite Tonkinoise'," + | |
| 130 | + "'Bye Bye Blackbird'," + | |
| 131 | + "'Joséphine Baker'" + | |
| 132 | + ");"); | |
| 133 | + } | |
| 134 | + | |
| 135 | + /** | |
| 136 | + * Queries and displays data. | |
| 137 | + */ | |
| 138 | + public void querySchema() { | |
| 139 | + | |
| 140 | + ResultSet results = session.execute( | |
| 141 | + "SELECT * FROM simplex.playlists " + | |
| 142 | + "WHERE id = 2cc9ccb7-6221-4ccb-8387-f22b6a1b354d;"); | |
| 143 | + | |
| 144 | + System.out.printf("%-30s\t%-20s\t%-20s%n", "title", "album", "artist"); | |
| 145 | + System.out.println("-------------------------------+-----------------------+--------------------"); | |
| 146 | + | |
| 147 | + for (Row row : results) { | |
| 148 | + | |
| 149 | + System.out.printf("%-30s\t%-20s\t%-20s%n", | |
| 150 | + row.getString("title"), | |
| 151 | + row.getString("album"), | |
| 152 | + row.getString("artist")); | |
| 153 | + | |
| 154 | + } | |
| 155 | + | |
| 156 | + } | |
| 157 | + | |
| 158 | + /** | |
| 159 | + * Closes the session and the cluster. | |
| 160 | + */ | |
| 161 | + public void close() { | |
| 162 | + session.close(); | |
| 163 | + cluster.close(); | |
| 164 | + } | |
| 165 | + | |
| 166 | +} |
added driver-examples/src/main/java/com/datastax/driver/examples/basic/ReadCassandraVersion.java +72 −0
| @@ -0,0 +1,72 @@ | ||
| 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.examples.basic; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.Cluster; | |
| 19 | +import com.datastax.driver.core.ResultSet; | |
| 20 | +import com.datastax.driver.core.Row; | |
| 21 | +import com.datastax.driver.core.Session; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * Connects to a Cassandra cluster and extracts basic information from it. | |
| 25 | + * <p/> | |
| 26 | + * Preconditions: | |
| 27 | + * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT. | |
| 28 | + * <p/> | |
| 29 | + * Side effects: none. | |
| 30 | + * | |
| 31 | + * @see <a href="http://datastax.github.io/java-driver/manual/">Java driver online manual</a> | |
| 32 | + */ | |
| 33 | +public class ReadCassandraVersion { | |
| 34 | + | |
| 35 | + static String[] CONTACT_POINTS = {"127.0.0.1"}; | |
| 36 | + static int PORT = 9042; | |
| 37 | + | |
| 38 | + public static void main(String[] args) { | |
| 39 | + | |
| 40 | + Cluster cluster = null; | |
| 41 | + try { | |
| 42 | + // The Cluster object is the main entry point of the driver. | |
| 43 | + // It holds the known state of the actual Cassandra cluster (notably the Metadata). | |
| 44 | + // This class is thread-safe, you should create a single instance (per target Cassandra cluster), and share | |
| 45 | + // it throughout your application. | |
| 46 | + cluster = Cluster.builder() | |
| 47 | + .addContactPoints(CONTACT_POINTS).withPort(PORT) | |
| 48 | + .build(); | |
| 49 | + | |
| 50 | + // The Session is what you use to execute queries. Likewise, it is thread-safe and should be reused. | |
| 51 | + Session session = cluster.connect(); | |
| 52 | + | |
| 53 | + // We use execute to send a query to Cassandra. This returns a ResultSet, which is essentially a collection | |
| 54 | + // of Row objects. | |
| 55 | + ResultSet rs = session.execute("select release_version from system.local"); | |
| 56 | + // Extract the first row (which is the only one in this case). | |
| 57 | + Row row = rs.one(); | |
| 58 | + | |
| 59 | + // Extract the value of the first (and only) column from the row. | |
| 60 | + String releaseVersion = row.getString("release_version"); | |
| 61 | + System.out.printf("Cassandra version is: %s%n", releaseVersion); | |
| 62 | + | |
| 63 | + } finally { | |
| 64 | + // Close the cluster after we’re done with it. This will also close any session that was created from this | |
| 65 | + // cluster. | |
| 66 | + // This step is important because it frees underlying resources (TCP connections, thread pools...). In a | |
| 67 | + // real application, you would typically do this at shutdown (for example, when undeploying your webapp). | |
| 68 | + if (cluster != null) | |
| 69 | + cluster.close(); | |
| 70 | + } | |
| 71 | + } | |
| 72 | +} |
added driver-examples/src/main/java/com/datastax/driver/examples/basic/ReadTopologyAndSchemaMetadata.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.examples.basic; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.*; | |
| 19 | + | |
| 20 | +/** | |
| 21 | + * Gathers information about a Cassandra cluster's topology (which nodes belong to the cluster) and schema (what | |
| 22 | + * keyspaces, tables, etc. exist in this cluster). | |
| 23 | + * <p/> | |
| 24 | + * Preconditions: | |
| 25 | + * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT. | |
| 26 | + * <p/> | |
| 27 | + * Side effects: none. | |
| 28 | + * | |
| 29 | + * @see <a href="http://datastax.github.io/java-driver/manual/">Java driver online manual</a> | |
| 30 | + */ | |
| 31 | +public class ReadTopologyAndSchemaMetadata { | |
| 32 | + | |
| 33 | + static String[] CONTACT_POINTS = {"127.0.0.1"}; | |
| 34 | + static int PORT = 9042; | |
| 35 | + | |
| 36 | + public static void main(String[] args) { | |
| 37 | + | |
| 38 | + Cluster cluster = null; | |
| 39 | + try { | |
| 40 | + cluster = Cluster.builder() | |
| 41 | + .addContactPoints(CONTACT_POINTS).withPort(PORT) | |
| 42 | + .build(); | |
| 43 | + | |
| 44 | + Metadata metadata = cluster.getMetadata(); | |
| 45 | + System.out.printf("Connected to cluster: %s%n", metadata.getClusterName()); | |
| 46 | + | |
| 47 | + for (Host host : metadata.getAllHosts()) { | |
| 48 | + System.out.printf("Datatacenter: %s; Host: %s; Rack: %s%n", | |
| 49 | + host.getDatacenter(), host.getAddress(), host.getRack()); | |
| 50 | + } | |
| 51 | + | |
| 52 | + for (KeyspaceMetadata keyspace : metadata.getKeyspaces()) { | |
| 53 | + for (TableMetadata table : keyspace.getTables()) { | |
| 54 | + System.out.printf("Keyspace: %s; Table: %s%n", | |
| 55 | + keyspace.getName(), table.getName()); | |
| 56 | + } | |
| 57 | + } | |
| 58 | + | |
| 59 | + } finally { | |
| 60 | + if (cluster != null) | |
| 61 | + cluster.close(); | |
| 62 | + } | |
| 63 | + } | |
| 64 | +} |
added driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java +253 −0
| @@ -0,0 +1,253 @@ | ||
| 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.examples.datatypes; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.*; | |
| 19 | +import com.datastax.driver.core.utils.Bytes; | |
| 20 | +import com.google.common.collect.ImmutableMap; | |
| 21 | + | |
| 22 | +import java.io.*; | |
| 23 | +import java.nio.ByteBuffer; | |
| 24 | +import java.nio.channels.FileChannel; | |
| 25 | +import java.util.Map; | |
| 26 | + | |
| 27 | +/** | |
| 28 | + * Inserts and retrieves values in BLOB columns. | |
| 29 | + * <p/> | |
| 30 | + * By default, the Java driver maps this type to {@link java.nio.ByteBuffer}. The ByteBuffer API is a bit tricky to use | |
| 31 | + * at times, so we will show common pitfalls as well. We strongly recommend that you read the {@link java.nio.Buffer} | |
| 32 | + * and {@link ByteBuffer} API docs and become familiar with the capacity, limit and position properties. | |
| 33 | + * <a href="http://tutorials.jenkov.com/java-nio/buffers.html">This tutorial</a> might also help. | |
| 34 | + * <p/> | |
| 35 | + * Preconditions: | |
| 36 | + * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT; | |
| 37 | + * - FILE references an existing file. | |
| 38 | + * <p/> | |
| 39 | + * Side effects: | |
| 40 | + * - creates a new keyspace "examples" in the cluster. It a keyspace with this name already exists, it will be reused; | |
| 41 | + * - creates a table "examples.blobs". If it already exists, it will be reused; | |
| 42 | + * - inserts data in the table. | |
| 43 | + */ | |
| 44 | +public class Blobs { | |
| 45 | + | |
| 46 | + static String[] CONTACT_POINTS = {"127.0.0.1"}; | |
| 47 | + static int PORT = 9042; | |
| 48 | + | |
| 49 | + static File FILE = new File(Blobs.class.getResource("/cassandra_logo.png").getFile()); | |
| 50 | + | |
| 51 | + public static void main(String[] args) throws IOException { | |
| 52 | + Cluster cluster = null; | |
| 53 | + try { | |
| 54 | + cluster = Cluster.builder() | |
| 55 | + .addContactPoints(CONTACT_POINTS).withPort(PORT) | |
| 56 | + .build(); | |
| 57 | + Session session = cluster.connect(); | |
| 58 | + | |
| 59 | + createSchema(session); | |
| 60 | + allocateAndInsert(session); | |
| 61 | + retrieveSimpleColumn(session); | |
| 62 | + retrieveMapColumn(session); | |
| 63 | + insertConcurrent(session); | |
| 64 | + insertFromAndRetrieveToFile(session); | |
| 65 | + } finally { | |
| 66 | + if (cluster != null) cluster.close(); | |
| 67 | + } | |
| 68 | + } | |
| 69 | + | |
| 70 | + private static void createSchema(Session session) { | |
| 71 | + session.execute("CREATE KEYSPACE IF NOT EXISTS examples " + | |
| 72 | + "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 73 | + session.execute("CREATE TABLE IF NOT EXISTS examples.blobs(k int PRIMARY KEY, b blob, m map<text, blob>)"); | |
| 74 | + } | |
| 75 | + | |
| 76 | + private static void allocateAndInsert(Session session) { | |
| 77 | + // One way to get a byte buffer is to allocate it and fill it yourself: | |
| 78 | + ByteBuffer buffer = ByteBuffer.allocate(16); | |
| 79 | + while (buffer.hasRemaining()) | |
| 80 | + buffer.put((byte) 0xFF); | |
| 81 | + | |
| 82 | + // Don't forget to flip! The driver expects a buffer that is ready for reading. That is, it will consider all | |
| 83 | + // the data between buffer.position() and buffer.limit(). | |
| 84 | + // Right now we are positioned at the end because we just finished writing, so if we passed the buffer as-is it | |
| 85 | + // would appear to be empty: | |
| 86 | + assert buffer.limit() - buffer.position() == 0; | |
| 87 | + | |
| 88 | + buffer.flip(); | |
| 89 | + // Now position is back to the beginning, so the driver will see all 16 bytes. | |
| 90 | + assert buffer.limit() - buffer.position() == 16; | |
| 91 | + | |
| 92 | + session.execute("INSERT INTO examples.blobs (k, b, m) VALUES (1, ?, ?)", | |
| 93 | + buffer, ImmutableMap.of("test", buffer)); | |
| 94 | + } | |
| 95 | + | |
| 96 | + private static void retrieveSimpleColumn(Session session) { | |
| 97 | + Row row = session.execute("SELECT b, m FROM examples.blobs WHERE k = 1").one(); | |
| 98 | + | |
| 99 | + ByteBuffer buffer = row.getBytes("b"); | |
| 100 | + | |
| 101 | + // The driver always returns buffers that are ready for reading. | |
| 102 | + assert buffer.limit() - buffer.position() == 16; | |
| 103 | + | |
| 104 | + // One way to read from the buffer is to use absolute getters. Do NOT start reading at index 0, as the buffer | |
| 105 | + // might start at a different position (we'll see an example of that later). | |
| 106 | + for (int i = buffer.position(); i < buffer.limit(); i++) { | |
| 107 | + byte b = buffer.get(i); | |
| 108 | + assert b == (byte) 0xFF; | |
| 109 | + } | |
| 110 | + | |
| 111 | + // Another way is to use relative getters. | |
| 112 | + while (buffer.hasRemaining()) { | |
| 113 | + byte b = buffer.get(); | |
| 114 | + assert b == (byte) 0xFF; | |
| 115 | + } | |
| 116 | + // Note that relative getters change the position, so when we're done reading we're at the end again. | |
| 117 | + assert buffer.position() == buffer.limit(); | |
| 118 | + | |
| 119 | + // Reset the position for the next operation. | |
| 120 | + buffer.flip(); | |
| 121 | + | |
| 122 | + // Yet another way is to convert the buffer to a byte array. Do NOT use buffer.array(), because it returns the | |
| 123 | + // buffer's *backing array*, which is not the same thing as its contents: | |
| 124 | + // - not all byte buffers have backing arrays | |
| 125 | + // - even then, the backing array might be larger than the buffer's contents | |
| 126 | + // | |
| 127 | + // The driver provides a utility method that handles those details for you: | |
| 128 | + byte[] array = Bytes.getArray(buffer); | |
| 129 | + assert array.length == 16; | |
| 130 | + for (byte b : array) { | |
| 131 | + assert b == (byte) 0xFF; | |
| 132 | + } | |
| 133 | + } | |
| 134 | + | |
| 135 | + private static void retrieveMapColumn(Session session) { | |
| 136 | + Row row = session.execute("SELECT b, m FROM examples.blobs WHERE k = 1").one(); | |
| 137 | + | |
| 138 | + // The map columns illustrates the pitfalls with position() and array(). | |
| 139 | + Map<String, ByteBuffer> m = row.getMap("m", String.class, ByteBuffer.class); | |
| 140 | + ByteBuffer buffer = m.get("test"); | |
| 141 | + | |
| 142 | + // We did get back a buffer that contains 16 bytes as expected. | |
| 143 | + assert buffer.limit() - buffer.position() == 16; | |
| 144 | + // However, it is not positioned at 0. And you can also see that its backing array contains more than 16 bytes. | |
| 145 | + // What happens is that the buffer is a "view" of the last 16 of a 32-byte array. | |
| 146 | + // This is an implementation detail and you shouldn't have to worry about it if you process the buffer correctly | |
| 147 | + // (don't iterate from 0, use Bytes.getArray()). | |
| 148 | + assert buffer.position() == 16; | |
| 149 | + assert buffer.array().length == 32; | |
| 150 | + } | |
| 151 | + | |
| 152 | + private static void insertConcurrent(Session session) { | |
| 153 | + PreparedStatement preparedStatement = session.prepare("INSERT INTO examples.blobs (k, b) VALUES (1, :b)"); | |
| 154 | + | |
| 155 | + // This is another convenient utility provided by the driver. It's useful for tests. | |
| 156 | + ByteBuffer buffer = Bytes.fromHexString("0xffffff"); | |
| 157 | + | |
| 158 | + // When you pass a byte buffer to a bound statement, it creates a shallow copy internally with the | |
| 159 | + // buffer.duplicate() method. | |
| 160 | + BoundStatement boundStatement = preparedStatement.bind(); | |
| 161 | + boundStatement.setBytes("b", buffer); | |
| 162 | + | |
| 163 | + // This means you can now move in the original buffer, without affecting the insertion if it happens later. | |
| 164 | + buffer.position(buffer.limit()); | |
| 165 | + | |
| 166 | + session.execute(boundStatement); | |
| 167 | + Row row = session.execute("SELECT b FROM examples.blobs WHERE k = 1").one(); | |
| 168 | + assert Bytes.toHexString(row.getBytes("b")).equals("0xffffff"); | |
| 169 | + | |
| 170 | + buffer.flip(); | |
| 171 | + | |
| 172 | + // HOWEVER duplicate() only performs a shallow copy. The two buffers still share the same contents. So if you | |
| 173 | + // modify the contents of the original buffer, this will affect another execution of the bound statement. | |
| 174 | + buffer.put(0, (byte) 0xaa); | |
| 175 | + session.execute(boundStatement); | |
| 176 | + row = session.execute("SELECT b FROM examples.blobs WHERE k = 1").one(); | |
| 177 | + assert Bytes.toHexString(row.getBytes("b")).equals("0xaaffff"); | |
| 178 | + | |
| 179 | + // This will also happen if you use the async API, e.g. create the bound statement, call executeAsync() on it | |
| 180 | + // and reuse the buffer immediately. | |
| 181 | + | |
| 182 | + // If you reuse buffers concurrently and want to avoid those issues, perform a deep copy of the buffer before | |
| 183 | + // passing it to the bound statement. | |
| 184 | + int startPosition = buffer.position(); | |
| 185 | + ByteBuffer buffer2 = ByteBuffer.allocate(buffer.limit() - startPosition); | |
| 186 | + buffer2.put(buffer); | |
| 187 | + buffer.position(startPosition); | |
| 188 | + buffer2.flip(); | |
| 189 | + boundStatement.setBytes("b", buffer2); | |
| 190 | + session.execute(boundStatement); | |
| 191 | + | |
| 192 | + // Note: unlike BoundStatement, SimpleStatement does not duplicate its arguments, so even the position will be | |
| 193 | + // affected if you change it before executing the statement. Again, resort to deep copies if required. | |
| 194 | + } | |
| 195 | + | |
| 196 | + private static void insertFromAndRetrieveToFile(Session session) throws IOException { | |
| 197 | + ByteBuffer buffer = readAll(FILE); | |
| 198 | + session.execute("INSERT INTO examples.blobs (k, b) VALUES (1, ?)", buffer); | |
| 199 | + | |
| 200 | + File tmpFile = File.createTempFile("blob", ".png"); | |
| 201 | + System.out.printf("Writing retrieved buffer to %s%n", tmpFile.getAbsoluteFile()); | |
| 202 | + | |
| 203 | + Row row = session.execute("SELECT b FROM examples.blobs WHERE k = 1").one(); | |
| 204 | + writeAll(row.getBytes("b"), tmpFile); | |
| 205 | + } | |
| 206 | + | |
| 207 | + // Note: | |
| 208 | + // - this is written with Java 6 APIs; if you're on a more recent version this can be improved (try-with-resources, | |
| 209 | + // new-new io...) | |
| 210 | + // - this reads the whole file in memory in one go. If your file does not fit in memory you should probably not | |
| 211 | + // insert it into Cassandra either ;) | |
| 212 | + private static ByteBuffer readAll(File file) throws IOException { | |
| 213 | + FileInputStream inputStream = null; | |
| 214 | + boolean threw = false; | |
| 215 | + try { | |
| 216 | + inputStream = new FileInputStream(file); | |
| 217 | + FileChannel channel = inputStream.getChannel(); | |
| 218 | + ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); | |
| 219 | + channel.read(buffer); | |
| 220 | + buffer.flip(); | |
| 221 | + return buffer; | |
| 222 | + } catch (IOException e) { | |
| 223 | + threw = true; | |
| 224 | + throw e; | |
| 225 | + } finally { | |
| 226 | + close(inputStream, threw); | |
| 227 | + } | |
| 228 | + } | |
| 229 | + | |
| 230 | + private static void writeAll(ByteBuffer buffer, File file) throws IOException { | |
| 231 | + FileOutputStream outputStream = null; | |
| 232 | + boolean threw = false; | |
| 233 | + try { | |
| 234 | + outputStream = new FileOutputStream(file); | |
| 235 | + FileChannel channel = outputStream.getChannel(); | |
| 236 | + channel.write(buffer); | |
| 237 | + } catch (IOException e) { | |
| 238 | + threw = true; | |
| 239 | + throw e; | |
| 240 | + } finally { | |
| 241 | + close(outputStream, threw); | |
| 242 | + } | |
| 243 | + } | |
| 244 | + | |
| 245 | + private static void close(Closeable inputStream, boolean threw) throws IOException { | |
| 246 | + if (inputStream != null) | |
| 247 | + try { | |
| 248 | + inputStream.close(); | |
| 249 | + } catch (IOException e) { | |
| 250 | + if (!threw) throw e; // else preserve original exception | |
| 251 | + } | |
| 252 | + } | |
| 253 | +} |
added driver-examples/src/main/resources/cassandra_logo.png +0 −0
Binary content is not shown. View the file.
added driver-examples/src/main/resources/logback.xml +39 −0
| @@ -0,0 +1,39 @@ | ||
| 1 | +<!-- | |
| 2 | + | |
| 3 | + Copyright (C) 2012-2015 DataStax Inc. | |
| 4 | + | |
| 5 | + Licensed under the Apache License, Version 2.0 (the "License"); | |
| 6 | + you may not use this file except in compliance with the License. | |
| 7 | + You may obtain a copy of the License at | |
| 8 | + | |
| 9 | + http://www.apache.org/licenses/LICENSE-2.0 | |
| 10 | + | |
| 11 | + Unless required by applicable law or agreed to in writing, software | |
| 12 | + distributed under the License is distributed on an "AS IS" BASIS, | |
| 13 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 14 | + See the License for the specific language governing permissions and | |
| 15 | + limitations under the License. | |
| 16 | + | |
| 17 | +--> | |
| 18 | +<configuration> | |
| 19 | + | |
| 20 | + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> | |
| 21 | + | |
| 22 | + <!-- encoders are assigned the type | |
| 23 | + ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> | |
| 24 | + <encoder> | |
| 25 | + <pattern>%-5level - %msg%n</pattern> | |
| 26 | + </encoder> | |
| 27 | + | |
| 28 | + </appender> | |
| 29 | + | |
| 30 | + <!-- adjust the driver's log verbosity; see | |
| 31 | + http://datastax.github.io/java-driver/manual/logging/ | |
| 32 | + for more information --> | |
| 33 | + <logger name="com.datastax.driver.core" level="WARN"/> | |
| 34 | + | |
| 35 | + <root level="INFO"> | |
| 36 | + <appender-ref ref="STDOUT"/> | |
| 37 | + </root> | |
| 38 | + | |
| 39 | +</configuration> |
deleted driver-examples/stress/README.md +0 −25
| @@ -1,25 +0,0 @@ | ||
| 1 | -# Stress application | |
| 2 | - | |
| 3 | -A simple example application that uses the java driver to stress test | |
| 4 | -Cassandra. This also somewhat stress test the java driver as a result. | |
| 5 | - | |
| 6 | -Please note that this simple example is far from being a complete stress | |
| 7 | -application. In particular it currently supports a very limited number of | |
| 8 | -stress scenario. | |
| 9 | - | |
| 10 | -## Usage | |
| 11 | - | |
| 12 | -You will need to build the stress application fist: | |
| 13 | - | |
| 14 | - ./bin/build | |
| 15 | - | |
| 16 | -After which you can run it using for instance: | |
| 17 | - | |
| 18 | - ./bin/stress insert_prepared | |
| 19 | - | |
| 20 | -Of course, you will need to have at least one Cassandra node running (on | |
| 21 | -127.0.0.1 by default) for this to work. Please refer to: | |
| 22 | - | |
| 23 | - ./bin/stress -h | |
| 24 | - | |
| 25 | -for more details on the options available. |
deleted driver-examples/stress/bin/build +0 −36
| @@ -1,36 +0,0 @@ | ||
| 1 | -#!/bin/sh | |
| 2 | - | |
| 3 | -SCRIPT_DIR=$( cd "$( dirname "$0" )" && pwd ) | |
| 4 | -CURRENT_DIR=$( pwd ) | |
| 5 | - | |
| 6 | -LOG_FILE="$CURRENT_DIR/stress_build.log" | |
| 7 | -[ -f $LOG_FILE ] && rm $LOG_FILE | |
| 8 | - | |
| 9 | -echo "Building java driver ..." | |
| 10 | -echo "-- Driver build --\n" > $LOG_FILE | |
| 11 | - | |
| 12 | -cd $SCRIPT_DIR/../../.. | |
| 13 | -mvn clean install -Dmaven.test.skip=true >> $LOG_FILE 2>&1 | |
| 14 | -EXIT_CODE=$? | |
| 15 | -if [ $EXIT_CODE -ne 0 ]; | |
| 16 | -then | |
| 17 | - echo "Error building driver. See $LOG_FILE for details." 1>&2 | |
| 18 | - cd $CURRENT_DIR | |
| 19 | - exit $EXIT_CODE | |
| 20 | -fi | |
| 21 | - | |
| 22 | -echo "Building stress application ..." | |
| 23 | -echo "\n-- Stress build --\n" >> $LOG_FILE | |
| 24 | - | |
| 25 | -cd $SCRIPT_DIR/.. | |
| 26 | -mvn package assembly:single >> $LOG_FILE 2>&1 | |
| 27 | -EXIT_CODE=$? | |
| 28 | -if [ $EXIT_CODE -ne 0 ]; | |
| 29 | -then | |
| 30 | - echo "Error building stress application. See $LOG_FILE for details." 1>&2 | |
| 31 | - cd $CURRENT_DIR | |
| 32 | - exit $EXIT_CODE | |
| 33 | -fi | |
| 34 | - | |
| 35 | -cd $CURRENT_DIR | |
| 36 | -rm $LOG_FILE |
deleted driver-examples/stress/bin/stress +0 −30
| @@ -1,30 +0,0 @@ | ||
| 1 | -#!/bin/sh | |
| 2 | - | |
| 3 | -SCRIPT_DIR=$( cd "$( dirname "$0" )" && pwd ) | |
| 4 | -CURRENT_DIR=$( pwd ) | |
| 5 | - | |
| 6 | -# Use $JAVA_HOME if set | |
| 7 | -if [ -n "$JAVA_HOME" ]; then | |
| 8 | - JAVA="$JAVA_HOME/bin/java" | |
| 9 | -else | |
| 10 | - JAVA=java | |
| 11 | -fi | |
| 12 | - | |
| 13 | -if [ "x$STRESS_JAR" = "x" ]; then | |
| 14 | - | |
| 15 | - STRESS_JAR="$SCRIPT_DIR/../target/cassandra-driver-examples-stress-*-jar-with-dependencies.jar" | |
| 16 | - | |
| 17 | - if [ ! -f $STRESS_JAR ]; then | |
| 18 | - # Trash the version file in case there was some crap in it | |
| 19 | - RELATIVE_SCRIPT_DIR=`dirname $0` | |
| 20 | - echo "Stress application does not seem to be build, try $RELATIVE_SCRIPT_DIR/build first" 1>&2 | |
| 21 | - exit 1 | |
| 22 | - fi | |
| 23 | -else | |
| 24 | - if [ ! -f $STRESS_JAR ]; then | |
| 25 | - echo "Cannot find file $STRESS_JAR" 1>&2 | |
| 26 | - exit 1 | |
| 27 | - fi | |
| 28 | -fi | |
| 29 | - | |
| 30 | -"$JAVA" -Dlog4j.configuration="$SCRIPT_DIR/../conf/log4j.properties" -jar $STRESS_JAR $@ |
deleted driver-examples/stress/pom.xml +0 −109
| @@ -1,109 +0,0 @@ | ||
| 1 | -<!-- | |
| 2 | - | |
| 3 | - Copyright (C) 2012-2015 DataStax Inc. | |
| 4 | - | |
| 5 | - Licensed under the Apache License, Version 2.0 (the "License"); | |
| 6 | - you may not use this file except in compliance with the License. | |
| 7 | - You may obtain a copy of the License at | |
| 8 | - | |
| 9 | - http://www.apache.org/licenses/LICENSE-2.0 | |
| 10 | - | |
| 11 | - Unless required by applicable law or agreed to in writing, software | |
| 12 | - distributed under the License is distributed on an "AS IS" BASIS, | |
| 13 | - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 14 | - See the License for the specific language governing permissions and | |
| 15 | - limitations under the License. | |
| 16 | - | |
| 17 | ---> | |
| 18 | -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 19 | - <modelVersion>4.0.0</modelVersion> | |
| 20 | - <parent> | |
| 21 | - <groupId>com.datastax.cassandra</groupId> | |
| 22 | - <artifactId>cassandra-driver-examples-parent</artifactId> | |
| 23 | - <version>3.0.1-SNAPSHOT</version> | |
| 24 | - </parent> | |
| 25 | - <artifactId>cassandra-driver-examples-stress</artifactId> | |
| 26 | - <packaging>jar</packaging> | |
| 27 | - <name>DataStax Java Driver for Apache Cassandra Examples - Stress</name> | |
| 28 | - <description>A stress test example for DataStax Java Driver for Apache Cassandra.</description> | |
| 29 | - <url>https://github.com/datastax/java-driver</url> | |
| 30 | - | |
| 31 | - <properties> | |
| 32 | - <main.basedir>${project.parent.parent.basedir}</main.basedir> | |
| 33 | - </properties> | |
| 34 | - | |
| 35 | - <dependencies> | |
| 36 | - <dependency> | |
| 37 | - <groupId>com.datastax.cassandra</groupId> | |
| 38 | - <artifactId>cassandra-driver-core</artifactId> | |
| 39 | - <version>3.0.1-SNAPSHOT</version> | |
| 40 | - </dependency> | |
| 41 | - | |
| 42 | - <dependency> | |
| 43 | - <groupId>com.yammer.metrics</groupId> | |
| 44 | - <artifactId>metrics-core</artifactId> | |
| 45 | - <version>2.2.0</version> | |
| 46 | - </dependency> | |
| 47 | - | |
| 48 | - <dependency> | |
| 49 | - <groupId>net.sf.jopt-simple</groupId> | |
| 50 | - <artifactId>jopt-simple</artifactId> | |
| 51 | - <version>4.5</version> | |
| 52 | - </dependency> | |
| 53 | - | |
| 54 | - <dependency> | |
| 55 | - <groupId>log4j</groupId> | |
| 56 | - <artifactId>log4j</artifactId> | |
| 57 | - <version>1.2.17</version> | |
| 58 | - </dependency> | |
| 59 | - | |
| 60 | - <dependency> | |
| 61 | - <groupId>org.slf4j</groupId> | |
| 62 | - <artifactId>slf4j-log4j12</artifactId> | |
| 63 | - <version>1.7.5</version> | |
| 64 | - </dependency> | |
| 65 | - </dependencies> | |
| 66 | - | |
| 67 | - <build> | |
| 68 | - <plugins> | |
| 69 | - <plugin> | |
| 70 | - <artifactId>maven-assembly-plugin</artifactId> | |
| 71 | - <version>2.4</version> | |
| 72 | - <configuration> | |
| 73 | - <archive> | |
| 74 | - <manifest> | |
| 75 | - <mainClass>com.datastax.driver.stress.Stress</mainClass> | |
| 76 | - </manifest> | |
| 77 | - </archive> | |
| 78 | - <descriptorRefs> | |
| 79 | - <descriptorRef>jar-with-dependencies</descriptorRef> | |
| 80 | - </descriptorRefs> | |
| 81 | - </configuration> | |
| 82 | - </plugin> | |
| 83 | - </plugins> | |
| 84 | - </build> | |
| 85 | - | |
| 86 | - <licenses> | |
| 87 | - <license> | |
| 88 | - <name>Apache 2</name> | |
| 89 | - <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> | |
| 90 | - <distribution>repo</distribution> | |
| 91 | - <comments>Apache License Version 2.0</comments> | |
| 92 | - </license> | |
| 93 | - </licenses> | |
| 94 | - | |
| 95 | - <scm> | |
| 96 | - <connection>scm:git:git@github.com:datastax/java-driver.git</connection> | |
| 97 | - <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection> | |
| 98 | - <url>https://github.com/datastax/java-driver</url> | |
| 99 | - <tag>HEAD</tag> | |
| 100 | - </scm> | |
| 101 | - | |
| 102 | - <developers> | |
| 103 | - <developer> | |
| 104 | - <name>Various</name> | |
| 105 | - <organization>DataStax</organization> | |
| 106 | - </developer> | |
| 107 | - </developers> | |
| 108 | -</project> | |
| 109 | - |
deleted driver-examples/stress/src/main/java/com/datastax/driver/stress/AsynchronousConsumer.java +0 −98
| @@ -1,98 +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.stress; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.ResultSet; | |
| 19 | -import com.datastax.driver.core.ResultSetFuture; | |
| 20 | -import com.datastax.driver.core.Session; | |
| 21 | -import com.google.common.util.concurrent.FutureCallback; | |
| 22 | -import com.google.common.util.concurrent.Futures; | |
| 23 | - | |
| 24 | -import java.util.concurrent.CountDownLatch; | |
| 25 | -import java.util.concurrent.ExecutorService; | |
| 26 | -import java.util.concurrent.Executors; | |
| 27 | - | |
| 28 | -import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; | |
| 29 | - | |
| 30 | -public class AsynchronousConsumer implements Consumer { | |
| 31 | - | |
| 32 | - private static final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); | |
| 33 | - | |
| 34 | - private final CountDownLatch shutdownLatch = new CountDownLatch(1); | |
| 35 | - | |
| 36 | - private final Session session; | |
| 37 | - private final QueryGenerator requests; | |
| 38 | - private final Reporter reporter; | |
| 39 | - | |
| 40 | - public AsynchronousConsumer(Session session, | |
| 41 | - QueryGenerator requests, | |
| 42 | - Reporter reporter) { | |
| 43 | - this.session = session; | |
| 44 | - this.requests = requests; | |
| 45 | - this.reporter = reporter; | |
| 46 | - } | |
| 47 | - | |
| 48 | - @Override | |
| 49 | - public void start() { | |
| 50 | - executorService.execute(new Runnable() { | |
| 51 | - @Override | |
| 52 | - public void run() { | |
| 53 | - request(); | |
| 54 | - } | |
| 55 | - }); | |
| 56 | - } | |
| 57 | - | |
| 58 | - private void request() { | |
| 59 | - | |
| 60 | - if (!requests.hasNext()) { | |
| 61 | - shutdown(); | |
| 62 | - return; | |
| 63 | - } | |
| 64 | - | |
| 65 | - handle(requests.next()); | |
| 66 | - } | |
| 67 | - | |
| 68 | - @Override | |
| 69 | - public void join() { | |
| 70 | - awaitUninterruptibly(shutdownLatch); | |
| 71 | - } | |
| 72 | - | |
| 73 | - protected void handle(QueryGenerator.Request request) { | |
| 74 | - | |
| 75 | - final Reporter.Context ctx = reporter.newRequest(); | |
| 76 | - | |
| 77 | - ResultSetFuture resultSetFuture = request.executeAsync(session); | |
| 78 | - Futures.addCallback(resultSetFuture, new FutureCallback<ResultSet>() { | |
| 79 | - @Override | |
| 80 | - public void onSuccess(final ResultSet result) { | |
| 81 | - ctx.done(); | |
| 82 | - request(); | |
| 83 | - } | |
| 84 | - | |
| 85 | - @Override | |
| 86 | - public void onFailure(final Throwable t) { | |
| 87 | - // Could do better I suppose | |
| 88 | - System.err.println("Error during request: " + t); | |
| 89 | - ctx.done(); | |
| 90 | - request(); | |
| 91 | - } | |
| 92 | - }, executorService); | |
| 93 | - } | |
| 94 | - | |
| 95 | - protected void shutdown() { | |
| 96 | - shutdownLatch.countDown(); | |
| 97 | - } | |
| 98 | -} |
deleted driver-examples/stress/src/main/java/com/datastax/driver/stress/BlockingConsumer.java +0 −74
| @@ -1,74 +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.stress; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.Session; | |
| 19 | -import com.datastax.driver.core.exceptions.DriverException; | |
| 20 | -import com.google.common.util.concurrent.Uninterruptibles; | |
| 21 | - | |
| 22 | -public class BlockingConsumer implements Consumer { | |
| 23 | - | |
| 24 | - private final Runner runner = new Runner(); | |
| 25 | - | |
| 26 | - private final Session session; | |
| 27 | - private final QueryGenerator requests; | |
| 28 | - private final Reporter reporter; | |
| 29 | - | |
| 30 | - public BlockingConsumer(Session session, | |
| 31 | - QueryGenerator requests, | |
| 32 | - Reporter reporter) { | |
| 33 | - this.session = session; | |
| 34 | - this.requests = requests; | |
| 35 | - this.reporter = reporter; | |
| 36 | - this.runner.setDaemon(true); | |
| 37 | - } | |
| 38 | - | |
| 39 | - @Override | |
| 40 | - public void start() { | |
| 41 | - this.runner.start(); | |
| 42 | - } | |
| 43 | - | |
| 44 | - @Override | |
| 45 | - public void join() { | |
| 46 | - Uninterruptibles.joinUninterruptibly(this.runner); | |
| 47 | - } | |
| 48 | - | |
| 49 | - private class Runner extends Thread { | |
| 50 | - | |
| 51 | - public Runner() { | |
| 52 | - super("Consumer Threads"); | |
| 53 | - } | |
| 54 | - | |
| 55 | - @Override | |
| 56 | - public void run() { | |
| 57 | - try { | |
| 58 | - while (requests.hasNext()) | |
| 59 | - handle(requests.next()); | |
| 60 | - } catch (DriverException e) { | |
| 61 | - System.err.println("Error during query: " + e.getMessage()); | |
| 62 | - } | |
| 63 | - } | |
| 64 | - | |
| 65 | - protected void handle(QueryGenerator.Request request) { | |
| 66 | - Reporter.Context ctx = reporter.newRequest(); | |
| 67 | - try { | |
| 68 | - request.execute(session); | |
| 69 | - } finally { | |
| 70 | - ctx.done(); | |
| 71 | - } | |
| 72 | - } | |
| 73 | - } | |
| 74 | -} |
deleted driver-examples/stress/src/main/java/com/datastax/driver/stress/Consumer.java +0 −23
| @@ -1,23 +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.stress; | |
| 17 | - | |
| 18 | -public interface Consumer { | |
| 19 | - | |
| 20 | - public void start(); | |
| 21 | - | |
| 22 | - public void join(); | |
| 23 | -} |
deleted driver-examples/stress/src/main/java/com/datastax/driver/stress/Generators.java +0 −227
| @@ -1,227 +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.stress; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.*; | |
| 19 | -import com.datastax.driver.core.exceptions.QueryValidationException; | |
| 20 | -import com.datastax.driver.core.utils.Bytes; | |
| 21 | -import joptsimple.OptionParser; | |
| 22 | -import joptsimple.OptionSet; | |
| 23 | - | |
| 24 | -import java.nio.ByteBuffer; | |
| 25 | -import java.util.Random; | |
| 26 | - | |
| 27 | -public class Generators { | |
| 28 | - private static ThreadLocal<Random> random = new ThreadLocal<Random>() { | |
| 29 | - @Override | |
| 30 | - protected Random initialValue() { | |
| 31 | - return new Random(); | |
| 32 | - } | |
| 33 | - }; | |
| 34 | - | |
| 35 | - private static ByteBuffer makeValue(final int valueSize) { | |
| 36 | - byte[] value = new byte[valueSize]; | |
| 37 | - random.get().nextBytes(value); | |
| 38 | - return ByteBuffer.wrap(value); | |
| 39 | - } | |
| 40 | - | |
| 41 | - private static abstract class AbstractGenerator extends QueryGenerator { | |
| 42 | - protected int iteration; | |
| 43 | - | |
| 44 | - protected AbstractGenerator(int iterations) { | |
| 45 | - super(iterations); | |
| 46 | - } | |
| 47 | - | |
| 48 | - @Override | |
| 49 | - public int currentIteration() { | |
| 50 | - return iteration; | |
| 51 | - } | |
| 52 | - | |
| 53 | - @Override | |
| 54 | - public boolean hasNext() { | |
| 55 | - return iterations == -1 || iteration < iterations; | |
| 56 | - } | |
| 57 | - | |
| 58 | - @Override | |
| 59 | - public void remove() { | |
| 60 | - throw new UnsupportedOperationException(); | |
| 61 | - } | |
| 62 | - } | |
| 63 | - | |
| 64 | - public static final QueryGenerator.Builder INSERTER = new QueryGenerator.Builder() { | |
| 65 | - | |
| 66 | - @Override | |
| 67 | - public String name() { | |
| 68 | - return "insert"; | |
| 69 | - } | |
| 70 | - | |
| 71 | - @Override | |
| 72 | - public OptionParser addOptions(OptionParser parser) { | |
| 73 | - String msg = "Simple insertion of CQL3 rows (using prepared statements unless the --no-prepare option is used). " | |
| 74 | - + "The inserted rows have a fixed set of columns but no clustering columns."; | |
| 75 | - parser.formatHelpWith(Stress.Help.formatFor(name(), msg)); | |
| 76 | - | |
| 77 | - parser.accepts("no-prepare", "Do no use prepared statement"); | |
| 78 | - parser.accepts("columns-per-row", "Number of columns per CQL3 row").withRequiredArg().ofType(Integer.class).defaultsTo(5); | |
| 79 | - parser.accepts("value-size", "The size in bytes for column values").withRequiredArg().ofType(Integer.class).defaultsTo(34); | |
| 80 | - parser.accepts("with-compact-storage", "Use COMPACT STORAGE on the table used"); | |
| 81 | - return parser; | |
| 82 | - } | |
| 83 | - | |
| 84 | - @Override | |
| 85 | - public void prepare(OptionSet options, Session session) { | |
| 86 | - | |
| 87 | - try { | |
| 88 | - session.execute("DROP KEYSPACE stress;"); | |
| 89 | - } catch (QueryValidationException e) { /* Fine, ignore */ } | |
| 90 | - | |
| 91 | - session.execute("CREATE KEYSPACE stress WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }"); | |
| 92 | - | |
| 93 | - session.execute("USE stress"); | |
| 94 | - | |
| 95 | - StringBuilder sb = new StringBuilder(); | |
| 96 | - sb.append("CREATE TABLE standard1 (key bigint PRIMARY KEY"); | |
| 97 | - for (int i = 0; i < (Integer) options.valueOf("columns-per-row"); ++i) | |
| 98 | - sb.append(", C").append(i).append(" blob"); | |
| 99 | - sb.append(')'); | |
| 100 | - | |
| 101 | - if (options.has("with-compact-storage")) | |
| 102 | - sb.append(" WITH COMPACT STORAGE"); | |
| 103 | - | |
| 104 | - session.execute(sb.toString()); | |
| 105 | - } | |
| 106 | - | |
| 107 | - @Override | |
| 108 | - public QueryGenerator create(int id, int iterations, OptionSet options, Session session) { | |
| 109 | - | |
| 110 | - return options.has("no-prepare") | |
| 111 | - ? createRegular(id, iterations, options, session) | |
| 112 | - : createPrepared(id, iterations, options, session); | |
| 113 | - } | |
| 114 | - | |
| 115 | - public QueryGenerator createRegular(int id, int iterations, OptionSet options, final Session session) { | |
| 116 | - final int valueSize = (Integer) options.valueOf("value-size"); | |
| 117 | - final int columnsPerRow = (Integer) options.valueOf("columns-per-row"); | |
| 118 | - final long prefix = (long) id << 32; | |
| 119 | - | |
| 120 | - return new AbstractGenerator(iterations) { | |
| 121 | - @Override | |
| 122 | - public QueryGenerator.Request next() { | |
| 123 | - StringBuilder sb = new StringBuilder(); | |
| 124 | - sb.append("UPDATE standard1 SET "); | |
| 125 | - for (int i = 0; i < columnsPerRow; ++i) { | |
| 126 | - if (i > 0) sb.append(", "); | |
| 127 | - sb.append('C').append(i).append("='").append(Bytes.toHexString(makeValue(valueSize))).append('\''); | |
| 128 | - } | |
| 129 | - sb.append(" WHERE key = ").append(prefix | iteration); | |
| 130 | - ++iteration; | |
| 131 | - return new QueryGenerator.Request.SimpleQuery(new SimpleStatement(sb.toString())); | |
| 132 | - } | |
| 133 | - }; | |
| 134 | - } | |
| 135 | - | |
| 136 | - public QueryGenerator createPrepared(int id, int iterations, OptionSet options, Session session) { | |
| 137 | - final int valueSize = (Integer) options.valueOf("value-size"); | |
| 138 | - final int columnsPerRow = (Integer) options.valueOf("columns-per-row"); | |
| 139 | - final long prefix = (long) id << 32; | |
| 140 | - | |
| 141 | - StringBuilder sb = new StringBuilder(); | |
| 142 | - sb.append("UPDATE standard1 SET "); | |
| 143 | - for (int i = 0; i < columnsPerRow; ++i) { | |
| 144 | - if (i > 0) sb.append(", "); | |
| 145 | - sb.append('C').append(i).append("=?"); | |
| 146 | - } | |
| 147 | - sb.append(" WHERE key = ?"); | |
| 148 | - | |
| 149 | - final PreparedStatement stmt = session.prepare(sb.toString()); | |
| 150 | - | |
| 151 | - return new AbstractGenerator(iterations) { | |
| 152 | - @Override | |
| 153 | - public QueryGenerator.Request next() { | |
| 154 | - BoundStatement b = stmt.bind(); | |
| 155 | - b.setLong("key", prefix | iteration); | |
| 156 | - for (int i = 0; i < columnsPerRow; ++i) | |
| 157 | - b.setBytes("c" + i, makeValue(valueSize)); | |
| 158 | - ++iteration; | |
| 159 | - return new QueryGenerator.Request.PreparedQuery(b); | |
| 160 | - } | |
| 161 | - }; | |
| 162 | - } | |
| 163 | - }; | |
| 164 | - | |
| 165 | - public static final QueryGenerator.Builder READER = new QueryGenerator.Builder() { | |
| 166 | - | |
| 167 | - @Override | |
| 168 | - public String name() { | |
| 169 | - return "read"; | |
| 170 | - } | |
| 171 | - | |
| 172 | - @Override | |
| 173 | - public OptionParser addOptions(OptionParser parser) { | |
| 174 | - String msg = "Read the rows inserted with the insert generator. Use prepared statements unless the --no-prepare option is used."; | |
| 175 | - parser.formatHelpWith(Stress.Help.formatFor(name(), msg)); | |
| 176 | - | |
| 177 | - parser.accepts("no-prepare", "Do no use prepared statement"); | |
| 178 | - return parser; | |
| 179 | - } | |
| 180 | - | |
| 181 | - @Override | |
| 182 | - public void prepare(OptionSet options, Session session) { | |
| 183 | - KeyspaceMetadata ks = session.getCluster().getMetadata().getKeyspace("stress"); | |
| 184 | - if (ks == null || ks.getTable("standard1") == null) { | |
| 185 | - System.err.println("There is nothing to reads, please run insert/insert_prepared first."); | |
| 186 | - System.exit(1); | |
| 187 | - } | |
| 188 | - | |
| 189 | - session.execute("USE stress"); | |
| 190 | - } | |
| 191 | - | |
| 192 | - @Override | |
| 193 | - public QueryGenerator create(int id, int iterations, OptionSet options, Session session) { | |
| 194 | - return options.has("no-prepare") | |
| 195 | - ? createRegular(id, iterations, session) | |
| 196 | - : createPrepared(id, iterations, session); | |
| 197 | - } | |
| 198 | - | |
| 199 | - public QueryGenerator createRegular(long id, int iterations, final Session session) { | |
| 200 | - final long prefix = (long) id << 32; | |
| 201 | - return new AbstractGenerator(iterations) { | |
| 202 | - @Override | |
| 203 | - public QueryGenerator.Request next() { | |
| 204 | - StringBuilder sb = new StringBuilder(); | |
| 205 | - sb.append("SELECT * FROM standard1 WHERE key = ").append(prefix | iteration); | |
| 206 | - ++iteration; | |
| 207 | - return new QueryGenerator.Request.SimpleQuery(new SimpleStatement(sb.toString())); | |
| 208 | - } | |
| 209 | - }; | |
| 210 | - } | |
| 211 | - | |
| 212 | - public QueryGenerator createPrepared(long id, int iterations, Session session) { | |
| 213 | - final long prefix = (long) id << 32; | |
| 214 | - final PreparedStatement stmt = session.prepare("SELECT * FROM standard1 WHERE key = ?"); | |
| 215 | - | |
| 216 | - return new AbstractGenerator(iterations) { | |
| 217 | - @Override | |
| 218 | - public QueryGenerator.Request next() { | |
| 219 | - BoundStatement bs = stmt.bind(); | |
| 220 | - bs.setLong("key", prefix | iteration); | |
| 221 | - ++iteration; | |
| 222 | - return new QueryGenerator.Request.PreparedQuery(bs); | |
| 223 | - } | |
| 224 | - }; | |
| 225 | - } | |
| 226 | - }; | |
| 227 | -} |
deleted driver-examples/stress/src/main/java/com/datastax/driver/stress/QueryGenerator.java +0 −92
| @@ -1,92 +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.stress; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.*; | |
| 19 | -import joptsimple.OptionParser; | |
| 20 | -import joptsimple.OptionSet; | |
| 21 | - | |
| 22 | -import java.util.Iterator; | |
| 23 | - | |
| 24 | -public abstract class QueryGenerator implements Iterator<QueryGenerator.Request> { | |
| 25 | - | |
| 26 | - protected final int iterations; | |
| 27 | - | |
| 28 | - protected QueryGenerator(int iterations) { | |
| 29 | - this.iterations = iterations; | |
| 30 | - } | |
| 31 | - | |
| 32 | - public abstract int currentIteration(); | |
| 33 | - | |
| 34 | - public int totalIterations() { | |
| 35 | - return iterations; | |
| 36 | - } | |
| 37 | - | |
| 38 | - public interface Builder { | |
| 39 | - public String name(); | |
| 40 | - | |
| 41 | - public OptionParser addOptions(OptionParser parser); | |
| 42 | - | |
| 43 | - public void prepare(OptionSet options, Session session); | |
| 44 | - | |
| 45 | - public QueryGenerator create(int id, int iterations, OptionSet options, Session session); | |
| 46 | - } | |
| 47 | - | |
| 48 | - public interface Request { | |
| 49 | - | |
| 50 | - public ResultSet execute(Session session); | |
| 51 | - | |
| 52 | - public ResultSetFuture executeAsync(Session session); | |
| 53 | - | |
| 54 | - public static class SimpleQuery implements Request { | |
| 55 | - | |
| 56 | - private final Statement statement; | |
| 57 | - | |
| 58 | - public SimpleQuery(Statement statement) { | |
| 59 | - this.statement = statement; | |
| 60 | - } | |
| 61 | - | |
| 62 | - @Override | |
| 63 | - public ResultSet execute(Session session) { | |
| 64 | - return session.execute(statement); | |
| 65 | - } | |
| 66 | - | |
| 67 | - @Override | |
| 68 | - public ResultSetFuture executeAsync(Session session) { | |
| 69 | - return session.executeAsync(statement); | |
| 70 | - } | |
| 71 | - } | |
| 72 | - | |
| 73 | - public static class PreparedQuery implements Request { | |
| 74 | - | |
| 75 | - private final BoundStatement query; | |
| 76 | - | |
| 77 | - public PreparedQuery(BoundStatement query) { | |
| 78 | - this.query = query; | |
| 79 | - } | |
| 80 | - | |
| 81 | - @Override | |
| 82 | - public ResultSet execute(Session session) { | |
| 83 | - return session.execute(query); | |
| 84 | - } | |
| 85 | - | |
| 86 | - @Override | |
| 87 | - public ResultSetFuture executeAsync(Session session) { | |
| 88 | - return session.executeAsync(query); | |
| 89 | - } | |
| 90 | - } | |
| 91 | - } | |
| 92 | -} |
deleted driver-examples/stress/src/main/java/com/datastax/driver/stress/Reporter.java +0 −281
| @@ -1,281 +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.stress; | |
| 17 | - | |
| 18 | -import com.yammer.metrics.Metrics; | |
| 19 | -import com.yammer.metrics.core.Meter; | |
| 20 | -import com.yammer.metrics.core.Timer; | |
| 21 | -import com.yammer.metrics.core.TimerContext; | |
| 22 | -import com.yammer.metrics.stats.Snapshot; | |
| 23 | - | |
| 24 | -import java.io.File; | |
| 25 | -import java.io.FileOutputStream; | |
| 26 | -import java.io.IOException; | |
| 27 | -import java.io.PrintStream; | |
| 28 | -import java.util.concurrent.Executors; | |
| 29 | -import java.util.concurrent.ScheduledExecutorService; | |
| 30 | -import java.util.concurrent.TimeUnit; | |
| 31 | -import java.util.concurrent.atomic.AtomicInteger; | |
| 32 | - | |
| 33 | -public class Reporter implements Runnable { | |
| 34 | - | |
| 35 | - private Meter requests; | |
| 36 | - private Timer latencies; | |
| 37 | - | |
| 38 | - public Meter requestsMiddle; | |
| 39 | - public Timer latenciesMiddle; | |
| 40 | - | |
| 41 | - private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); | |
| 42 | - | |
| 43 | - private final File csvFile; | |
| 44 | - private final String header; | |
| 45 | - private final long period; | |
| 46 | - private final int consoleReportPeriod; | |
| 47 | - private final int iterations; | |
| 48 | - private final AtomicInteger requestsDone = new AtomicInteger(0); | |
| 49 | - | |
| 50 | - private final int middleLowBound; | |
| 51 | - private final int middleHighBound; | |
| 52 | - | |
| 53 | - private volatile double meanMiddleRate = -1.0; | |
| 54 | - | |
| 55 | - private long startTime; | |
| 56 | - private long lastOpCount; | |
| 57 | - | |
| 58 | - private PrintStream csv; | |
| 59 | - | |
| 60 | - private long lastConsoleOpCount; | |
| 61 | - private long lastConsoleTimestamp; | |
| 62 | - private int tickSinceLastConsoleReport; | |
| 63 | - | |
| 64 | - public Reporter(int consoleReportPeriod, String csvFileName, String[] args, int iterations) { | |
| 65 | - this(1, consoleReportPeriod, new File(csvFileName), formatHeader(args), iterations); | |
| 66 | - } | |
| 67 | - | |
| 68 | - private Reporter(int csvPeriod, int consolePeriod, File csvFile, String header, int iterations) { | |
| 69 | - this.period = csvPeriod; | |
| 70 | - this.consoleReportPeriod = consolePeriod / csvPeriod; | |
| 71 | - this.csvFile = csvFile; | |
| 72 | - this.header = header; | |
| 73 | - this.iterations = iterations; | |
| 74 | - | |
| 75 | - // Middle = exclude first and last 10% (note: if requests is -1, we'll end up with negative bounds, which will always exclude. It's fine if we never stop anyway) | |
| 76 | - this.middleLowBound = (int) (0.1 * iterations); | |
| 77 | - this.middleHighBound = (int) (0.9 * iterations); | |
| 78 | - } | |
| 79 | - | |
| 80 | - private static String formatHeader(String[] args) { | |
| 81 | - StringBuilder sb = new StringBuilder(); | |
| 82 | - sb.append("stress"); | |
| 83 | - for (String arg : args) | |
| 84 | - sb.append(' ').append(arg); | |
| 85 | - return sb.toString(); | |
| 86 | - } | |
| 87 | - | |
| 88 | - public void start() { | |
| 89 | - | |
| 90 | - this.requests = Metrics.newMeter(Reporter.class, "requests", "requests", TimeUnit.SECONDS); | |
| 91 | - this.latencies = Metrics.newTimer(Reporter.class, "latencies", TimeUnit.MILLISECONDS, TimeUnit.SECONDS); | |
| 92 | - this.startTime = System.currentTimeMillis(); | |
| 93 | - initConsole(); | |
| 94 | - initCSV(); | |
| 95 | - | |
| 96 | - this.executor.scheduleAtFixedRate(this, period, period, TimeUnit.SECONDS); | |
| 97 | - } | |
| 98 | - | |
| 99 | - public Context newRequest() { | |
| 100 | - int iteration = requestsDone.getAndIncrement(); | |
| 101 | - if (iteration >= middleLowBound) { | |
| 102 | - if (latenciesMiddle == null) { | |
| 103 | - synchronized (this) { | |
| 104 | - if (latenciesMiddle == null) { | |
| 105 | - latenciesMiddle = Metrics.newTimer(Reporter.class, "latencies_middle", TimeUnit.MILLISECONDS, TimeUnit.SECONDS); | |
| 106 | - requestsMiddle = Metrics.newMeter(Reporter.class, "requests_middle", "requests", TimeUnit.SECONDS); | |
| 107 | - } | |
| 108 | - } | |
| 109 | - } | |
| 110 | - if (iteration > middleHighBound) { | |
| 111 | - if (meanMiddleRate < 0) | |
| 112 | - meanMiddleRate = requestsMiddle.meanRate(); | |
| 113 | - | |
| 114 | - return new Context(this, latencies.time(), null); | |
| 115 | - } else { | |
| 116 | - return new Context(this, latencies.time(), latenciesMiddle.time()); | |
| 117 | - } | |
| 118 | - } else { | |
| 119 | - return new Context(this, latencies.time(), null); | |
| 120 | - } | |
| 121 | - } | |
| 122 | - | |
| 123 | - public void stop() { | |
| 124 | - executor.shutdown(); | |
| 125 | - | |
| 126 | - long tstamp = System.currentTimeMillis(); | |
| 127 | - long elapsed = TimeUnit.MILLISECONDS.toSeconds(tstamp - startTime); | |
| 128 | - Report lastReport = new Report(tstamp, elapsed, requests, latencies, lastOpCount); | |
| 129 | - | |
| 130 | - stopCSV(lastReport); | |
| 131 | - stopConsole(lastReport); | |
| 132 | - } | |
| 133 | - | |
| 134 | - @Override | |
| 135 | - public void run() { | |
| 136 | - report(); | |
| 137 | - } | |
| 138 | - | |
| 139 | - private void report() { | |
| 140 | - long tstamp = System.currentTimeMillis(); | |
| 141 | - long elapsed = TimeUnit.MILLISECONDS.toSeconds(tstamp - startTime); | |
| 142 | - | |
| 143 | - Report report = new Report(tstamp, elapsed, requests, latencies, lastOpCount); | |
| 144 | - lastOpCount = report.totalOps; | |
| 145 | - | |
| 146 | - reportToCSV(report); | |
| 147 | - reportToConsole(report); | |
| 148 | - } | |
| 149 | - | |
| 150 | - private void initCSV() { | |
| 151 | - if (csvFile.exists()) | |
| 152 | - if (!csvFile.delete()) | |
| 153 | - throw new RuntimeException("File " + csvFile + " already exists and cannot delete it"); | |
| 154 | - | |
| 155 | - try { | |
| 156 | - if (!csvFile.createNewFile()) | |
| 157 | - throw new RuntimeException("Unable to create report file " + csvFile); | |
| 158 | - | |
| 159 | - csv = new PrintStream(new FileOutputStream(csvFile)); | |
| 160 | - | |
| 161 | - csv.println("# " + header); | |
| 162 | - csv.println("# elapsed,total_ops,interval_rate,mean_rate,mean_latency,95th_latency,99th_latency,std_dev"); | |
| 163 | - | |
| 164 | - } catch (IOException e) { | |
| 165 | - throw new RuntimeException("Error creating report file " + csvFile, e); | |
| 166 | - } | |
| 167 | - } | |
| 168 | - | |
| 169 | - private void reportToCSV(Report report) { | |
| 170 | - csv.println(new StringBuilder() | |
| 171 | - .append(report.elapsed).append(',') | |
| 172 | - .append(report.totalOps).append(',') | |
| 173 | - .append(report.intervalRate).append(',') | |
| 174 | - .append(report.meanRate).append(',') | |
| 175 | - .append(report.meanLatency).append(',') | |
| 176 | - .append(report.latency95th).append(',') | |
| 177 | - .append(report.latency99th).append(',') | |
| 178 | - .append(report.stdDev)); | |
| 179 | - } | |
| 180 | - | |
| 181 | - private void stopCSV(Report lastReport) { | |
| 182 | - reportToCSV(lastReport); | |
| 183 | - } | |
| 184 | - | |
| 185 | - private void initConsole() { | |
| 186 | - this.lastConsoleTimestamp = startTime; | |
| 187 | - | |
| 188 | - System.out.println(" Time (s) | total ops | interval rate | mean rate | mean latency (ms) | 95th latency (ms) | 99th latency (ms) | std dev"); | |
| 189 | - System.out.println("--------------------------------------------------------------------------------------------------------------------------------"); | |
| 190 | - } | |
| 191 | - | |
| 192 | - private void reportToConsole(Report report) { | |
| 193 | - | |
| 194 | - if (++tickSinceLastConsoleReport < consoleReportPeriod) | |
| 195 | - return; | |
| 196 | - | |
| 197 | - printReportToConsole(report); | |
| 198 | - | |
| 199 | - tickSinceLastConsoleReport = 0; | |
| 200 | - lastConsoleTimestamp = report.timestamp; | |
| 201 | - lastConsoleOpCount = report.totalOps; | |
| 202 | - } | |
| 203 | - | |
| 204 | - private void printReportToConsole(Report report) { | |
| 205 | - long delay = report.timestamp - lastConsoleTimestamp; | |
| 206 | - double intervalRate = (((double) (report.totalOps - lastConsoleOpCount)) / delay) * 1000; | |
| 207 | - | |
| 208 | - String msg = String.format(" %8d | %12d | %13.2f | %12.2f | %17.3f | %17.3f | %17.3f | %9.3f", | |
| 209 | - report.elapsed, report.totalOps, intervalRate, report.meanRate, report.meanLatency, report.latency95th, report.latency99th, report.stdDev); | |
| 210 | - System.out.println(msg); | |
| 211 | - } | |
| 212 | - | |
| 213 | - private void stopConsole(Report lastReport) { | |
| 214 | - printReportToConsole(lastReport); | |
| 215 | - | |
| 216 | - if (latenciesMiddle == null) | |
| 217 | - return; | |
| 218 | - | |
| 219 | - Snapshot snapshot = latenciesMiddle.getSnapshot(); | |
| 220 | - | |
| 221 | - System.out.println(); | |
| 222 | - System.out.println("For the middle 80% of values:"); | |
| 223 | - System.out.println(String.format(" Mean rate (ops/sec): %10.1f", meanMiddleRate)); | |
| 224 | - System.out.println(String.format(" Mean latency (ms): %10.3f", latenciesMiddle.mean())); | |
| 225 | - System.out.println(String.format(" Median latency (ms): %10.3f", snapshot.getMedian())); | |
| 226 | - System.out.println(String.format(" 75th percentile latency (ms): %10.3f", snapshot.get75thPercentile())); | |
| 227 | - System.out.println(String.format(" 95th percentile latency (ms): %10.3f", snapshot.get95thPercentile())); | |
| 228 | - System.out.println(String.format(" 99th percentile latency (ms): %10.3f", snapshot.get99thPercentile())); | |
| 229 | - System.out.println(String.format(" Standard latency deviation: %10.3f", latenciesMiddle.stdDev())); | |
| 230 | - } | |
| 231 | - | |
| 232 | - private static class Report { | |
| 233 | - public final long timestamp; | |
| 234 | - public final long elapsed; | |
| 235 | - | |
| 236 | - public final long totalOps; | |
| 237 | - public final long intervalRate; | |
| 238 | - public final double meanRate; | |
| 239 | - | |
| 240 | - public final double meanLatency; | |
| 241 | - public final double latency95th; | |
| 242 | - public final double latency99th; | |
| 243 | - public final double stdDev; | |
| 244 | - | |
| 245 | - public Report(long timestamp, long elapsed, Meter meter, Timer timer, long lastOpCount) { | |
| 246 | - this.timestamp = timestamp; | |
| 247 | - this.elapsed = elapsed; | |
| 248 | - | |
| 249 | - this.totalOps = meter.count(); | |
| 250 | - this.intervalRate = totalOps - lastOpCount; | |
| 251 | - this.meanRate = meter.meanRate(); | |
| 252 | - | |
| 253 | - Snapshot snapshot = timer.getSnapshot(); | |
| 254 | - this.meanLatency = timer.mean(); | |
| 255 | - this.latency95th = snapshot.get95thPercentile(); | |
| 256 | - this.latency99th = snapshot.get99thPercentile(); | |
| 257 | - this.stdDev = timer.stdDev(); | |
| 258 | - } | |
| 259 | - } | |
| 260 | - | |
| 261 | - public static class Context { | |
| 262 | - private final Reporter reporter; | |
| 263 | - private final TimerContext context; | |
| 264 | - private final TimerContext contextMiddle; | |
| 265 | - | |
| 266 | - private Context(Reporter reporter, TimerContext context, TimerContext contextMiddle) { | |
| 267 | - this.reporter = reporter; | |
| 268 | - this.context = context; | |
| 269 | - this.contextMiddle = contextMiddle; | |
| 270 | - } | |
| 271 | - | |
| 272 | - public void done() { | |
| 273 | - context.stop(); | |
| 274 | - reporter.requests.mark(); | |
| 275 | - if (contextMiddle != null) { | |
| 276 | - contextMiddle.stop(); | |
| 277 | - reporter.requestsMiddle.mark(); | |
| 278 | - } | |
| 279 | - } | |
| 280 | - } | |
| 281 | -} |
deleted driver-examples/stress/src/main/java/com/datastax/driver/stress/Stress.java +0 −280
| @@ -1,280 +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.stress; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.*; | |
| 19 | -import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 20 | -import joptsimple.*; | |
| 21 | -import org.apache.log4j.PropertyConfigurator; | |
| 22 | - | |
| 23 | -import java.io.IOException; | |
| 24 | -import java.util.HashMap; | |
| 25 | -import java.util.List; | |
| 26 | -import java.util.Map; | |
| 27 | - | |
| 28 | -/** | |
| 29 | - * A simple stress tool to demonstrate the use of the driver. | |
| 30 | - * <p/> | |
| 31 | - * Sample usage: | |
| 32 | - * stress insert -n 100000 | |
| 33 | - * stress read -n 10000 | |
| 34 | - */ | |
| 35 | -public class Stress { | |
| 36 | - | |
| 37 | - private static final Map<String, QueryGenerator.Builder> generators = new HashMap<String, QueryGenerator.Builder>(); | |
| 38 | - | |
| 39 | - static { | |
| 40 | - PropertyConfigurator.configure(System.getProperty("log4j.configuration", "./conf/log4j.properties")); | |
| 41 | - | |
| 42 | - QueryGenerator.Builder[] gs = new QueryGenerator.Builder[]{ | |
| 43 | - Generators.INSERTER, | |
| 44 | - Generators.READER | |
| 45 | - }; | |
| 46 | - | |
| 47 | - for (QueryGenerator.Builder b : gs) | |
| 48 | - register(b.name(), b); | |
| 49 | - } | |
| 50 | - | |
| 51 | - private static OptionParser defaultParser() { | |
| 52 | - OptionParser parser = new OptionParser() {{ | |
| 53 | - accepts("h", "Show this help message"); | |
| 54 | - accepts("n", "Number of requests to perform (default: unlimited)").withRequiredArg().ofType(Integer.class); | |
| 55 | - accepts("t", "Level of concurrency to use").withRequiredArg().ofType(Integer.class).defaultsTo(50); | |
| 56 | - accepts("async", "Make asynchronous requests instead of blocking ones"); | |
| 57 | - accepts("ip", "The hosts ip to connect to").withRequiredArg().ofType(String.class).defaultsTo("127.0.0.1"); | |
| 58 | - accepts("report-file", "The name of csv file to use for reporting results").withRequiredArg().ofType(String.class).defaultsTo("last.csv"); | |
| 59 | - accepts("print-delay", "The delay in seconds at which to report on the console").withRequiredArg().ofType(Integer.class).defaultsTo(5); | |
| 60 | - accepts("compression", "Use compression (SNAPPY)"); | |
| 61 | - accepts("connections-per-host", "The number of connections per hosts (default: based on the number of threads)").withRequiredArg().ofType(Integer.class); | |
| 62 | - }}; | |
| 63 | - String msg = "Where <generator> can be one of " + generators.keySet() + '\n' | |
| 64 | - + "You can get more help on a particular generator with: stress <generator> -h"; | |
| 65 | - parser.formatHelpWith(Help.formatFor("<generator>", msg)); | |
| 66 | - return parser; | |
| 67 | - } | |
| 68 | - | |
| 69 | - public static void register(String name, QueryGenerator.Builder generator) { | |
| 70 | - if (generators.containsKey(name)) | |
| 71 | - throw new IllegalStateException("There is already a generator registered with the name " + name); | |
| 72 | - | |
| 73 | - generators.put(name, generator); | |
| 74 | - } | |
| 75 | - | |
| 76 | - private static class Stresser { | |
| 77 | - private final QueryGenerator.Builder genBuilder; | |
| 78 | - private final OptionParser parser; | |
| 79 | - private final OptionSet options; | |
| 80 | - | |
| 81 | - private Stresser(QueryGenerator.Builder genBuilder, OptionParser parser, OptionSet options) { | |
| 82 | - this.genBuilder = genBuilder; | |
| 83 | - this.parser = parser; | |
| 84 | - this.options = options; | |
| 85 | - } | |
| 86 | - | |
| 87 | - public static Stresser forCommandLineArguments(String[] args) { | |
| 88 | - OptionParser parser = defaultParser(); | |
| 89 | - | |
| 90 | - String generatorName = findPotentialGenerator(args); | |
| 91 | - if (generatorName == null) { | |
| 92 | - // Still parse the options to handle -h | |
| 93 | - OptionSet options = parseOptions(parser, args); | |
| 94 | - System.err.println("Missing generator, you need to provide a generator."); | |
| 95 | - printHelp(parser); | |
| 96 | - System.exit(1); | |
| 97 | - } | |
| 98 | - | |
| 99 | - if (!generators.containsKey(generatorName)) { | |
| 100 | - System.err.println(String.format("Unknown generator '%s'", generatorName)); | |
| 101 | - printHelp(parser); | |
| 102 | - System.exit(1); | |
| 103 | - } | |
| 104 | - | |
| 105 | - QueryGenerator.Builder genBuilder = generators.get(generatorName); | |
| 106 | - parser = genBuilder.addOptions(parser); | |
| 107 | - OptionSet options = parseOptions(parser, args); | |
| 108 | - | |
| 109 | - List<?> nonOpts = options.nonOptionArguments(); | |
| 110 | - if (nonOpts.size() > 1) { | |
| 111 | - System.err.println("Too many generators provided. Got " + nonOpts + " but only one generator supported."); | |
| 112 | - printHelp(parser); | |
| 113 | - System.exit(1); | |
| 114 | - } | |
| 115 | - | |
| 116 | - return new Stresser(genBuilder, parser, options); | |
| 117 | - } | |
| 118 | - | |
| 119 | - private static String findPotentialGenerator(String[] args) { | |
| 120 | - for (String arg : args) | |
| 121 | - if (!arg.startsWith("-")) | |
| 122 | - return arg; | |
| 123 | - | |
| 124 | - return null; | |
| 125 | - } | |
| 126 | - | |
| 127 | - private static OptionSet parseOptions(OptionParser parser, String[] args) { | |
| 128 | - try { | |
| 129 | - OptionSet options = parser.parse(args); | |
| 130 | - if (options.has("h")) { | |
| 131 | - printHelp(parser); | |
| 132 | - System.exit(0); | |
| 133 | - } | |
| 134 | - return options; | |
| 135 | - } catch (Exception e) { | |
| 136 | - System.err.println("Error parsing options: " + e.getMessage()); | |
| 137 | - printHelp(parser); | |
| 138 | - System.exit(1); | |
| 139 | - throw new AssertionError(); | |
| 140 | - } | |
| 141 | - } | |
| 142 | - | |
| 143 | - private static void printHelp(OptionParser parser) { | |
| 144 | - try { | |
| 145 | - parser.printHelpOn(System.out); | |
| 146 | - } catch (IOException e) { | |
| 147 | - throw new AssertionError(e); | |
| 148 | - } | |
| 149 | - } | |
| 150 | - | |
| 151 | - public OptionSet getOptions() { | |
| 152 | - return options; | |
| 153 | - } | |
| 154 | - | |
| 155 | - public void prepare(Session session) { | |
| 156 | - genBuilder.prepare(options, session); | |
| 157 | - } | |
| 158 | - | |
| 159 | - public QueryGenerator newGenerator(int id, Session session, int iterations) { | |
| 160 | - return genBuilder.create(id, iterations, options, session); | |
| 161 | - } | |
| 162 | - } | |
| 163 | - | |
| 164 | - public static class Help implements HelpFormatter { | |
| 165 | - | |
| 166 | - private final HelpFormatter defaultFormatter; | |
| 167 | - private final String generator; | |
| 168 | - private final String header; | |
| 169 | - | |
| 170 | - private Help(HelpFormatter defaultFormatter, String generator, String header) { | |
| 171 | - this.defaultFormatter = defaultFormatter; | |
| 172 | - this.generator = generator; | |
| 173 | - this.header = header; | |
| 174 | - } | |
| 175 | - | |
| 176 | - public static Help formatFor(String generator, String header) { | |
| 177 | - // It's a pain in the ass to get the real console width in JAVA so hardcode it. But it's the 21th | |
| 178 | - // century, we're not stuck at 80 characters anymore. | |
| 179 | - int width = 120; | |
| 180 | - return new Help(new BuiltinHelpFormatter(width, 4), generator, header); | |
| 181 | - } | |
| 182 | - | |
| 183 | - @Override | |
| 184 | - public String format(Map<String, ? extends OptionDescriptor> options) { | |
| 185 | - StringBuilder sb = new StringBuilder(); | |
| 186 | - | |
| 187 | - sb.append("Usage: stress ").append(generator).append(" [<option>]*").append("\n\n"); | |
| 188 | - sb.append(header).append("\n\n"); | |
| 189 | - sb.append(defaultFormatter.format(options)); | |
| 190 | - return sb.toString(); | |
| 191 | - } | |
| 192 | - } | |
| 193 | - | |
| 194 | - public static void main(String[] args) throws Exception { | |
| 195 | - | |
| 196 | - Stresser stresser = Stresser.forCommandLineArguments(args); | |
| 197 | - OptionSet options = stresser.getOptions(); | |
| 198 | - | |
| 199 | - int requests = options.has("n") ? (Integer) options.valueOf("n") : -1; | |
| 200 | - int concurrency = (Integer) options.valueOf("t"); | |
| 201 | - | |
| 202 | - String reportFileName = (String) options.valueOf("report-file"); | |
| 203 | - | |
| 204 | - boolean async = options.has("async"); | |
| 205 | - | |
| 206 | - int iterations = (requests == -1 ? -1 : requests / concurrency); | |
| 207 | - | |
| 208 | - final int maxRequestsPerConnection = 128; | |
| 209 | - int maxConnections = options.has("connections-per-host") | |
| 210 | - ? (Integer) options.valueOf("connections-per-host") | |
| 211 | - : concurrency / maxRequestsPerConnection + 1; | |
| 212 | - | |
| 213 | - PoolingOptions pools = new PoolingOptions(); | |
| 214 | - pools.setNewConnectionThreshold(HostDistance.LOCAL, concurrency); | |
| 215 | - pools.setCoreConnectionsPerHost(HostDistance.LOCAL, maxConnections); | |
| 216 | - pools.setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections); | |
| 217 | - pools.setCoreConnectionsPerHost(HostDistance.REMOTE, maxConnections); | |
| 218 | - pools.setMaxConnectionsPerHost(HostDistance.REMOTE, maxConnections); | |
| 219 | - | |
| 220 | - System.out.println("Initializing stress test:"); | |
| 221 | - System.out.println(" request count: " + (requests == -1 ? "unlimited" : requests)); | |
| 222 | - System.out.println(" concurrency: " + concurrency + " (" + iterations + " requests/thread)"); | |
| 223 | - System.out.println(" mode: " + (async ? "asynchronous" : "blocking")); | |
| 224 | - System.out.println(" per-host connections: " + maxConnections); | |
| 225 | - System.out.println(" compression: " + options.has("compression")); | |
| 226 | - | |
| 227 | - try { | |
| 228 | - // Create session to hosts | |
| 229 | - Cluster cluster = new Cluster.Builder() | |
| 230 | - .addContactPoints(String.valueOf(options.valueOf("ip"))) | |
| 231 | - .withPoolingOptions(pools) | |
| 232 | - .withSocketOptions(new SocketOptions().setTcpNoDelay(true)) | |
| 233 | - .build(); | |
| 234 | - | |
| 235 | - if (options.has("compression")) | |
| 236 | - cluster.getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.SNAPPY); | |
| 237 | - | |
| 238 | - Session session = cluster.connect(); | |
| 239 | - | |
| 240 | - Metadata metadata = cluster.getMetadata(); | |
| 241 | - System.out.println(String.format("Connected to cluster '%s' on %s.", metadata.getClusterName(), metadata.getAllHosts())); | |
| 242 | - | |
| 243 | - System.out.println("Preparing test..."); | |
| 244 | - stresser.prepare(session); | |
| 245 | - | |
| 246 | - Reporter reporter = new Reporter((Integer) options.valueOf("print-delay"), reportFileName, args, requests); | |
| 247 | - | |
| 248 | - Consumer[] consumers = new Consumer[concurrency]; | |
| 249 | - for (int i = 0; i < concurrency; i++) { | |
| 250 | - QueryGenerator generator = stresser.newGenerator(i, session, iterations); | |
| 251 | - consumers[i] = async ? new AsynchronousConsumer(session, generator, reporter) : | |
| 252 | - new BlockingConsumer(session, generator, reporter); | |
| 253 | - } | |
| 254 | - | |
| 255 | - System.out.println("Starting to stress test..."); | |
| 256 | - System.out.println(); | |
| 257 | - | |
| 258 | - reporter.start(); | |
| 259 | - | |
| 260 | - for (Consumer consumer : consumers) | |
| 261 | - consumer.start(); | |
| 262 | - | |
| 263 | - for (Consumer consumer : consumers) | |
| 264 | - consumer.join(); | |
| 265 | - | |
| 266 | - reporter.stop(); | |
| 267 | - | |
| 268 | - System.out.println("Stress test successful."); | |
| 269 | - System.exit(0); | |
| 270 | - | |
| 271 | - } catch (NoHostAvailableException e) { | |
| 272 | - System.err.println("No alive hosts to use: " + e.getMessage()); | |
| 273 | - System.exit(1); | |
| 274 | - } catch (Exception e) { | |
| 275 | - System.err.println("Unexpected error: " + e.getMessage()); | |
| 276 | - e.printStackTrace(); | |
| 277 | - System.exit(1); | |
| 278 | - } | |
| 279 | - } | |
| 280 | -} |
modified driver-extras/pom.xml +49 −13
| @@ -24,7 +24,7 @@ | ||
| 24 | 24 | <modelVersion>4.0.0</modelVersion> |
| 25 | 25 | |
| 26 | 26 | <artifactId>cassandra-driver-extras</artifactId> |
| 27 | - | |
| 27 | + <packaging>bundle</packaging> | |
| 28 | 28 | <name>DataStax Java Driver for Apache Cassandra - Extras</name> |
| 29 | 29 | <description>Extended functionality for the Java driver.</description> |
| 30 | 30 | <url>https://github.com/datastax/java-driver</url> |
| @@ -120,6 +120,20 @@ | ||
| 120 | 120 | <scope>test</scope> |
| 121 | 121 | </dependency> |
| 122 | 122 | |
| 123 | + <dependency> | |
| 124 | + <groupId>log4j</groupId> | |
| 125 | + <artifactId>log4j</artifactId> | |
| 126 | + <version>${log4j.version}</version> | |
| 127 | + <scope>test</scope> | |
| 128 | + </dependency> | |
| 129 | + | |
| 130 | + <dependency> | |
| 131 | + <groupId>org.slf4j</groupId> | |
| 132 | + <artifactId>slf4j-log4j12</artifactId> | |
| 133 | + <version>${slf4j-log4j12.version}</version> | |
| 134 | + <scope>test</scope> | |
| 135 | + </dependency> | |
| 136 | + | |
| 123 | 137 | </dependencies> |
| 124 | 138 | |
| 125 | 139 | <build> |
| @@ -142,18 +156,39 @@ | ||
| 142 | 156 | <plugin> |
| 143 | 157 | <groupId>org.codehaus.mojo</groupId> |
| 144 | 158 | <artifactId>animal-sniffer-maven-plugin</artifactId> |
| 145 | - <configuration> | |
| 146 | - <!-- | |
| 147 | - There is no support for JDK 8 yet, see | |
| 148 | - https://github.com/mojohaus/animal-sniffer/issues/1 | |
| 149 | - --> | |
| 150 | - <skip>true</skip> | |
| 151 | - <signature> | |
| 152 | - <groupId>org.codehaus.mojo.signature</groupId> | |
| 153 | - <artifactId>java18</artifactId> | |
| 154 | - <version>1.0</version> | |
| 155 | - </signature> | |
| 156 | - </configuration> | |
| 159 | + <executions> | |
| 160 | + <execution> | |
| 161 | + <id>check</id> | |
| 162 | + <phase>process-classes</phase> | |
| 163 | + <goals> | |
| 164 | + <goal>check</goal> | |
| 165 | + </goals> | |
| 166 | + <configuration> | |
| 167 | + <signature> | |
| 168 | + <groupId>org.codehaus.mojo.signature</groupId> | |
| 169 | + <artifactId>java16</artifactId> | |
| 170 | + <version>1.0</version> | |
| 171 | + </signature> | |
| 172 | + <annotations> | |
| 173 | + <annotation>com.datastax.driver.extras.codecs.jdk8.IgnoreJDK6Requirement</annotation> | |
| 174 | + </annotations> | |
| 175 | + </configuration> | |
| 176 | + </execution> | |
| 177 | + <execution> | |
| 178 | + <id>check-jdk8</id> | |
| 179 | + <phase>process-classes</phase> | |
| 180 | + <goals> | |
| 181 | + <goal>check</goal> | |
| 182 | + </goals> | |
| 183 | + <configuration> | |
| 184 | + <signature> | |
| 185 | + <groupId>org.codehaus.mojo.signature</groupId> | |
| 186 | + <artifactId>java18</artifactId> | |
| 187 | + <version>1.0</version> | |
| 188 | + </signature> | |
| 189 | + </configuration> | |
| 190 | + </execution> | |
| 191 | + </executions> | |
| 157 | 192 | </plugin> |
| 158 | 193 | |
| 159 | 194 | <plugin> |
| @@ -195,6 +230,7 @@ | ||
| 195 | 230 | <Bundle-SymbolicName>com.datastax.driver.extras</Bundle-SymbolicName> |
| 196 | 231 | <Bundle-Version>${project.version}</Bundle-Version> |
| 197 | 232 | <_include>-osgi.bnd</_include> |
| 233 | + <Import-Package><![CDATA[com.google.common*;version="[16.0.1,20)",*]]></Import-Package> | |
| 198 | 234 | </instructions> |
| 199 | 235 | <supportedProjectTypes> |
| 200 | 236 | <supportedProjectType>jar</supportedProjectType> |
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/IgnoreJDK6Requirement.java +25 −0
| @@ -0,0 +1,25 @@ | ||
| 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.extras.codecs.jdk8; | |
| 17 | + | |
| 18 | +/** | |
| 19 | + * Annotation used to mark classes in this package as | |
| 20 | + * excluded from JDK signature check performed | |
| 21 | + * by <a href="http://www.mojohaus.org/animal-sniffer/animal-sniffer-maven-plugin/check-mojo.html">animal-sniffer</a> | |
| 22 | + * Maven plugin as they require JDK 8 and not the usual JDK 6. | |
| 23 | + */ | |
| 24 | +@interface IgnoreJDK6Requirement { | |
| 25 | +} |
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/InstantCodec.java +25 −30
| @@ -21,90 +21,85 @@ | ||
| 21 | 21 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 22 | 22 | |
| 23 | 23 | import java.nio.ByteBuffer; |
| 24 | -import java.time.Instant; | |
| 25 | -import java.time.format.DateTimeFormatter; | |
| 26 | -import java.time.format.DateTimeFormatterBuilder; | |
| 27 | -import java.time.format.DateTimeParseException; | |
| 28 | 24 | |
| 29 | 25 | import static com.datastax.driver.core.ParseUtils.*; |
| 30 | 26 | import static java.lang.Long.parseLong; |
| 31 | -import static java.time.Instant.ofEpochMilli; | |
| 32 | -import static java.time.ZoneOffset.UTC; | |
| 33 | -import static java.time.temporal.ChronoField.*; | |
| 34 | 27 | |
| 35 | 28 | /** |
| 36 | - * {@link TypeCodec} that maps {@link Instant} to CQL {@code timestamp} | |
| 29 | + * {@link TypeCodec} that maps {@link java.time.Instant} to CQL {@code timestamp} | |
| 37 | 30 | * allowing the setting and retrieval of {@code timestamp} |
| 38 | - * columns as {@link Instant} instances. | |
| 31 | + * columns as {@link java.time.Instant} instances. | |
| 39 | 32 | * <p/> |
| 40 | 33 | * Since C* <code>timestamp</code> columns do not preserve timezones |
| 41 | 34 | * any attached timezone information will be lost. |
| 42 | 35 | * <p/> |
| 43 | - * <strong>IMPORTANT</strong>: this codec's {@link #format(Instant) format} method formats | |
| 36 | + * <strong>IMPORTANT</strong>: this codec's {@link #format(java.time.Instant) format} method formats | |
| 44 | 37 | * timestamps using an ISO-8601 format that includes milliseconds. |
| 45 | 38 | * <strong>This format is incompatible with Cassandra versions < 2.0.9.</strong> |
| 46 | 39 | * |
| 47 | 40 | * @see ZonedDateTimeCodec |
| 48 | 41 | * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps">'Working with timestamps' section of CQL specification</a> |
| 49 | 42 | */ |
| 50 | -public class InstantCodec extends TypeCodec<Instant> { | |
| 43 | +@IgnoreJDK6Requirement | |
| 44 | +@SuppressWarnings("Since15") | |
| 45 | +public class InstantCodec extends TypeCodec<java.time.Instant> { | |
| 51 | 46 | |
| 52 | 47 | public static final InstantCodec instance = new InstantCodec(); |
| 53 | 48 | |
| 54 | 49 | /** |
| 55 | - * A {@link DateTimeFormatter} that parses (most) of | |
| 50 | + * A {@link java.time.format.DateTimeFormatter} that parses (most) of | |
| 56 | 51 | * the ISO formats accepted in CQL. |
| 57 | 52 | */ |
| 58 | - private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder() | |
| 53 | + private static final java.time.format.DateTimeFormatter PARSER = new java.time.format.DateTimeFormatterBuilder() | |
| 59 | 54 | .parseCaseSensitive() |
| 60 | 55 | .parseStrict() |
| 61 | - .append(DateTimeFormatter.ISO_LOCAL_DATE) | |
| 56 | + .append(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE) | |
| 62 | 57 | .optionalStart() |
| 63 | 58 | .appendLiteral('T') |
| 64 | - .appendValue(HOUR_OF_DAY, 2) | |
| 59 | + .appendValue(java.time.temporal.ChronoField.HOUR_OF_DAY, 2) | |
| 65 | 60 | .appendLiteral(':') |
| 66 | - .appendValue(MINUTE_OF_HOUR, 2) | |
| 61 | + .appendValue(java.time.temporal.ChronoField.MINUTE_OF_HOUR, 2) | |
| 67 | 62 | .optionalEnd() |
| 68 | 63 | .optionalStart() |
| 69 | 64 | .appendLiteral(':') |
| 70 | - .appendValue(SECOND_OF_MINUTE, 2) | |
| 65 | + .appendValue(java.time.temporal.ChronoField.SECOND_OF_MINUTE, 2) | |
| 71 | 66 | .optionalEnd() |
| 72 | 67 | .optionalStart() |
| 73 | - .appendFraction(NANO_OF_SECOND, 0, 9, true) | |
| 68 | + .appendFraction(java.time.temporal.ChronoField.NANO_OF_SECOND, 0, 9, true) | |
| 74 | 69 | .optionalEnd() |
| 75 | 70 | .optionalStart() |
| 76 | 71 | .appendZoneId() |
| 77 | 72 | .optionalEnd() |
| 78 | 73 | .toFormatter() |
| 79 | - .withZone(UTC); | |
| 74 | + .withZone(java.time.ZoneOffset.UTC); | |
| 80 | 75 | |
| 81 | - private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx") | |
| 82 | - .withZone(UTC); | |
| 76 | + private static final java.time.format.DateTimeFormatter FORMATTER = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx") | |
| 77 | + .withZone(java.time.ZoneOffset.UTC); | |
| 83 | 78 | |
| 84 | 79 | |
| 85 | 80 | private InstantCodec() { |
| 86 | - super(DataType.timestamp(), Instant.class); | |
| 81 | + super(DataType.timestamp(), java.time.Instant.class); | |
| 87 | 82 | } |
| 88 | 83 | |
| 89 | 84 | @Override |
| 90 | - public ByteBuffer serialize(Instant value, ProtocolVersion protocolVersion) { | |
| 85 | + public ByteBuffer serialize(java.time.Instant value, ProtocolVersion protocolVersion) { | |
| 91 | 86 | return value == null ? null : bigint().serializeNoBoxing(value.toEpochMilli(), protocolVersion); |
| 92 | 87 | } |
| 93 | 88 | |
| 94 | 89 | @Override |
| 95 | - public Instant deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) { | |
| 96 | - return bytes == null || bytes.remaining() == 0 ? null : ofEpochMilli(bigint().deserializeNoBoxing(bytes, protocolVersion)); | |
| 90 | + public java.time.Instant deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) { | |
| 91 | + return bytes == null || bytes.remaining() == 0 ? null : java.time.Instant.ofEpochMilli(bigint().deserializeNoBoxing(bytes, protocolVersion)); | |
| 97 | 92 | } |
| 98 | 93 | |
| 99 | 94 | @Override |
| 100 | - public String format(Instant value) { | |
| 95 | + public String format(java.time.Instant value) { | |
| 101 | 96 | if (value == null) |
| 102 | 97 | return "NULL"; |
| 103 | 98 | return quote(FORMATTER.format(value)); |
| 104 | 99 | } |
| 105 | 100 | |
| 106 | 101 | @Override |
| 107 | - public Instant parse(String value) { | |
| 102 | + public java.time.Instant parse(String value) { | |
| 108 | 103 | if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) |
| 109 | 104 | return null; |
| 110 | 105 | // strip enclosing single quotes, if any |
| @@ -112,14 +107,14 @@ | ||
| 112 | 107 | value = unquote(value); |
| 113 | 108 | if (isLongLiteral(value)) { |
| 114 | 109 | try { |
| 115 | - return ofEpochMilli(parseLong(value)); | |
| 110 | + return java.time.Instant.ofEpochMilli(parseLong(value)); | |
| 116 | 111 | } catch (NumberFormatException e) { |
| 117 | 112 | throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); |
| 118 | 113 | } |
| 119 | 114 | } |
| 120 | 115 | try { |
| 121 | - return Instant.from(PARSER.parse(value)); | |
| 122 | - } catch (DateTimeParseException e) { | |
| 116 | + return java.time.Instant.from(PARSER.parse(value)); | |
| 117 | + } catch (java.time.format.DateTimeParseException e) { | |
| 123 | 118 | throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); |
| 124 | 119 | } |
| 125 | 120 | } |
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/LocalDateCodec.java +12 −13
| @@ -21,39 +21,38 @@ | ||
| 21 | 21 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 22 | 22 | |
| 23 | 23 | import java.nio.ByteBuffer; |
| 24 | -import java.time.LocalDate; | |
| 25 | -import java.time.temporal.ChronoUnit; | |
| 26 | 24 | |
| 27 | 25 | import static com.datastax.driver.core.CodecUtils.*; |
| 28 | 26 | import static com.datastax.driver.core.ParseUtils.*; |
| 29 | 27 | import static java.lang.Long.parseLong; |
| 30 | -import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE; | |
| 31 | 28 | |
| 32 | 29 | /** |
| 33 | 30 | * {@link TypeCodec} that maps |
| 34 | 31 | * {@link java.time.LocalDate} to CQL {@code date}. |
| 35 | 32 | */ |
| 36 | -public class LocalDateCodec extends TypeCodec<LocalDate> { | |
| 33 | +@IgnoreJDK6Requirement | |
| 34 | +@SuppressWarnings("Since15") | |
| 35 | +public class LocalDateCodec extends TypeCodec<java.time.LocalDate> { | |
| 37 | 36 | |
| 38 | 37 | public static final LocalDateCodec instance = new LocalDateCodec(); |
| 39 | 38 | |
| 40 | - private static final LocalDate EPOCH = LocalDate.of(1970, 1, 1); | |
| 39 | + private static final java.time.LocalDate EPOCH = java.time.LocalDate.of(1970, 1, 1); | |
| 41 | 40 | |
| 42 | 41 | private LocalDateCodec() { |
| 43 | - super(DataType.date(), LocalDate.class); | |
| 42 | + super(DataType.date(), java.time.LocalDate.class); | |
| 44 | 43 | } |
| 45 | 44 | |
| 46 | 45 | @Override |
| 47 | - public ByteBuffer serialize(LocalDate value, ProtocolVersion protocolVersion) { | |
| 46 | + public ByteBuffer serialize(java.time.LocalDate value, ProtocolVersion protocolVersion) { | |
| 48 | 47 | if (value == null) |
| 49 | 48 | return null; |
| 50 | - long days = ChronoUnit.DAYS.between(EPOCH, value); | |
| 49 | + long days = java.time.temporal.ChronoUnit.DAYS.between(EPOCH, value); | |
| 51 | 50 | int unsigned = fromSignedToUnsignedInt((int) days); |
| 52 | 51 | return cint().serializeNoBoxing(unsigned, protocolVersion); |
| 53 | 52 | } |
| 54 | 53 | |
| 55 | 54 | @Override |
| 56 | - public LocalDate deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) { | |
| 55 | + public java.time.LocalDate deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) { | |
| 57 | 56 | if (bytes == null || bytes.remaining() == 0) |
| 58 | 57 | return null; |
| 59 | 58 | int unsigned = cint().deserializeNoBoxing(bytes, protocolVersion); |
| @@ -62,14 +61,14 @@ | ||
| 62 | 61 | } |
| 63 | 62 | |
| 64 | 63 | @Override |
| 65 | - public String format(LocalDate value) { | |
| 64 | + public String format(java.time.LocalDate value) { | |
| 66 | 65 | if (value == null) |
| 67 | 66 | return "NULL"; |
| 68 | - return quote(ISO_LOCAL_DATE.format(value)); | |
| 67 | + return quote(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE.format(value)); | |
| 69 | 68 | } |
| 70 | 69 | |
| 71 | 70 | @Override |
| 72 | - public LocalDate parse(String value) { | |
| 71 | + public java.time.LocalDate parse(String value) { | |
| 73 | 72 | if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) |
| 74 | 73 | return null; |
| 75 | 74 | |
| @@ -95,7 +94,7 @@ | ||
| 95 | 94 | } |
| 96 | 95 | |
| 97 | 96 | try { |
| 98 | - return LocalDate.parse(value, ISO_LOCAL_DATE); | |
| 97 | + return java.time.LocalDate.parse(value, java.time.format.DateTimeFormatter.ISO_LOCAL_DATE); | |
| 99 | 98 | } catch (RuntimeException e) { |
| 100 | 99 | throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value)); |
| 101 | 100 | } |
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodec.java +13 −13
| @@ -22,48 +22,48 @@ | ||
| 22 | 22 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 23 | 23 | |
| 24 | 24 | import java.nio.ByteBuffer; |
| 25 | -import java.time.LocalTime; | |
| 26 | -import java.time.format.DateTimeFormatter; | |
| 27 | 25 | |
| 28 | 26 | import static com.datastax.driver.core.ParseUtils.quote; |
| 29 | 27 | |
| 30 | 28 | /** |
| 31 | - * {@link TypeCodec} that maps {@link LocalTime} to CQL {@code time} (long representing nanoseconds since midnight). | |
| 29 | + * {@link TypeCodec} that maps {@link java.time.LocalTime} to CQL {@code time} (long representing nanoseconds since midnight). | |
| 32 | 30 | */ |
| 33 | -public class LocalTimeCodec extends TypeCodec<LocalTime> { | |
| 31 | +@IgnoreJDK6Requirement | |
| 32 | +@SuppressWarnings("Since15") | |
| 33 | +public class LocalTimeCodec extends TypeCodec<java.time.LocalTime> { | |
| 34 | 34 | |
| 35 | 35 | public static final LocalTimeCodec instance = new LocalTimeCodec(); |
| 36 | 36 | |
| 37 | - private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); | |
| 37 | + private static final java.time.format.DateTimeFormatter FORMATTER = java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); | |
| 38 | 38 | |
| 39 | 39 | private LocalTimeCodec() { |
| 40 | - super(DataType.time(), LocalTime.class); | |
| 40 | + super(DataType.time(), java.time.LocalTime.class); | |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | 43 | @Override |
| 44 | - public ByteBuffer serialize(LocalTime value, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 44 | + public ByteBuffer serialize(java.time.LocalTime value, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 45 | 45 | if (value == null) |
| 46 | 46 | return null; |
| 47 | 47 | return bigint().serializeNoBoxing(value.toNanoOfDay(), protocolVersion); |
| 48 | 48 | } |
| 49 | 49 | |
| 50 | 50 | @Override |
| 51 | - public LocalTime deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 51 | + public java.time.LocalTime deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 52 | 52 | if (bytes == null || bytes.remaining() == 0) |
| 53 | 53 | return null; |
| 54 | 54 | long nanosOfDay = bigint().deserializeNoBoxing(bytes, protocolVersion); |
| 55 | - return LocalTime.ofNanoOfDay(nanosOfDay); | |
| 55 | + return java.time.LocalTime.ofNanoOfDay(nanosOfDay); | |
| 56 | 56 | } |
| 57 | 57 | |
| 58 | 58 | @Override |
| 59 | - public String format(LocalTime value) { | |
| 59 | + public String format(java.time.LocalTime value) { | |
| 60 | 60 | if (value == null) |
| 61 | 61 | return "NULL"; |
| 62 | 62 | return quote(FORMATTER.format(value)); |
| 63 | 63 | } |
| 64 | 64 | |
| 65 | 65 | @Override |
| 66 | - public LocalTime parse(String value) { | |
| 66 | + public java.time.LocalTime parse(String value) { | |
| 67 | 67 | if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) |
| 68 | 68 | return null; |
| 69 | 69 | |
| @@ -79,11 +79,11 @@ | ||
| 79 | 79 | } catch (NumberFormatException e) { |
| 80 | 80 | throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e); |
| 81 | 81 | } |
| 82 | - return LocalTime.ofNanoOfDay(nanosOfDay); | |
| 82 | + return java.time.LocalTime.ofNanoOfDay(nanosOfDay); | |
| 83 | 83 | } |
| 84 | 84 | |
| 85 | 85 | try { |
| 86 | - return LocalTime.parse(value); | |
| 86 | + return java.time.LocalTime.parse(value); | |
| 87 | 87 | } catch (RuntimeException e) { |
| 88 | 88 | throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e); |
| 89 | 89 | } |
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodec.java +11 −11
| @@ -22,20 +22,20 @@ | ||
| 22 | 22 | |
| 23 | 23 | import java.util.Collection; |
| 24 | 24 | import java.util.Map; |
| 25 | -import java.util.Optional; | |
| 26 | -import java.util.function.Predicate; | |
| 27 | 25 | |
| 28 | 26 | /** |
| 29 | - * A codec that wraps other codecs around JDK 8's {@link Optional} API. | |
| 27 | + * A codec that wraps other codecs around JDK 8's {@link java.util.Optional} API. | |
| 30 | 28 | * |
| 31 | 29 | * @param <T> The wrapped Java type |
| 32 | 30 | */ |
| 33 | -public class OptionalCodec<T> extends MappingCodec<Optional<T>, T> { | |
| 31 | +@IgnoreJDK6Requirement | |
| 32 | +@SuppressWarnings({"Since15", "OptionalUsedAsFieldOrParameterType"}) | |
| 33 | +public class OptionalCodec<T> extends MappingCodec<java.util.Optional<T>, T> { | |
| 34 | 34 | |
| 35 | - private final Predicate<T> isAbsent; | |
| 35 | + private final java.util.function.Predicate<T> isAbsent; | |
| 36 | 36 | |
| 37 | 37 | public OptionalCodec(TypeCodec<T> codec) { |
| 38 | - this(codec, new Predicate<T>() { | |
| 38 | + this(codec, new java.util.function.Predicate<T>() { | |
| 39 | 39 | @Override |
| 40 | 40 | public boolean test(T input) { |
| 41 | 41 | return input == null |
| @@ -46,20 +46,20 @@ | ||
| 46 | 46 | }); |
| 47 | 47 | } |
| 48 | 48 | |
| 49 | - public OptionalCodec(TypeCodec<T> codec, Predicate<T> isAbsent) { | |
| 49 | + public OptionalCodec(TypeCodec<T> codec, java.util.function.Predicate<T> isAbsent) { | |
| 50 | 50 | // @formatter:off |
| 51 | - super(codec, new TypeToken<Optional<T>>() {}.where(new TypeParameter<T>() {}, codec.getJavaType())); | |
| 51 | + super(codec, new TypeToken<java.util.Optional<T>>() {}.where(new TypeParameter<T>() {}, codec.getJavaType())); | |
| 52 | 52 | // @formatter:on |
| 53 | 53 | this.isAbsent = isAbsent; |
| 54 | 54 | } |
| 55 | 55 | |
| 56 | 56 | @Override |
| 57 | - protected Optional<T> deserialize(T value) { | |
| 58 | - return isAbsent(value) ? Optional.<T>empty() : Optional.of(value); | |
| 57 | + protected java.util.Optional<T> deserialize(T value) { | |
| 58 | + return isAbsent(value) ? java.util.Optional.<T>empty() : java.util.Optional.of(value); | |
| 59 | 59 | } |
| 60 | 60 | |
| 61 | 61 | @Override |
| 62 | - protected T serialize(Optional<T> value) { | |
| 62 | + protected T serialize(java.util.Optional<T> value) { | |
| 63 | 63 | return value.isPresent() ? value.get() : absentValue(); |
| 64 | 64 | } |
| 65 | 65 |
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodec.java +25 −31
| @@ -19,23 +19,15 @@ | ||
| 19 | 19 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 20 | 20 | |
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | -import java.time.Instant; | |
| 23 | -import java.time.ZoneId; | |
| 24 | -import java.time.ZoneOffset; | |
| 25 | -import java.time.ZonedDateTime; | |
| 26 | -import java.time.format.DateTimeFormatter; | |
| 27 | -import java.time.format.DateTimeFormatterBuilder; | |
| 28 | -import java.time.format.DateTimeParseException; | |
| 29 | 22 | import java.util.List; |
| 30 | 23 | |
| 31 | 24 | import static com.datastax.driver.core.ParseUtils.isLongLiteral; |
| 32 | 25 | import static com.datastax.driver.core.ParseUtils.quote; |
| 33 | 26 | import static com.google.common.base.Preconditions.checkArgument; |
| 34 | -import static java.time.temporal.ChronoField.*; | |
| 35 | 27 | |
| 36 | 28 | /** |
| 37 | 29 | * {@link TypeCodec} that maps |
| 38 | - * {@link ZonedDateTime} to CQL {@code tuple<timestamp,varchar>}, | |
| 30 | + * {@link java.time.ZonedDateTime} to CQL {@code tuple<timestamp,varchar>}, | |
| 39 | 31 | * providing a pattern for maintaining timezone information in |
| 40 | 32 | * Cassandra. |
| 41 | 33 | * <p/> |
| @@ -53,39 +45,41 @@ | ||
| 53 | 45 | * |
| 54 | 46 | * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps">'Working with timestamps' section of CQL specification</a> |
| 55 | 47 | */ |
| 56 | -public class ZonedDateTimeCodec extends TypeCodec.AbstractTupleCodec<ZonedDateTime> { | |
| 48 | +@IgnoreJDK6Requirement | |
| 49 | +@SuppressWarnings("Since15") | |
| 50 | +public class ZonedDateTimeCodec extends TypeCodec.AbstractTupleCodec<java.time.ZonedDateTime> { | |
| 57 | 51 | |
| 58 | 52 | /** |
| 59 | - * A {@link DateTimeFormatter} that parses (most) of | |
| 53 | + * A {@link java.time.format.DateTimeFormatter} that parses (most) of | |
| 60 | 54 | * the ISO formats accepted in CQL. |
| 61 | 55 | */ |
| 62 | - private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder() | |
| 56 | + private static final java.time.format.DateTimeFormatter FORMATTER = new java.time.format.DateTimeFormatterBuilder() | |
| 63 | 57 | .parseCaseSensitive() |
| 64 | 58 | .parseStrict() |
| 65 | - .append(DateTimeFormatter.ISO_LOCAL_DATE) | |
| 59 | + .append(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE) | |
| 66 | 60 | .optionalStart() |
| 67 | 61 | .appendLiteral('T') |
| 68 | - .appendValue(HOUR_OF_DAY, 2) | |
| 62 | + .appendValue(java.time.temporal.ChronoField.HOUR_OF_DAY, 2) | |
| 69 | 63 | .appendLiteral(':') |
| 70 | - .appendValue(MINUTE_OF_HOUR, 2) | |
| 64 | + .appendValue(java.time.temporal.ChronoField.MINUTE_OF_HOUR, 2) | |
| 71 | 65 | .optionalEnd() |
| 72 | 66 | .optionalStart() |
| 73 | 67 | .appendLiteral(':') |
| 74 | - .appendValue(SECOND_OF_MINUTE, 2) | |
| 68 | + .appendValue(java.time.temporal.ChronoField.SECOND_OF_MINUTE, 2) | |
| 75 | 69 | .optionalEnd() |
| 76 | 70 | .optionalStart() |
| 77 | - .appendFraction(NANO_OF_SECOND, 0, 9, true) | |
| 71 | + .appendFraction(java.time.temporal.ChronoField.NANO_OF_SECOND, 0, 9, true) | |
| 78 | 72 | .optionalEnd() |
| 79 | 73 | .optionalStart() |
| 80 | 74 | .appendZoneOrOffsetId() |
| 81 | 75 | .optionalEnd() |
| 82 | 76 | .toFormatter() |
| 83 | - .withZone(ZoneOffset.UTC); | |
| 77 | + .withZone(java.time.ZoneOffset.UTC); | |
| 84 | 78 | |
| 85 | - private static final DateTimeFormatter ZONE_FORMATTER = DateTimeFormatter.ofPattern("xxx"); | |
| 79 | + private static final java.time.format.DateTimeFormatter ZONE_FORMATTER = java.time.format.DateTimeFormatter.ofPattern("xxx"); | |
| 86 | 80 | |
| 87 | 81 | public ZonedDateTimeCodec(TupleType tupleType) { |
| 88 | - super(tupleType, ZonedDateTime.class); | |
| 82 | + super(tupleType, java.time.ZonedDateTime.class); | |
| 89 | 83 | List<DataType> types = tupleType.getComponentTypes(); |
| 90 | 84 | checkArgument( |
| 91 | 85 | types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()), |
| @@ -94,12 +88,12 @@ | ||
| 94 | 88 | } |
| 95 | 89 | |
| 96 | 90 | @Override |
| 97 | - protected ZonedDateTime newInstance() { | |
| 91 | + protected java.time.ZonedDateTime newInstance() { | |
| 98 | 92 | return null; |
| 99 | 93 | } |
| 100 | 94 | |
| 101 | 95 | @Override |
| 102 | - protected ByteBuffer serializeField(ZonedDateTime source, int index, ProtocolVersion protocolVersion) { | |
| 96 | + protected ByteBuffer serializeField(java.time.ZonedDateTime source, int index, ProtocolVersion protocolVersion) { | |
| 103 | 97 | if (index == 0) { |
| 104 | 98 | long millis = source.toInstant().toEpochMilli(); |
| 105 | 99 | return bigint().serializeNoBoxing(millis, protocolVersion); |
| @@ -111,20 +105,20 @@ | ||
| 111 | 105 | } |
| 112 | 106 | |
| 113 | 107 | @Override |
| 114 | - protected ZonedDateTime deserializeAndSetField(ByteBuffer input, ZonedDateTime target, int index, ProtocolVersion protocolVersion) { | |
| 108 | + protected java.time.ZonedDateTime deserializeAndSetField(ByteBuffer input, java.time.ZonedDateTime target, int index, ProtocolVersion protocolVersion) { | |
| 115 | 109 | if (index == 0) { |
| 116 | 110 | long millis = bigint().deserializeNoBoxing(input, protocolVersion); |
| 117 | - return Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC); | |
| 111 | + return java.time.Instant.ofEpochMilli(millis).atZone(java.time.ZoneOffset.UTC); | |
| 118 | 112 | } |
| 119 | 113 | if (index == 1) { |
| 120 | 114 | String zoneId = varchar().deserialize(input, protocolVersion); |
| 121 | - return target.withZoneSameInstant(ZoneId.of(zoneId)); | |
| 115 | + return target.withZoneSameInstant(java.time.ZoneId.of(zoneId)); | |
| 122 | 116 | } |
| 123 | 117 | throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index); |
| 124 | 118 | } |
| 125 | 119 | |
| 126 | 120 | @Override |
| 127 | - protected String formatField(ZonedDateTime value, int index) { | |
| 121 | + protected String formatField(java.time.ZonedDateTime value, int index) { | |
| 128 | 122 | if (index == 0) { |
| 129 | 123 | return quote(FORMATTER.format(value)); |
| 130 | 124 | } |
| @@ -135,7 +129,7 @@ | ||
| 135 | 129 | } |
| 136 | 130 | |
| 137 | 131 | @Override |
| 138 | - protected ZonedDateTime parseAndSetField(String input, ZonedDateTime target, int index) { | |
| 132 | + protected java.time.ZonedDateTime parseAndSetField(String input, java.time.ZonedDateTime target, int index) { | |
| 139 | 133 | if (index == 0) { |
| 140 | 134 | // strip enclosing single quotes, if any |
| 141 | 135 | if (ParseUtils.isQuoted(input)) |
| @@ -143,20 +137,20 @@ | ||
| 143 | 137 | if (isLongLiteral(input)) { |
| 144 | 138 | try { |
| 145 | 139 | long millis = Long.parseLong(input); |
| 146 | - return ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneOffset.UTC); | |
| 140 | + return java.time.ZonedDateTime.ofInstant(java.time.Instant.ofEpochMilli(millis), java.time.ZoneOffset.UTC); | |
| 147 | 141 | } catch (NumberFormatException e) { |
| 148 | 142 | throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", input)); |
| 149 | 143 | } |
| 150 | 144 | } |
| 151 | 145 | try { |
| 152 | - return ZonedDateTime.from(FORMATTER.parse(input)); | |
| 153 | - } catch (DateTimeParseException e) { | |
| 146 | + return java.time.ZonedDateTime.from(FORMATTER.parse(input)); | |
| 147 | + } catch (java.time.format.DateTimeParseException e) { | |
| 154 | 148 | throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", target)); |
| 155 | 149 | } |
| 156 | 150 | } |
| 157 | 151 | if (index == 1) { |
| 158 | 152 | String zoneId = varchar().parse(input); |
| 159 | - return target.withZoneSameInstant(ZoneId.of(zoneId)); | |
| 153 | + return target.withZoneSameInstant(java.time.ZoneId.of(zoneId)); | |
| 160 | 154 | } |
| 161 | 155 | throw new IndexOutOfBoundsException("Tuple index out of bounds. " + index); |
| 162 | 156 | } |
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/package-info.java +1 −1
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | * This package contains a collection of convenience |
| 19 | 19 | * {@link com.datastax.driver.core.TypeCodec TypeCodec} instances useful for |
| 20 | 20 | * serializing between CQL types and Java 8 types, such as the ones from the |
| 21 | - * {@link java.time} API and {@link java.util.Optional}. | |
| 21 | + * {@code java.time} API and {@code java.util.Optional}. | |
| 22 | 22 | * <p/> |
| 23 | 23 | * <p/> |
| 24 | 24 | * Note that, while the driver remains globally compatible with older JDKs, |
modified driver-mapping/pom.xml +16 −81
| @@ -93,6 +93,21 @@ | ||
| 93 | 93 | <version>4.1</version> |
| 94 | 94 | </dependency> |
| 95 | 95 | --> |
| 96 | + | |
| 97 | + <dependency> | |
| 98 | + <groupId>log4j</groupId> | |
| 99 | + <artifactId>log4j</artifactId> | |
| 100 | + <version>${log4j.version}</version> | |
| 101 | + <scope>test</scope> | |
| 102 | + </dependency> | |
| 103 | + | |
| 104 | + <dependency> | |
| 105 | + <groupId>org.slf4j</groupId> | |
| 106 | + <artifactId>slf4j-log4j12</artifactId> | |
| 107 | + <version>${slf4j-log4j12.version}</version> | |
| 108 | + <scope>test</scope> | |
| 109 | + </dependency> | |
| 110 | + | |
| 96 | 111 | </dependencies> |
| 97 | 112 | |
| 98 | 113 | <build> |
| @@ -116,6 +131,7 @@ | ||
| 116 | 131 | <Bundle-SymbolicName>com.datastax.driver.mapping</Bundle-SymbolicName> |
| 117 | 132 | <Bundle-Version>${project.version}</Bundle-Version> |
| 118 | 133 | <_include>-osgi.bnd</_include> |
| 134 | + <Import-Package><![CDATA[com.google.common*;version="[16.0.1,20)",*]]></Import-Package> | |
| 119 | 135 | </instructions> |
| 120 | 136 | <supportedProjectTypes> |
| 121 | 137 | <supportedProjectType>jar</supportedProjectType> |
| @@ -127,87 +143,6 @@ | ||
| 127 | 143 | </plugins> |
| 128 | 144 | </build> |
| 129 | 145 | |
| 130 | - <profiles> | |
| 131 | - <profile> | |
| 132 | - <id>unit</id> | |
| 133 | - <properties> | |
| 134 | - <env>default</env> | |
| 135 | - </properties> | |
| 136 | - <!-- do not use activeByDefault as other profiles might be active --> | |
| 137 | - <activation> | |
| 138 | - <property> | |
| 139 | - <name>!activateUnitTests</name> | |
| 140 | - </property> | |
| 141 | - </activation> | |
| 142 | - <build> | |
| 143 | - <plugins> | |
| 144 | - <plugin> | |
| 145 | - <groupId>org.apache.maven.plugins</groupId> | |
| 146 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 147 | - <version>2.14</version> | |
| 148 | - <configuration> | |
| 149 | - <groups>unit</groups> | |
| 150 | - <useFile>false</useFile> | |
| 151 | - <systemPropertyVariables> | |
| 152 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 153 | - <ipprefix>${ipprefix}</ipprefix> | |
| 154 | - </systemPropertyVariables> | |
| 155 | - </configuration> | |
| 156 | - </plugin> | |
| 157 | - </plugins> | |
| 158 | - </build> | |
| 159 | - </profile> | |
| 160 | - | |
| 161 | - <profile> | |
| 162 | - <id>short</id> | |
| 163 | - <properties> | |
| 164 | - <env>default</env> | |
| 165 | - </properties> | |
| 166 | - <build> | |
| 167 | - <plugins> | |
| 168 | - <plugin> | |
| 169 | - <groupId>org.apache.maven.plugins</groupId> | |
| 170 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 171 | - <version>2.14</version> | |
| 172 | - <configuration> | |
| 173 | - <groups>unit,short</groups> | |
| 174 | - <useFile>false</useFile> | |
| 175 | - <systemPropertyVariables> | |
| 176 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 177 | - <ipprefix>${ipprefix}</ipprefix> | |
| 178 | - </systemPropertyVariables> | |
| 179 | - </configuration> | |
| 180 | - </plugin> | |
| 181 | - </plugins> | |
| 182 | - </build> | |
| 183 | - </profile> | |
| 184 | - | |
| 185 | - <profile> | |
| 186 | - <id>long</id> | |
| 187 | - <properties> | |
| 188 | - <env>default</env> | |
| 189 | - </properties> | |
| 190 | - <build> | |
| 191 | - <plugins> | |
| 192 | - <plugin> | |
| 193 | - <groupId>org.apache.maven.plugins</groupId> | |
| 194 | - <artifactId>maven-surefire-plugin</artifactId> | |
| 195 | - <version>2.14</version> | |
| 196 | - <configuration> | |
| 197 | - <groups>unit,short,long</groups> | |
| 198 | - <useFile>false</useFile> | |
| 199 | - <systemPropertyVariables> | |
| 200 | - <cassandra.version>${cassandra.version}</cassandra.version> | |
| 201 | - <ipprefix>${ipprefix}</ipprefix> | |
| 202 | - </systemPropertyVariables> | |
| 203 | - </configuration> | |
| 204 | - </plugin> | |
| 205 | - </plugins> | |
| 206 | - </build> | |
| 207 | - </profile> | |
| 208 | - | |
| 209 | - </profiles> | |
| 210 | - | |
| 211 | 146 | <licenses> |
| 212 | 147 | <license> |
| 213 | 148 | <name>Apache 2</name> |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +6 −1
| @@ -320,15 +320,20 @@ | ||
| 320 | 320 | ConsistencyLevel cl = null; |
| 321 | 321 | int fetchSize = -1; |
| 322 | 322 | boolean tracing = false; |
| 323 | + Boolean idempotent = null; | |
| 323 | 324 | |
| 324 | 325 | QueryParameters options = m.getAnnotation(QueryParameters.class); |
| 325 | 326 | if (options != null) { |
| 326 | 327 | cl = options.consistency().isEmpty() ? null : ConsistencyLevel.valueOf(options.consistency().toUpperCase()); |
| 327 | 328 | fetchSize = options.fetchSize(); |
| 328 | 329 | tracing = options.tracing(); |
| 330 | + if (options.idempotent().length > 1) { | |
| 331 | + throw new IllegalStateException("idemtpotence() attribute can only accept one value"); | |
| 332 | + } | |
| 333 | + idempotent = options.idempotent().length == 0 ? null : options.idempotent()[0]; | |
| 329 | 334 | } |
| 330 | 335 | |
| 331 | - methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing)); | |
| 336 | + methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing, idempotent)); | |
| 332 | 337 | } |
| 333 | 338 | |
| 334 | 339 | return factory.create(accClass, methods); |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +5 −7
| @@ -24,9 +24,7 @@ | ||
| 24 | 24 | |
| 25 | 25 | abstract class ColumnMapper<T> { |
| 26 | 26 | |
| 27 | - public enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED} | |
| 28 | - | |
| 29 | - ; | |
| 27 | + enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED} | |
| 30 | 28 | |
| 31 | 29 | private final String columnName; |
| 32 | 30 | private final String alias; |
| @@ -52,17 +50,17 @@ | ||
| 52 | 50 | this.customCodec = AnnotationParser.customCodec(field); |
| 53 | 51 | } |
| 54 | 52 | |
| 55 | - public abstract Object getValue(T entity); | |
| 53 | + abstract Object getValue(T entity); | |
| 56 | 54 | |
| 57 | - public abstract void setValue(T entity, Object value); | |
| 55 | + abstract void setValue(T entity, Object value); | |
| 58 | 56 | |
| 59 | - public String getColumnName() { | |
| 57 | + String getColumnName() { | |
| 60 | 58 | return kind == Kind.COMPUTED |
| 61 | 59 | ? columnName |
| 62 | 60 | : Metadata.quote(columnName); |
| 63 | 61 | } |
| 64 | 62 | |
| 65 | - public String getAlias() { | |
| 63 | + String getAlias() { | |
| 66 | 64 | return alias; |
| 67 | 65 | } |
| 68 | 66 |
added driver-mapping/src/main/java/com/datastax/driver/mapping/DriverThrowables.java +45 −0
| @@ -0,0 +1,45 @@ | ||
| 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.mapping; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 19 | +import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 20 | + | |
| 21 | +import java.util.concurrent.ExecutionException; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * Copied here from com.datastax.driver.core.DriverThrowables | |
| 25 | + * because we don't want this class to be public. | |
| 26 | + */ | |
| 27 | +class DriverThrowables { | |
| 28 | + | |
| 29 | + static RuntimeException propagateCause(ExecutionException e) { | |
| 30 | + Throwable cause = e.getCause(); | |
| 31 | + | |
| 32 | + if (cause instanceof Error) | |
| 33 | + throw ((Error) cause); | |
| 34 | + | |
| 35 | + // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been | |
| 36 | + // created on the I/O thread receiving the response. Which means that the stacktrace associated | |
| 37 | + // with said cause will make no mention of the current thread. This is painful for say, finding | |
| 38 | + // out which execute() statement actually raised the exception. So instead, we re-create the | |
| 39 | + // exception. | |
| 40 | + if (cause instanceof DriverException) | |
| 41 | + throw ((DriverException) cause).copy(); | |
| 42 | + else | |
| 43 | + throw new DriverInternalError("Unexpected exception thrown", cause); | |
| 44 | + } | |
| 45 | +} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/EntityMapper.java +14 −14
| @@ -26,16 +26,16 @@ | ||
| 26 | 26 | |
| 27 | 27 | abstract class EntityMapper<T> { |
| 28 | 28 | |
| 29 | - public final Class<T> entityClass; | |
| 29 | + final Class<T> entityClass; | |
| 30 | 30 | private final String keyspace; |
| 31 | 31 | private final String table; |
| 32 | 32 | |
| 33 | - public final ConsistencyLevel writeConsistency; | |
| 34 | - public final ConsistencyLevel readConsistency; | |
| 33 | + final ConsistencyLevel writeConsistency; | |
| 34 | + final ConsistencyLevel readConsistency; | |
| 35 | 35 | |
| 36 | - public final List<ColumnMapper<T>> partitionKeys = new ArrayList<ColumnMapper<T>>(); | |
| 37 | - public final List<ColumnMapper<T>> clusteringColumns = new ArrayList<ColumnMapper<T>>(); | |
| 38 | - public final List<ColumnMapper<T>> regularColumns = new ArrayList<ColumnMapper<T>>(); | |
| 36 | + final List<ColumnMapper<T>> partitionKeys = new ArrayList<ColumnMapper<T>>(); | |
| 37 | + final List<ColumnMapper<T>> clusteringColumns = new ArrayList<ColumnMapper<T>>(); | |
| 38 | + final List<ColumnMapper<T>> regularColumns = new ArrayList<ColumnMapper<T>>(); | |
| 39 | 39 | |
| 40 | 40 | private final List<ColumnMapper<T>> allColumns = new ArrayList<ColumnMapper<T>>(); |
| 41 | 41 | |
| @@ -47,23 +47,23 @@ | ||
| 47 | 47 | this.readConsistency = readConsistency; |
| 48 | 48 | } |
| 49 | 49 | |
| 50 | - public String getKeyspace() { | |
| 50 | + String getKeyspace() { | |
| 51 | 51 | return quote(keyspace); |
| 52 | 52 | } |
| 53 | 53 | |
| 54 | - public String getTable() { | |
| 54 | + String getTable() { | |
| 55 | 55 | return quote(table); |
| 56 | 56 | } |
| 57 | 57 | |
| 58 | - public int primaryKeySize() { | |
| 58 | + int primaryKeySize() { | |
| 59 | 59 | return partitionKeys.size() + clusteringColumns.size(); |
| 60 | 60 | } |
| 61 | 61 | |
| 62 | - public ColumnMapper<T> getPrimaryKeyColumn(int i) { | |
| 62 | + ColumnMapper<T> getPrimaryKeyColumn(int i) { | |
| 63 | 63 | return i < partitionKeys.size() ? partitionKeys.get(i) : clusteringColumns.get(i - partitionKeys.size()); |
| 64 | 64 | } |
| 65 | 65 | |
| 66 | - public void addColumns(List<ColumnMapper<T>> pks, List<ColumnMapper<T>> ccs, List<ColumnMapper<T>> rgs) { | |
| 66 | + void addColumns(List<ColumnMapper<T>> pks, List<ColumnMapper<T>> ccs, List<ColumnMapper<T>> rgs) { | |
| 67 | 67 | partitionKeys.addAll(pks); |
| 68 | 68 | allColumns.addAll(pks); |
| 69 | 69 | |
| @@ -73,14 +73,14 @@ | ||
| 73 | 73 | addColumns(rgs); |
| 74 | 74 | } |
| 75 | 75 | |
| 76 | - public void addColumns(List<ColumnMapper<T>> rgs) { | |
| 76 | + void addColumns(List<ColumnMapper<T>> rgs) { | |
| 77 | 77 | regularColumns.addAll(rgs); |
| 78 | 78 | allColumns.addAll(rgs); |
| 79 | 79 | } |
| 80 | 80 | |
| 81 | - public abstract T newEntity(); | |
| 81 | + abstract T newEntity(); | |
| 82 | 82 | |
| 83 | - public List<ColumnMapper<T>> allColumns() { | |
| 83 | + List<ColumnMapper<T>> allColumns() { | |
| 84 | 84 | return allColumns; |
| 85 | 85 | } |
| 86 | 86 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +234 −139
| @@ -20,18 +20,19 @@ | ||
| 20 | 20 | import com.datastax.driver.core.querybuilder.Insert; |
| 21 | 21 | import com.datastax.driver.core.querybuilder.QueryBuilder; |
| 22 | 22 | import com.datastax.driver.mapping.Mapper.Option.SaveNullFields; |
| 23 | -import com.datastax.driver.mapping.annotations.Accessor; | |
| 24 | 23 | import com.datastax.driver.mapping.annotations.Computed; |
| 25 | 24 | import com.google.common.base.Function; |
| 26 | 25 | import com.google.common.base.Functions; |
| 27 | 26 | import com.google.common.base.Objects; |
| 28 | 27 | import com.google.common.base.Preconditions; |
| 29 | -import com.google.common.util.concurrent.Futures; | |
| 30 | -import com.google.common.util.concurrent.ListenableFuture; | |
| 28 | +import com.google.common.util.concurrent.*; | |
| 31 | 29 | import org.slf4j.Logger; |
| 32 | 30 | import org.slf4j.LoggerFactory; |
| 33 | 31 | |
| 34 | 32 | import java.util.*; |
| 33 | +import java.util.concurrent.ConcurrentHashMap; | |
| 34 | +import java.util.concurrent.ConcurrentMap; | |
| 35 | +import java.util.concurrent.ExecutionException; | |
| 35 | 36 | |
| 36 | 37 | import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS; |
| 37 | 38 | import static com.google.common.base.Preconditions.checkArgument; |
| @@ -44,7 +45,8 @@ | ||
| 44 | 45 | */ |
| 45 | 46 | public class Mapper<T> { |
| 46 | 47 | |
| 47 | - private static final Logger logger = LoggerFactory.getLogger(EntityMapper.class); | |
| 48 | + private static final Logger logger = LoggerFactory.getLogger(Mapper.class); | |
| 49 | + private static final Function<Object, Void> TO_NULL = Functions.constant(null); | |
| 48 | 50 | |
| 49 | 51 | final MappingManager manager; |
| 50 | 52 | final ProtocolVersion protocolVersion; |
| @@ -53,9 +55,7 @@ | ||
| 53 | 55 | final TableMetadata tableMetadata; |
| 54 | 56 | |
| 55 | 57 | // Cache prepared statements for each type of query we use. |
| 56 | - private volatile Map<MapperQueryKey, PreparedStatement> preparedQueries = Collections.emptyMap(); | |
| 57 | - | |
| 58 | - private static final Function<Object, Void> NOOP = Functions.constant(null); | |
| 58 | + private final ConcurrentMap<MapperQueryKey, ListenableFuture<PreparedStatement>> preparedQueries = new ConcurrentHashMap<MapperQueryKey, ListenableFuture<PreparedStatement>>(); | |
| 59 | 59 | |
| 60 | 60 | private volatile EnumMap<Option.Type, Option> defaultSaveOptions; |
| 61 | 61 | private volatile EnumMap<Option.Type, Option> defaultGetOptions; |
| @@ -79,7 +79,7 @@ | ||
| 79 | 79 | this.mapOneFunction = new Function<ResultSet, T>() { |
| 80 | 80 | @Override |
| 81 | 81 | public T apply(ResultSet rs) { |
| 82 | - return Mapper.this.mapAliased(rs).one(); | |
| 82 | + return Mapper.this.map(rs).one(); | |
| 83 | 83 | } |
| 84 | 84 | }; |
| 85 | 85 | this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() { |
| @@ -104,29 +104,41 @@ | ||
| 104 | 104 | return manager.getSession(); |
| 105 | 105 | } |
| 106 | 106 | |
| 107 | - PreparedStatement getPreparedQuery(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) { | |
| 108 | - | |
| 109 | - MapperQueryKey pqk = new MapperQueryKey(type, columns, options); | |
| 110 | - | |
| 111 | - PreparedStatement stmt = preparedQueries.get(pqk); | |
| 112 | - if (stmt == null) { | |
| 113 | - synchronized (preparedQueries) { | |
| 114 | - stmt = preparedQueries.get(pqk); | |
| 115 | - if (stmt == null) { | |
| 116 | - String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values()); | |
| 117 | - logger.debug("Preparing query {}", queryString); | |
| 118 | - stmt = session().prepare(queryString); | |
| 119 | - Map<MapperQueryKey, PreparedStatement> newQueries = new HashMap<MapperQueryKey, PreparedStatement>(preparedQueries); | |
| 120 | - newQueries.put(pqk, stmt); | |
| 121 | - preparedQueries = newQueries; | |
| 122 | - } | |
| 107 | + ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) { | |
| 108 | + | |
| 109 | + final MapperQueryKey pqk = new MapperQueryKey(type, columns, options); | |
| 110 | + ListenableFuture<PreparedStatement> existingFuture = preparedQueries.get(pqk); | |
| 111 | + if (existingFuture == null) { | |
| 112 | + final SettableFuture<PreparedStatement> future = SettableFuture.create(); | |
| 113 | + ListenableFuture<PreparedStatement> old = preparedQueries.putIfAbsent(pqk, future); | |
| 114 | + if (old != null) { | |
| 115 | + return old; | |
| 116 | + } else { | |
| 117 | + String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values()); | |
| 118 | + logger.debug("Preparing query {}", queryString); | |
| 119 | + SimpleStatement s = new SimpleStatement(queryString); | |
| 120 | + // all queries generated by the mapper are idempotent | |
| 121 | + s.setIdempotent(true); | |
| 122 | + Futures.addCallback(session().prepareAsync(s), new FutureCallback<PreparedStatement>() { | |
| 123 | + @Override | |
| 124 | + public void onSuccess(PreparedStatement stmt) { | |
| 125 | + future.set(stmt); | |
| 126 | + } | |
| 127 | + | |
| 128 | + @Override | |
| 129 | + public void onFailure(Throwable t) { | |
| 130 | + future.setException(t); | |
| 131 | + } | |
| 132 | + }); | |
| 133 | + return future; | |
| 123 | 134 | } |
| 135 | + } else { | |
| 136 | + return existingFuture; | |
| 124 | 137 | } |
| 125 | - return stmt; | |
| 126 | 138 | } |
| 127 | 139 | |
| 128 | - PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) { | |
| 129 | - return getPreparedQuery(type, Collections.<ColumnMapper<?>>emptySet(), options); | |
| 140 | + ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, EnumMap<Option.Type, Option> options) { | |
| 141 | + return getPreparedQueryAsync(type, Collections.<ColumnMapper<?>>emptySet(), options); | |
| 130 | 142 | } |
| 131 | 143 | |
| 132 | 144 | /** |
| @@ -160,7 +172,11 @@ | ||
| 160 | 172 | * @return a query that saves {@code entity} (based on it's defined mapping). |
| 161 | 173 | */ |
| 162 | 174 | public Statement saveQuery(T entity) { |
| 163 | - return saveQuery(entity, this.defaultSaveOptions); | |
| 175 | + try { | |
| 176 | + return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, this.defaultSaveOptions)); | |
| 177 | + } catch (ExecutionException e) { | |
| 178 | + throw DriverThrowables.propagateCause(e); | |
| 179 | + } | |
| 164 | 180 | } |
| 165 | 181 | |
| 166 | 182 | /** |
| @@ -184,11 +200,15 @@ | ||
| 184 | 200 | * @return a query that saves {@code entity} (based on it's defined mapping). |
| 185 | 201 | */ |
| 186 | 202 | public Statement saveQuery(T entity, Option... options) { |
| 187 | - return saveQuery(entity, toMapWithDefaults(options, this.defaultSaveOptions)); | |
| 203 | + try { | |
| 204 | + return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions))); | |
| 205 | + } catch (ExecutionException e) { | |
| 206 | + throw DriverThrowables.propagateCause(e); | |
| 207 | + } | |
| 188 | 208 | } |
| 189 | 209 | |
| 190 | - private Statement saveQuery(T entity, EnumMap<Option.Type, Option> options) { | |
| 191 | - Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>(); | |
| 210 | + private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { | |
| 211 | + final Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>(); | |
| 192 | 212 | boolean saveNullFields = shouldSaveNullFields(options); |
| 193 | 213 | |
| 194 | 214 | for (ColumnMapper<T> cm : mapper.allColumns()) { |
| @@ -198,23 +218,28 @@ | ||
| 198 | 218 | } |
| 199 | 219 | } |
| 200 | 220 | |
| 201 | - BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind(); | |
| 202 | - int i = 0; | |
| 203 | - for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) { | |
| 204 | - ColumnMapper<?> mapper = entry.getKey(); | |
| 205 | - Object value = entry.getValue(); | |
| 206 | - setObject(bs, i++, value, mapper); | |
| 207 | - } | |
| 221 | + return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, values.keySet(), options), new Function<PreparedStatement, BoundStatement>() { | |
| 222 | + @Override | |
| 223 | + public BoundStatement apply(PreparedStatement input) { | |
| 224 | + BoundStatement bs = input.bind(); | |
| 225 | + int i = 0; | |
| 226 | + for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) { | |
| 227 | + ColumnMapper<?> mapper = entry.getKey(); | |
| 228 | + Object value = entry.getValue(); | |
| 229 | + setObject(bs, i++, value, mapper); | |
| 230 | + } | |
| 208 | 231 | |
| 209 | - if (mapper.writeConsistency != null) | |
| 210 | - bs.setConsistencyLevel(mapper.writeConsistency); | |
| 232 | + if (mapper.writeConsistency != null) | |
| 233 | + bs.setConsistencyLevel(mapper.writeConsistency); | |
| 211 | 234 | |
| 212 | - for (Option opt : options.values()) { | |
| 213 | - opt.checkValidFor(QueryType.SAVE, manager); | |
| 214 | - opt.addToPreparedStatement(bs, i++); | |
| 215 | - } | |
| 235 | + for (Option opt : options.values()) { | |
| 236 | + opt.checkValidFor(QueryType.SAVE, manager); | |
| 237 | + opt.addToPreparedStatement(bs, i++); | |
| 238 | + } | |
| 216 | 239 | |
| 217 | - return bs; | |
| 240 | + return bs; | |
| 241 | + } | |
| 242 | + }); | |
| 218 | 243 | } |
| 219 | 244 | |
| 220 | 245 | private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) { |
| @@ -231,18 +256,22 @@ | ||
| 231 | 256 | } |
| 232 | 257 | |
| 233 | 258 | /** |
| 234 | - * Save an entity mapped by this mapper. | |
| 259 | + * Saves an entity mapped by this mapper. | |
| 235 | 260 | * <p/> |
| 236 | 261 | * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}. |
| 237 | 262 | * |
| 238 | 263 | * @param entity the entity to save. |
| 239 | 264 | */ |
| 240 | 265 | public void save(T entity) { |
| 241 | - session().execute(saveQuery(entity)); | |
| 266 | + try { | |
| 267 | + Uninterruptibles.getUninterruptibly(saveAsync(entity)); | |
| 268 | + } catch (ExecutionException e) { | |
| 269 | + throw DriverThrowables.propagateCause(e); | |
| 270 | + } | |
| 242 | 271 | } |
| 243 | 272 | |
| 244 | 273 | /** |
| 245 | - * Save an entity mapped by this mapper and using special options for save. | |
| 274 | + * Saves an entity mapped by this mapper and using special options for save. | |
| 246 | 275 | * This method allows you to provide a suite of {@link Option} to include in |
| 247 | 276 | * the SAVE query. Options currently supported for SAVE are : |
| 248 | 277 | * <ul> |
| @@ -256,11 +285,15 @@ | ||
| 256 | 285 | * @param options the options object specified defining special options when saving. |
| 257 | 286 | */ |
| 258 | 287 | public void save(T entity, Option... options) { |
| 259 | - session().execute(saveQuery(entity, options)); | |
| 288 | + try { | |
| 289 | + Uninterruptibles.getUninterruptibly(saveAsync(entity, options)); | |
| 290 | + } catch (ExecutionException e) { | |
| 291 | + throw DriverThrowables.propagateCause(e); | |
| 292 | + } | |
| 260 | 293 | } |
| 261 | 294 | |
| 262 | 295 | /** |
| 263 | - * Save an entity mapped by this mapper asynchronously. | |
| 296 | + * Saves an entity mapped by this mapper asynchronously. | |
| 264 | 297 | * <p/> |
| 265 | 298 | * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}. |
| 266 | 299 | * |
| @@ -268,7 +301,7 @@ | ||
| 268 | 301 | * @return a future on the completion of the save operation. |
| 269 | 302 | */ |
| 270 | 303 | public ListenableFuture<Void> saveAsync(T entity) { |
| 271 | - return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP); | |
| 304 | + return submitVoidQueryAsync(saveQueryAsync(entity, this.defaultSaveOptions)); | |
| 272 | 305 | } |
| 273 | 306 | |
| 274 | 307 | /** |
| @@ -281,7 +314,17 @@ | ||
| 281 | 314 | * @return a future on the completion of the save operation. |
| 282 | 315 | */ |
| 283 | 316 | public ListenableFuture<Void> saveAsync(T entity, Option... options) { |
| 284 | - return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP); | |
| 317 | + return submitVoidQueryAsync(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions))); | |
| 318 | + } | |
| 319 | + | |
| 320 | + private ListenableFuture<Void> submitVoidQueryAsync(ListenableFuture<BoundStatement> bsFuture) { | |
| 321 | + ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { | |
| 322 | + @Override | |
| 323 | + public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { | |
| 324 | + return session().executeAsync(bs); | |
| 325 | + } | |
| 326 | + }); | |
| 327 | + return Futures.transform(rsFuture, TO_NULL); | |
| 285 | 328 | } |
| 286 | 329 | |
| 287 | 330 | /** |
| @@ -310,10 +353,17 @@ | ||
| 310 | 353 | * at least one of those values is {@code null}. |
| 311 | 354 | */ |
| 312 | 355 | public Statement getQuery(Object... objects) { |
| 356 | + try { | |
| 357 | + return Uninterruptibles.getUninterruptibly(getQueryAsync(objects)); | |
| 358 | + } catch (ExecutionException e) { | |
| 359 | + throw DriverThrowables.propagateCause(e); | |
| 360 | + } | |
| 361 | + } | |
| 362 | + | |
| 363 | + private ListenableFuture<BoundStatement> getQueryAsync(Object... objects) { | |
| 313 | 364 | // Order and duplicates matter for primary keys |
| 314 | 365 | List<Object> pks = new ArrayList<Object>(); |
| 315 | 366 | EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions); |
| 316 | - | |
| 317 | 367 | for (Object o : objects) { |
| 318 | 368 | if (o instanceof Option) { |
| 319 | 369 | Option option = (Option) o; |
| @@ -322,35 +372,38 @@ | ||
| 322 | 372 | pks.add(o); |
| 323 | 373 | } |
| 324 | 374 | } |
| 325 | - return getQuery(pks, options); | |
| 375 | + return getQueryAsync(pks, options); | |
| 326 | 376 | } |
| 327 | 377 | |
| 328 | - private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) { | |
| 329 | - | |
| 378 | + private ListenableFuture<BoundStatement> getQueryAsync(final List<Object> primaryKeys, final EnumMap<Option.Type, Option> options) { | |
| 330 | 379 | if (primaryKeys.size() != mapper.primaryKeySize()) |
| 331 | 380 | throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size())); |
| 332 | 381 | |
| 333 | - BoundStatement bs = getPreparedQuery(QueryType.GET, options).bind(); | |
| 334 | - int i = 0; | |
| 335 | - for (Object value : primaryKeys) { | |
| 336 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i); | |
| 337 | - if (value == null) { | |
| 338 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 339 | - } | |
| 340 | - setObject(bs, i++, value, column); | |
| 341 | - } | |
| 342 | - | |
| 343 | - if (mapper.readConsistency != null) | |
| 344 | - bs.setConsistencyLevel(mapper.readConsistency); | |
| 345 | - | |
| 346 | - for (Option opt : options.values()) { | |
| 347 | - opt.checkValidFor(QueryType.GET, manager); | |
| 348 | - opt.addToPreparedStatement(bs, i); | |
| 349 | - if (opt.isIncludedInQuery()) | |
| 350 | - i++; | |
| 351 | - } | |
| 382 | + return Futures.transform(getPreparedQueryAsync(QueryType.GET, options), new Function<PreparedStatement, BoundStatement>() { | |
| 383 | + @Override | |
| 384 | + public BoundStatement apply(PreparedStatement input) { | |
| 385 | + BoundStatement bs = new MapperBoundStatement(input); | |
| 386 | + int i = 0; | |
| 387 | + for (Object value : primaryKeys) { | |
| 388 | + ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i); | |
| 389 | + if (value == null) { | |
| 390 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 391 | + } | |
| 392 | + setObject(bs, i++, value, column); | |
| 393 | + } | |
| 352 | 394 | |
| 353 | - return bs; | |
| 395 | + if (mapper.readConsistency != null) | |
| 396 | + bs.setConsistencyLevel(mapper.readConsistency); | |
| 397 | + | |
| 398 | + for (Option opt : options.values()) { | |
| 399 | + opt.checkValidFor(QueryType.GET, manager); | |
| 400 | + opt.addToPreparedStatement(bs, i); | |
| 401 | + if (opt.isIncludedInQuery()) | |
| 402 | + i++; | |
| 403 | + } | |
| 404 | + return bs; | |
| 405 | + } | |
| 406 | + }); | |
| 354 | 407 | } |
| 355 | 408 | |
| 356 | 409 | /** |
| @@ -367,7 +420,11 @@ | ||
| 367 | 420 | * at least one of those values is {@code null}. |
| 368 | 421 | */ |
| 369 | 422 | public T get(Object... objects) { |
| 370 | - return mapAliased(session().execute(getQuery(objects))).one(); | |
| 423 | + try { | |
| 424 | + return Uninterruptibles.getUninterruptibly(getAsync(objects)); | |
| 425 | + } catch (ExecutionException e) { | |
| 426 | + throw DriverThrowables.propagateCause(e); | |
| 427 | + } | |
| 371 | 428 | } |
| 372 | 429 | |
| 373 | 430 | /** |
| @@ -384,8 +441,15 @@ | ||
| 384 | 441 | * the number of columns composing the PRIMARY KEY of the mapped class, or if |
| 385 | 442 | * at least one of those values is {@code null}. |
| 386 | 443 | */ |
| 387 | - public ListenableFuture<T> getAsync(Object... objects) { | |
| 388 | - return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction); | |
| 444 | + public ListenableFuture<T> getAsync(final Object... objects) { | |
| 445 | + ListenableFuture<BoundStatement> bsFuture = getQueryAsync(objects); | |
| 446 | + ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { | |
| 447 | + @Override | |
| 448 | + public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { | |
| 449 | + return session().executeAsync(bs); | |
| 450 | + } | |
| 451 | + }); | |
| 452 | + return Futures.transform(rsFuture, mapOneFunction); | |
| 389 | 453 | } |
| 390 | 454 | |
| 391 | 455 | /** |
| @@ -417,12 +481,11 @@ | ||
| 417 | 481 | * provided USING options. |
| 418 | 482 | */ |
| 419 | 483 | public Statement deleteQuery(T entity, Option... options) { |
| 420 | - List<Object> pks = new ArrayList<Object>(); | |
| 421 | - for (int i = 0; i < mapper.primaryKeySize(); i++) { | |
| 422 | - pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); | |
| 484 | + try { | |
| 485 | + return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); | |
| 486 | + } catch (ExecutionException e) { | |
| 487 | + throw DriverThrowables.propagateCause(e); | |
| 423 | 488 | } |
| 424 | - | |
| 425 | - return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions)); | |
| 426 | 489 | } |
| 427 | 490 | |
| 428 | 491 | /** |
| @@ -441,12 +504,11 @@ | ||
| 441 | 504 | * @return a query that delete {@code entity} (based on it's defined mapping). |
| 442 | 505 | */ |
| 443 | 506 | public Statement deleteQuery(T entity) { |
| 444 | - List<Object> pks = new ArrayList<Object>(); | |
| 445 | - for (int i = 0; i < mapper.primaryKeySize(); i++) { | |
| 446 | - pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); | |
| 507 | + try { | |
| 508 | + return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, defaultDeleteOptions)); | |
| 509 | + } catch (ExecutionException e) { | |
| 510 | + throw DriverThrowables.propagateCause(e); | |
| 447 | 511 | } |
| 448 | - | |
| 449 | - return deleteQuery(pks, defaultDeleteOptions); | |
| 450 | 512 | } |
| 451 | 513 | |
| 452 | 514 | /** |
| @@ -481,10 +543,25 @@ | ||
| 481 | 543 | * at least one of those values is {@code null}. |
| 482 | 544 | */ |
| 483 | 545 | public Statement deleteQuery(Object... objects) { |
| 546 | + try { | |
| 547 | + return Uninterruptibles.getUninterruptibly(deleteQueryAsync(objects)); | |
| 548 | + } catch (ExecutionException e) { | |
| 549 | + throw DriverThrowables.propagateCause(e); | |
| 550 | + } | |
| 551 | + } | |
| 552 | + | |
| 553 | + private ListenableFuture<BoundStatement> deleteQueryAsync(T entity, EnumMap<Option.Type, Option> options) { | |
| 554 | + List<Object> pks = new ArrayList<Object>(); | |
| 555 | + for (int i = 0; i < mapper.primaryKeySize(); i++) { | |
| 556 | + pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); | |
| 557 | + } | |
| 558 | + return deleteQueryAsync(pks, options); | |
| 559 | + } | |
| 560 | + | |
| 561 | + private ListenableFuture<BoundStatement> deleteQueryAsync(Object... objects) { | |
| 484 | 562 | // Order and duplicates matter for primary keys |
| 485 | 563 | List<Object> pks = new ArrayList<Object>(); |
| 486 | 564 | EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions); |
| 487 | - | |
| 488 | 565 | for (Object o : objects) { |
| 489 | 566 | if (o instanceof Option) { |
| 490 | 567 | Option option = (Option) o; |
| @@ -493,36 +570,40 @@ | ||
| 493 | 570 | pks.add(o); |
| 494 | 571 | } |
| 495 | 572 | } |
| 496 | - return deleteQuery(pks, options); | |
| 573 | + return deleteQueryAsync(pks, options); | |
| 497 | 574 | } |
| 498 | 575 | |
| 499 | - private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) { | |
| 576 | + private ListenableFuture<BoundStatement> deleteQueryAsync(final List<Object> primaryKey, final EnumMap<Option.Type, Option> options) { | |
| 500 | 577 | if (primaryKey.size() != mapper.primaryKeySize()) |
| 501 | 578 | throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size())); |
| 502 | 579 | |
| 503 | - BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind(); | |
| 504 | - | |
| 505 | - if (mapper.writeConsistency != null) | |
| 506 | - bs.setConsistencyLevel(mapper.writeConsistency); | |
| 507 | - | |
| 508 | - int i = 0; | |
| 509 | - for (Option opt : options.values()) { | |
| 510 | - opt.checkValidFor(QueryType.DEL, manager); | |
| 511 | - opt.addToPreparedStatement(bs, i); | |
| 512 | - if (opt.isIncludedInQuery()) | |
| 513 | - i++; | |
| 514 | - } | |
| 580 | + return Futures.transform(getPreparedQueryAsync(QueryType.DEL, options), new Function<PreparedStatement, BoundStatement>() { | |
| 581 | + @Override | |
| 582 | + public BoundStatement apply(PreparedStatement input) { | |
| 583 | + BoundStatement bs = input.bind(); | |
| 584 | + if (mapper.writeConsistency != null) | |
| 585 | + bs.setConsistencyLevel(mapper.writeConsistency); | |
| 586 | + | |
| 587 | + int i = 0; | |
| 588 | + for (Option opt : options.values()) { | |
| 589 | + opt.checkValidFor(QueryType.DEL, manager); | |
| 590 | + opt.addToPreparedStatement(bs, i); | |
| 591 | + if (opt.isIncludedInQuery()) | |
| 592 | + i++; | |
| 593 | + } | |
| 515 | 594 | |
| 516 | - int columnNumber = 0; | |
| 517 | - for (Object value : primaryKey) { | |
| 518 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 519 | - if (value == null) { | |
| 520 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 595 | + int columnNumber = 0; | |
| 596 | + for (Object value : primaryKey) { | |
| 597 | + ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 598 | + if (value == null) { | |
| 599 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 600 | + } | |
| 601 | + setObject(bs, i++, value, column); | |
| 602 | + columnNumber++; | |
| 603 | + } | |
| 604 | + return bs; | |
| 521 | 605 | } |
| 522 | - setObject(bs, i++, value, column); | |
| 523 | - columnNumber++; | |
| 524 | - } | |
| 525 | - return bs; | |
| 606 | + }); | |
| 526 | 607 | } |
| 527 | 608 | |
| 528 | 609 | /** |
| @@ -533,7 +614,11 @@ | ||
| 533 | 614 | * @param entity the entity to delete. |
| 534 | 615 | */ |
| 535 | 616 | public void delete(T entity) { |
| 536 | - session().execute(deleteQuery(entity)); | |
| 617 | + try { | |
| 618 | + Uninterruptibles.getUninterruptibly(deleteAsync(entity)); | |
| 619 | + } catch (ExecutionException e) { | |
| 620 | + throw DriverThrowables.propagateCause(e); | |
| 621 | + } | |
| 537 | 622 | } |
| 538 | 623 | |
| 539 | 624 | /** |
| @@ -545,7 +630,11 @@ | ||
| 545 | 630 | * @param options the options to add to the DELETE query. |
| 546 | 631 | */ |
| 547 | 632 | public void delete(T entity, Option... options) { |
| 548 | - session().execute(deleteQuery(entity, options)); | |
| 633 | + try { | |
| 634 | + Uninterruptibles.getUninterruptibly(deleteAsync(entity, options)); | |
| 635 | + } catch (ExecutionException e) { | |
| 636 | + throw DriverThrowables.propagateCause(e); | |
| 637 | + } | |
| 549 | 638 | } |
| 550 | 639 | |
| 551 | 640 | /** |
| @@ -557,7 +646,7 @@ | ||
| 557 | 646 | * @return a future on the completion of the deletion. |
| 558 | 647 | */ |
| 559 | 648 | public ListenableFuture<Void> deleteAsync(T entity) { |
| 560 | - return Futures.transform(session().executeAsync(deleteQuery(entity)), NOOP); | |
| 649 | + return submitVoidQueryAsync(deleteQueryAsync(entity, defaultDeleteOptions)); | |
| 561 | 650 | } |
| 562 | 651 | |
| 563 | 652 | /** |
| @@ -570,7 +659,7 @@ | ||
| 570 | 659 | * @return a future on the completion of the deletion. |
| 571 | 660 | */ |
| 572 | 661 | public ListenableFuture<Void> deleteAsync(T entity, Option... options) { |
| 573 | - return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP); | |
| 662 | + return submitVoidQueryAsync(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); | |
| 574 | 663 | } |
| 575 | 664 | |
| 576 | 665 | /** |
| @@ -587,7 +676,11 @@ | ||
| 587 | 676 | * at least one of those values is {@code null}. |
| 588 | 677 | */ |
| 589 | 678 | public void delete(Object... objects) { |
| 590 | - session().execute(deleteQuery(objects)); | |
| 679 | + try { | |
| 680 | + Uninterruptibles.getUninterruptibly(deleteAsync(objects)); | |
| 681 | + } catch (ExecutionException e) { | |
| 682 | + throw DriverThrowables.propagateCause(e); | |
| 683 | + } | |
| 591 | 684 | } |
| 592 | 685 | |
| 593 | 686 | /** |
| @@ -604,45 +697,47 @@ | ||
| 604 | 697 | * at least one of those values is {@code null}. |
| 605 | 698 | */ |
| 606 | 699 | public ListenableFuture<Void> deleteAsync(Object... objects) { |
| 607 | - return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP); | |
| 700 | + return submitVoidQueryAsync(deleteQueryAsync(objects)); | |
| 608 | 701 | } |
| 609 | 702 | |
| 610 | 703 | /** |
| 704 | + * Creates a query to fetch entity given its PRIMARY KEY. | |
| 705 | + * <p/> | |
| 706 | + * <p/> | |
| 707 | + * /** | |
| 611 | 708 | * Maps the rows from a {@code ResultSet} into the class this is a mapper of. |
| 612 | 709 | * <p/> |
| 613 | - * Use this method to map a result set that was not generated by the mapper (e.g. a result set coming from a | |
| 614 | - * manual query or an {@link Accessor method}. | |
| 615 | - * It expects that the result set contains all column mapped in the target class, | |
| 616 | - * and that they are not aliased. {@link Computed} fields will not be filled in mapped objects. | |
| 710 | + * If the query was user-generated (that is, passed directly to {@code session.execute()} or configured with | |
| 711 | + * {@link com.datastax.driver.mapping.annotations.Query @Query} in an | |
| 712 | + * {@link com.datastax.driver.mapping.annotations.Accessor @Accessor}-annotated interface), then only the columns | |
| 713 | + * present in the result set will be mapped to the corresponding fields, and {@link Computed} fields will not be | |
| 714 | + * populated. | |
| 715 | + * <p/> | |
| 716 | + * If the query was generated by the mapper (for example with {@link #getQuery(Object...)}), all fields will be | |
| 717 | + * mapped, as if the object came from a direct {@link #get(Object...)} call. | |
| 617 | 718 | * |
| 618 | 719 | * @param resultSet the {@code ResultSet} to map. |
| 619 | 720 | * @return the mapped result set. Note that the returned mapped result set |
| 620 | 721 | * will encapsulate {@code resultSet} and so consuming results from this |
| 621 | 722 | * returned mapped result set will consume results from {@code resultSet} |
| 622 | 723 | * and vice-versa. |
| 623 | - * @see #mapAliased(ResultSet) | |
| 624 | 724 | */ |
| 625 | 725 | public Result<T> map(ResultSet resultSet) { |
| 626 | - return new Result<T>(resultSet, mapper, protocolVersion); | |
| 726 | + boolean useAlias = !manager.isCassandraV1 && isFromMapperQuery(resultSet); | |
| 727 | + return new Result<T>(resultSet, mapper, protocolVersion, useAlias); | |
| 728 | + } | |
| 729 | + | |
| 730 | + private boolean isFromMapperQuery(ResultSet resultSet) { | |
| 731 | + return resultSet.getExecutionInfo().getStatement() instanceof MapperBoundStatement; | |
| 627 | 732 | } |
| 628 | 733 | |
| 629 | 734 | /** |
| 630 | - * Maps the rows from a {@code ResultSet} into the class this is a mapper of. | |
| 631 | - * <p/> | |
| 632 | - * Use this method to map a result set coming from the execution of the {@code Statement} returned by | |
| 633 | - * {@link #getQuery(Object...)}. {@link Computed} fields will be filled in the mapped object. | |
| 634 | - * | |
| 635 | - * @param resultSet the {@code ResultSet} to map. | |
| 636 | - * @return the mapped result set. Note that the returned mapped result set | |
| 637 | - * will encapsulate {@code resultSet} and so consuming results from this | |
| 638 | - * returned mapped result set will consume results from {@code resultSet} | |
| 639 | - * and vice-versa. | |
| 640 | - * @see #map(ResultSet) | |
| 735 | + * @deprecated you no longer need to specify whether a result set is aliased, it will be detected automatically. Use | |
| 736 | + * {@link #map(ResultSet)} instead of this method. | |
| 641 | 737 | */ |
| 738 | + @Deprecated | |
| 642 | 739 | public Result<T> mapAliased(ResultSet resultSet) { |
| 643 | - return (manager.isCassandraV1) | |
| 644 | - ? map(resultSet) // no aliases | |
| 645 | - : new Result<T>(resultSet, mapper, protocolVersion, true); | |
| 740 | + return map(resultSet); | |
| 646 | 741 | } |
| 647 | 742 | |
| 648 | 743 | /** |
added driver-mapping/src/main/java/com/datastax/driver/mapping/MapperBoundStatement.java +28 −0
| @@ -0,0 +1,28 @@ | ||
| 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.mapping; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.BoundStatement; | |
| 19 | +import com.datastax.driver.core.PreparedStatement; | |
| 20 | + | |
| 21 | +/** | |
| 22 | + * A bound statement that was generated by the object mapper. | |
| 23 | + */ | |
| 24 | +class MapperBoundStatement extends BoundStatement { | |
| 25 | + public MapperBoundStatement(PreparedStatement statement) { | |
| 26 | + super(statement); | |
| 27 | + } | |
| 28 | +} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +5 −1
| @@ -37,6 +37,7 @@ | ||
| 37 | 37 | private final ConsistencyLevel consistency; |
| 38 | 38 | private final int fetchSize; |
| 39 | 39 | private final boolean tracing; |
| 40 | + private final Boolean idempotent; | |
| 40 | 41 | |
| 41 | 42 | private Session session; |
| 42 | 43 | private PreparedStatement statement; |
| @@ -46,13 +47,14 @@ | ||
| 46 | 47 | private boolean mapOne; |
| 47 | 48 | private boolean async; |
| 48 | 49 | |
| 49 | - MethodMapper(Method method, String queryString, ParamMapper[] paramMappers, ConsistencyLevel consistency, int fetchSize, boolean enableTracing) { | |
| 50 | + MethodMapper(Method method, String queryString, ParamMapper[] paramMappers, ConsistencyLevel consistency, int fetchSize, boolean enableTracing, Boolean idempotent) { | |
| 50 | 51 | this.method = method; |
| 51 | 52 | this.queryString = queryString; |
| 52 | 53 | this.paramMappers = paramMappers; |
| 53 | 54 | this.consistency = consistency; |
| 54 | 55 | this.fetchSize = fetchSize; |
| 55 | 56 | this.tracing = enableTracing; |
| 57 | + this.idempotent = idempotent; | |
| 56 | 58 | } |
| 57 | 59 | |
| 58 | 60 | public void prepare(MappingManager manager, PreparedStatement ps) { |
| @@ -151,6 +153,8 @@ | ||
| 151 | 153 | bs.setFetchSize(fetchSize); |
| 152 | 154 | if (tracing) |
| 153 | 155 | bs.enableTracing(); |
| 156 | + if (idempotent != null) | |
| 157 | + bs.setIdempotent(idempotent); | |
| 154 | 158 | |
| 155 | 159 | if (returnStatement) |
| 156 | 160 | return bs; |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +1 −1
| @@ -78,7 +78,7 @@ | ||
| 78 | 78 | Select.Selection selection = select(); |
| 79 | 79 | for (ColumnMapper cm : mapper.allColumns()) { |
| 80 | 80 | Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED) |
| 81 | - ? ((Select.SelectionOrAlias) selection).raw(cm.getColumnName()) | |
| 81 | + ? selection.raw(cm.getColumnName()) | |
| 82 | 82 | : selection.column(cm.getColumnName()); |
| 83 | 83 | |
| 84 | 84 | if (cm.getAlias() == null) { |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +2 −2
| @@ -60,7 +60,7 @@ | ||
| 60 | 60 | } |
| 61 | 61 | |
| 62 | 62 | @Override |
| 63 | - public Object getValue(T entity) { | |
| 63 | + Object getValue(T entity) { | |
| 64 | 64 | try { |
| 65 | 65 | return readMethod.invoke(entity); |
| 66 | 66 | } catch (IllegalArgumentException e) { |
| @@ -71,7 +71,7 @@ | ||
| 71 | 71 | } |
| 72 | 72 | |
| 73 | 73 | @Override |
| 74 | - public void setValue(Object entity, Object value) { | |
| 74 | + void setValue(Object entity, Object value) { | |
| 75 | 75 | try { |
| 76 | 76 | writeMethod.invoke(entity, value); |
| 77 | 77 | } catch (IllegalArgumentException e) { |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +1 −5
| @@ -29,10 +29,6 @@ | ||
| 29 | 29 | private final ProtocolVersion protocolVersion; |
| 30 | 30 | private final boolean useAlias; |
| 31 | 31 | |
| 32 | - Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion) { | |
| 33 | - this(rs, mapper, protocolVersion, false); | |
| 34 | - } | |
| 35 | - | |
| 36 | 32 | Result(ResultSet rs, EntityMapper<T> mapper, ProtocolVersion protocolVersion, boolean useAlias) { |
| 37 | 33 | this.rs = rs; |
| 38 | 34 | this.mapper = mapper; |
| @@ -120,7 +116,7 @@ | ||
| 120 | 116 | * this mapped result set. |
| 121 | 117 | */ |
| 122 | 118 | @Override |
| 123 | - public Iterator<T> iterator() { | |
| 119 | + public Iterator<T> iterator() { | |
| 124 | 120 | return new Iterator<T>() { |
| 125 | 121 | private final Iterator<Row> rowIterator = rs.iterator(); |
| 126 | 122 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/QueryParameters.java +25 −0
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.mapping.annotations; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.Configuration; |
| 19 | +import com.datastax.driver.core.QueryOptions; | |
| 19 | 20 | |
| 20 | 21 | import java.lang.annotation.ElementType; |
| 21 | 22 | import java.lang.annotation.Retention; |
| @@ -53,4 +54,28 @@ | ||
| 53 | 54 | * @return whether tracing should be enabled for this operation. |
| 54 | 55 | */ |
| 55 | 56 | boolean tracing() default false; |
| 57 | + | |
| 58 | + /** | |
| 59 | + * Whether the operation is idempotent or not. | |
| 60 | + * <p/> | |
| 61 | + * When this attribute is set to {@code true} the operation is assumed idempotent; | |
| 62 | + * when set to {@code false}, it is assumed that it is not. | |
| 63 | + * <p/> | |
| 64 | + * If a value of {@code true} or {@code false} is provided, | |
| 65 | + * the underlying {@link com.datastax.driver.core.Statement} | |
| 66 | + * will have its {@link com.datastax.driver.core.Statement#setIdempotent(boolean) idempotent flag} | |
| 67 | + * set accordingly. | |
| 68 | + * <p/> | |
| 69 | + * When this attribute is set to its default | |
| 70 | + * (an empty array), it means that the statement's idempotent flag | |
| 71 | + * will not be set, and its idempotence will be inferred | |
| 72 | + * from {@link QueryOptions#getDefaultIdempotence()}. | |
| 73 | + * <p/> | |
| 74 | + * This attribute is declared as a boolean array to allow | |
| 75 | + * for "unset" values, but it can only contain at most | |
| 76 | + * one element. | |
| 77 | + * | |
| 78 | + * @return {@code true} if the operation is idempotent, {@code false} otherwise. | |
| 79 | + */ | |
| 80 | + boolean[] idempotent() default {}; | |
| 56 | 81 | } |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +25 −0
| @@ -17,10 +17,14 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CCMTestsSupport; |
| 19 | 19 | import com.datastax.driver.core.Row; |
| 20 | +import com.datastax.driver.core.exceptions.CodecNotFoundException; | |
| 20 | 21 | import com.datastax.driver.core.utils.CassandraVersion; |
| 21 | 22 | import com.datastax.driver.mapping.annotations.*; |
| 23 | +import com.google.common.collect.Lists; | |
| 22 | 24 | import org.testng.annotations.Test; |
| 23 | 25 | |
| 26 | +import java.util.List; | |
| 27 | + | |
| 24 | 28 | import static org.assertj.core.api.Assertions.assertThat; |
| 25 | 29 | |
| 26 | 30 | @SuppressWarnings("unused") |
| @@ -75,6 +79,19 @@ | ||
| 75 | 79 | .createAccessor(UserPhoneAccessor_TooManyParams.class); |
| 76 | 80 | } |
| 77 | 81 | |
| 82 | + /** | |
| 83 | + * Ensures that a wrong parameter type is detected when | |
| 84 | + * the accessor is called with a wrong data type. | |
| 85 | + * | |
| 86 | + * @jira_ticket JAVA-974 | |
| 87 | + */ | |
| 88 | + @Test(groups = "short", expectedExceptions = CodecNotFoundException.class) | |
| 89 | + public void should_fail_if_wrong_parameter_type() { | |
| 90 | + UserPhoneAccessor_WrongParameterTypes accessor = new MappingManager(session()) | |
| 91 | + .createAccessor(UserPhoneAccessor_WrongParameterTypes.class); | |
| 92 | + accessor.findUsersBykeys(Lists.newArrayList(1, 2, 3)); | |
| 93 | + } | |
| 94 | + | |
| 78 | 95 | private void assertPhonesEqual(int key, String home, String work) { |
| 79 | 96 | Row row = session().execute("select * from user where key = " + key).one(); |
| 80 | 97 | assertThat(row.getString("home_phone")).isEqualTo(home); |
| @@ -188,4 +205,12 @@ | ||
| 188 | 205 | this.gender = val; |
| 189 | 206 | } |
| 190 | 207 | } |
| 208 | + | |
| 209 | + @Accessor | |
| 210 | + public interface UserPhoneAccessor_WrongParameterTypes { | |
| 211 | + @Query("select * from user where key IN (?)") | |
| 212 | + // WRONG, should be "where key IN ?" | |
| 213 | + void findUsersBykeys(List<Integer> keys); | |
| 214 | + } | |
| 215 | + | |
| 191 | 216 | } |
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAsyncTest.java +186 −0
| @@ -0,0 +1,186 @@ | ||
| 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.mapping; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | +import com.datastax.driver.core.Cluster; | |
| 20 | +import com.datastax.driver.core.Session; | |
| 21 | +import com.datastax.driver.core.utils.MoreFutures.SuccessCallback; | |
| 22 | +import com.datastax.driver.core.utils.UUIDs; | |
| 23 | +import com.datastax.driver.mapping.annotations.Column; | |
| 24 | +import com.datastax.driver.mapping.annotations.PartitionKey; | |
| 25 | +import com.datastax.driver.mapping.annotations.Table; | |
| 26 | +import com.google.common.base.Function; | |
| 27 | +import com.google.common.base.Objects; | |
| 28 | +import com.google.common.util.concurrent.Futures; | |
| 29 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 30 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 31 | +import org.testng.annotations.Test; | |
| 32 | + | |
| 33 | +import java.util.UUID; | |
| 34 | +import java.util.concurrent.CountDownLatch; | |
| 35 | + | |
| 36 | +import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; | |
| 37 | +import static java.util.concurrent.TimeUnit.MINUTES; | |
| 38 | +import static org.testng.Assert.fail; | |
| 39 | + | |
| 40 | +/** | |
| 41 | + * Basic tests for the mapping module. | |
| 42 | + */ | |
| 43 | +@SuppressWarnings("unused") | |
| 44 | +public class MapperAsyncTest extends CCMTestsSupport { | |
| 45 | + | |
| 46 | + private static final String KEYSPACE = "mapper_async_test_ks"; | |
| 47 | + | |
| 48 | + private final User paul = new User("Paul", "paul@yahoo.com"); | |
| 49 | + | |
| 50 | + @Override | |
| 51 | + public void onTestContextInitialized() { | |
| 52 | + execute( | |
| 53 | + String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, KEYSPACE, 1), | |
| 54 | + String.format("CREATE TABLE %s.users (user_id uuid PRIMARY KEY, name text, email text)", KEYSPACE) | |
| 55 | + ); | |
| 56 | + } | |
| 57 | + | |
| 58 | + /** | |
| 59 | + * Validates that when using save, get and deleteAsync using the same executor as the caller that the driver | |
| 60 | + * does not block indefinitely in a netty worker thread. | |
| 61 | + * | |
| 62 | + * @jira_ticket JAVA-1070 | |
| 63 | + * @test_category queries:async | |
| 64 | + * @test_category object_mapper | |
| 65 | + */ | |
| 66 | + @Test(groups = "short") | |
| 67 | + public void should_get_query_async_without_blocking() { | |
| 68 | + | |
| 69 | + final CountDownLatch latch = new CountDownLatch(1); | |
| 70 | + | |
| 71 | + // create a second cluster to perform everything asynchronously, | |
| 72 | + // including session initialization | |
| 73 | + Cluster cluster2 = register( | |
| 74 | + createClusterBuilderNoDebouncing() | |
| 75 | + .addContactPoints(getContactPoints()) | |
| 76 | + .withPort(ccm().getBinaryPort()) | |
| 77 | + .build()); | |
| 78 | + | |
| 79 | + ListenableFuture<MappingManager> mappingManagerFuture = Futures.transform( | |
| 80 | + cluster2.connectAsync(), | |
| 81 | + new Function<Session, MappingManager>() { | |
| 82 | + @Override | |
| 83 | + public MappingManager apply(Session session) { | |
| 84 | + return new MappingManager(session); | |
| 85 | + } | |
| 86 | + }); | |
| 87 | + | |
| 88 | + Futures.addCallback(mappingManagerFuture, new SuccessCallback<MappingManager>() { | |
| 89 | + | |
| 90 | + @Override | |
| 91 | + public void onSuccess(MappingManager manager) { | |
| 92 | + | |
| 93 | + final Mapper<User> mapper = manager.mapper(User.class); | |
| 94 | + ListenableFuture<Void> saveFuture = mapper.saveAsync(paul); | |
| 95 | + Futures.addCallback(saveFuture, new SuccessCallback<Void>() { | |
| 96 | + | |
| 97 | + @Override | |
| 98 | + public void onSuccess(Void result) { | |
| 99 | + ListenableFuture<User> getFuture = mapper.getAsync(paul.getUserId()); | |
| 100 | + Futures.addCallback(getFuture, new SuccessCallback<User>() { | |
| 101 | + | |
| 102 | + @Override | |
| 103 | + public void onSuccess(User paul) { | |
| 104 | + | |
| 105 | + Futures.addCallback(mapper.deleteAsync(paul), new SuccessCallback<Void>() { | |
| 106 | + @Override | |
| 107 | + public void onSuccess(Void result) { | |
| 108 | + latch.countDown(); | |
| 109 | + } | |
| 110 | + }); | |
| 111 | + } | |
| 112 | + }); | |
| 113 | + } | |
| 114 | + }); | |
| 115 | + } | |
| 116 | + }); | |
| 117 | + | |
| 118 | + try { | |
| 119 | + Uninterruptibles.awaitUninterruptibly(latch, 5, MINUTES); | |
| 120 | + } catch (Exception e) { | |
| 121 | + fail("Operation did not complete normally within 5 minutes"); | |
| 122 | + } | |
| 123 | + } | |
| 124 | + | |
| 125 | + @Table(name = "users", keyspace = KEYSPACE) | |
| 126 | + public static class User { | |
| 127 | + | |
| 128 | + @PartitionKey | |
| 129 | + @Column(name = "user_id") | |
| 130 | + private UUID userId; | |
| 131 | + | |
| 132 | + private String name; | |
| 133 | + | |
| 134 | + private String email; | |
| 135 | + | |
| 136 | + public User() { | |
| 137 | + } | |
| 138 | + | |
| 139 | + public User(String name, String email) { | |
| 140 | + this.userId = UUIDs.random(); | |
| 141 | + this.name = name; | |
| 142 | + this.email = email; | |
| 143 | + } | |
| 144 | + | |
| 145 | + public UUID getUserId() { | |
| 146 | + return userId; | |
| 147 | + } | |
| 148 | + | |
| 149 | + public void setUserId(UUID userId) { | |
| 150 | + this.userId = userId; | |
| 151 | + } | |
| 152 | + | |
| 153 | + public String getName() { | |
| 154 | + return name; | |
| 155 | + } | |
| 156 | + | |
| 157 | + public void setName(String name) { | |
| 158 | + this.name = name; | |
| 159 | + } | |
| 160 | + | |
| 161 | + public String getEmail() { | |
| 162 | + return email; | |
| 163 | + } | |
| 164 | + | |
| 165 | + public void setEmail(String email) { | |
| 166 | + this.email = email; | |
| 167 | + } | |
| 168 | + | |
| 169 | + @Override | |
| 170 | + public boolean equals(Object other) { | |
| 171 | + if (other == null || other.getClass() != this.getClass()) | |
| 172 | + return false; | |
| 173 | + | |
| 174 | + User that = (User) other; | |
| 175 | + return Objects.equal(userId, that.userId) | |
| 176 | + && Objects.equal(name, that.name) | |
| 177 | + && Objects.equal(email, that.email); | |
| 178 | + } | |
| 179 | + | |
| 180 | + @Override | |
| 181 | + public int hashCode() { | |
| 182 | + return Objects.hashCode(userId, name, email); | |
| 183 | + } | |
| 184 | + } | |
| 185 | + | |
| 186 | +} |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +1 −1
| @@ -103,7 +103,7 @@ | ||
| 103 | 103 | getQuery.setConsistencyLevel(ConsistencyLevel.QUORUM); |
| 104 | 104 | ResultSet rs = session().execute(getQuery); |
| 105 | 105 | |
| 106 | - Result<User> result = userMapper.mapAliased(rs); | |
| 106 | + Result<User> result = userMapper.map(rs); | |
| 107 | 107 | User user = result.one(); |
| 108 | 108 | |
| 109 | 109 | assertThat(user.getLogin()).isEqualTo("testlogin"); |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +1 −1
| @@ -83,7 +83,7 @@ | ||
| 83 | 83 | |
| 84 | 84 | ResultSet rs = session().execute(bs); |
| 85 | 85 | assertThat(rs.getExecutionInfo().getQueryTrace()).isNotNull(); |
| 86 | - User us = mapper.mapAliased(rs).one(); | |
| 86 | + User us = mapper.map(rs).one(); | |
| 87 | 87 | assertThat(us.getV()).isEqualTo("toget"); |
| 88 | 88 | |
| 89 | 89 | mapper.getQuery(45, Option.timestamp(1337)); |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +91 −7
| @@ -145,17 +145,18 @@ | ||
| 145 | 145 | @Table(name = "posts") |
| 146 | 146 | public static class Post { |
| 147 | 147 | |
| 148 | - @PartitionKey | |
| 149 | - @Column(name = "user_id") | |
| 150 | - private UUID userId; | |
| 148 | + private String title; | |
| 149 | + private String content; | |
| 150 | + private InetAddress device; | |
| 151 | 151 | |
| 152 | 152 | @ClusteringColumn |
| 153 | 153 | @Column(name = "post_id") |
| 154 | 154 | private UUID postId; |
| 155 | 155 | |
| 156 | - private String title; | |
| 157 | - private String content; | |
| 158 | - private InetAddress device; | |
| 156 | + @PartitionKey | |
| 157 | + @Column(name = "user_id") | |
| 158 | + private UUID userId; | |
| 159 | + | |
| 159 | 160 | |
| 160 | 161 | private Set<String> tags; |
| 161 | 162 | |
| @@ -278,6 +279,17 @@ | ||
| 278 | 279 | |
| 279 | 280 | @Query("SELECT * FROM posts") |
| 280 | 281 | Result<Post> getAll(); |
| 282 | + | |
| 283 | + @Query("SELECT * FROM posts") | |
| 284 | + @QueryParameters(idempotent = true) | |
| 285 | + Statement getAllAsStatementIdempotent(); | |
| 286 | + | |
| 287 | + @Query("SELECT * FROM posts") | |
| 288 | + @QueryParameters(idempotent = false) | |
| 289 | + Statement getAllAsStatementNonIdempotent(); | |
| 290 | + | |
| 291 | + @Query("SELECT * FROM posts") | |
| 292 | + Statement getAllAsStatement(); | |
| 281 | 293 | } |
| 282 | 294 | |
| 283 | 295 | @Test(groups = "short") |
| @@ -395,7 +407,6 @@ | ||
| 395 | 407 | session().execute("delete from posts where user_id = " + u1.getUserId()); |
| 396 | 408 | } |
| 397 | 409 | |
| 398 | - | |
| 399 | 410 | @Test(groups = "short") |
| 400 | 411 | public void should_return_table_metadata() throws Exception { |
| 401 | 412 | MappingManager manager = new MappingManager(session()); |
| @@ -419,4 +430,77 @@ | ||
| 419 | 430 | newSession.execute("USE " + keyspace); |
| 420 | 431 | assertThat(newSession.getState().getConnectedHosts()).hasSize(1); |
| 421 | 432 | } |
| 433 | + | |
| 434 | + /** | |
| 435 | + * Ensures that if an accessor method has a {@link QueryParameters} annotation with | |
| 436 | + * {@link QueryParameters#idempotent()} as {@code true} that the {@link Statement} it generates returns | |
| 437 | + * {@code true} for {@link Statement#isIdempotent()}. | |
| 438 | + * | |
| 439 | + * @jira_ticket JAVA-923 | |
| 440 | + * @test_category object_mapper | |
| 441 | + */ | |
| 442 | + @Test(groups = "short") | |
| 443 | + @CassandraVersion(major = 2.0) | |
| 444 | + public void should_flag_statement_as_idempotent() { | |
| 445 | + MappingManager manager = new MappingManager(session()); | |
| 446 | + PostAccessor post = manager.createAccessor(PostAccessor.class); | |
| 447 | + Statement stmt = post.getAllAsStatementIdempotent(); | |
| 448 | + assertThat(stmt.isIdempotent()).isEqualTo(true); | |
| 449 | + } | |
| 450 | + | |
| 451 | + /** | |
| 452 | + * Ensures that if an accessor method has a {@link QueryParameters} annotation with | |
| 453 | + * {@link QueryParameters#idempotent()} as {@code false} that the {@link Statement} it generates returns | |
| 454 | + * {@code false} for {@link Statement#isIdempotent()}. | |
| 455 | + * | |
| 456 | + * @jira_ticket JAVA-923 | |
| 457 | + * @test_category object_mapper | |
| 458 | + */ | |
| 459 | + @Test(groups = "short") | |
| 460 | + @CassandraVersion(major = 2.0) | |
| 461 | + public void should_flag_statement_as_non_idempotent() { | |
| 462 | + MappingManager manager = new MappingManager(session()); | |
| 463 | + PostAccessor post = manager.createAccessor(PostAccessor.class); | |
| 464 | + Statement stmt = post.getAllAsStatementNonIdempotent(); | |
| 465 | + assertThat(stmt.isIdempotent()).isEqualTo(false); | |
| 466 | + } | |
| 467 | + | |
| 468 | + /** | |
| 469 | + * Ensures that if an accessor method lacks a {@link QueryParameters} annotation with | |
| 470 | + * {@link QueryParameters#idempotent()} set that the {@link Statement} it generates returns | |
| 471 | + * {@code null} for {@link Statement#isIdempotent()}. | |
| 472 | + * | |
| 473 | + * @jira_ticket JAVA-923 | |
| 474 | + * @test_category object_mapper | |
| 475 | + */ | |
| 476 | + @Test(groups = "short") | |
| 477 | + @CassandraVersion(major = 2.0) | |
| 478 | + public void should_flag_statement_with_null_idempotence() { | |
| 479 | + MappingManager manager = new MappingManager(session()); | |
| 480 | + PostAccessor post = manager.createAccessor(PostAccessor.class); | |
| 481 | + Statement stmt = post.getAllAsStatement(); | |
| 482 | + assertThat(stmt.isIdempotent()).isNull(); | |
| 483 | + } | |
| 484 | + | |
| 485 | + /** | |
| 486 | + * Ensures that all statements generated by the mapper are | |
| 487 | + * flagged as idempotent. | |
| 488 | + * | |
| 489 | + * @jira_ticket JAVA-923 | |
| 490 | + * @test_category object_mapper | |
| 491 | + */ | |
| 492 | + @Test(groups = "short") | |
| 493 | + @CassandraVersion(major = 2.0) | |
| 494 | + public void should_flag_all_mapper_generated_statements_as_idempotent() { | |
| 495 | + MappingManager manager = new MappingManager(session()); | |
| 496 | + Mapper<User> mapper = manager.mapper(User.class); | |
| 497 | + User u = new User("Paul", "paul@yahoo.com"); | |
| 498 | + Statement saveQuery = mapper.saveQuery(u); | |
| 499 | + assertThat(saveQuery.isIdempotent()).isTrue(); | |
| 500 | + Statement getQuery = mapper.getQuery(u.getUserId()); | |
| 501 | + assertThat(saveQuery.isIdempotent()).isTrue(); | |
| 502 | + Statement deleteQuery = mapper.deleteQuery(u.getUserId()); | |
| 503 | + assertThat(saveQuery.isIdempotent()).isTrue(); | |
| 504 | + } | |
| 505 | + | |
| 422 | 506 | } |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTCollectionsTest.java +2 −0
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CCMTestsSupport; |
| 19 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 19 | 20 | import com.datastax.driver.mapping.annotations.*; |
| 20 | 21 | import com.google.common.base.Objects; |
| 21 | 22 | import com.google.common.collect.ImmutableMap; |
| @@ -33,6 +34,7 @@ | ||
| 33 | 34 | * Tests mapping of collections of UDTs. |
| 34 | 35 | */ |
| 35 | 36 | @SuppressWarnings("unused") |
| 37 | +@CassandraVersion(major = 2.1) | |
| 36 | 38 | public class MapperUDTCollectionsTest extends CCMTestsSupport { |
| 37 | 39 | |
| 38 | 40 | @Override |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +2 −0
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | 19 | import com.datastax.driver.core.exceptions.CodecNotFoundException; |
| 20 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 20 | 21 | import com.datastax.driver.core.utils.UUIDs; |
| 21 | 22 | import com.datastax.driver.mapping.annotations.*; |
| 22 | 23 | import com.google.common.base.Objects; |
| @@ -32,6 +33,7 @@ | ||
| 32 | 33 | import static org.testng.Assert.*; |
| 33 | 34 | |
| 34 | 35 | @SuppressWarnings("unused") |
| 36 | +@CassandraVersion(major = 2.1) | |
| 35 | 37 | public class MapperUDTTest extends CCMTestsSupport { |
| 36 | 38 | |
| 37 | 39 | @Override |
added driver-tests/osgi/README.md +34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +# OSGi Example | |
| 2 | + | |
| 3 | +A simple test for the Java Driver in an OSGi environment. | |
| 4 | + | |
| 5 | +`MailboxService` is an OSGi service that uses Cassandra to | |
| 6 | +store messages that can be retrieved by email address. | |
| 7 | + | |
| 8 | +## Usage | |
| 9 | + | |
| 10 | +To build the bundle and run tests, execute the following Maven goal: | |
| 11 | + | |
| 12 | + mvn verify -P short | |
| 13 | + | |
| 14 | +The "short" profile needs to be activated since the tests run under | |
| 15 | +this group. | |
| 16 | + | |
| 17 | +Note: tests will try to load the jars of 3 dependent modules: | |
| 18 | +`driver-core`, `driver-mapping` and `driver-extras`. | |
| 19 | +For this to succeed, you need to run `mvn package` | |
| 20 | +first for these modules and make sure the jars are present | |
| 21 | +in each module's `target/` subdirectory. | |
| 22 | + | |
| 23 | +Once `mvn verify` completes, the bundle jar will be present in the `target/` directory. | |
| 24 | + | |
| 25 | +The project includes integration tests that verify the service can | |
| 26 | +be activated and used in an OSGi container. It also verifies that | |
| 27 | +the Java driver can be used in an OSGi container in the following | |
| 28 | +configurations: | |
| 29 | + | |
| 30 | +1. Default (default classifier with all dependencies) | |
| 31 | +2. Netty-Shaded (shaded classifier with all depedencies w/o Netty) | |
| 32 | +5. Guava 17 | |
| 33 | +6. Guava 18 | |
| 34 | +7. Guava 19 |
added driver-tests/osgi/pom.xml +282 −0
| @@ -0,0 +1,282 @@ | ||
| 1 | +<!-- | |
| 2 | + | |
| 3 | + Copyright (C) 2012-2015 DataStax Inc. | |
| 4 | + | |
| 5 | + Licensed under the Apache License, Version 2.0 (the "License"); | |
| 6 | + you may not use this file except in compliance with the License. | |
| 7 | + You may obtain a copy of the License at | |
| 8 | + | |
| 9 | + http://www.apache.org/licenses/LICENSE-2.0 | |
| 10 | + | |
| 11 | + Unless required by applicable law or agreed to in writing, software | |
| 12 | + distributed under the License is distributed on an "AS IS" BASIS, | |
| 13 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 14 | + See the License for the specific language governing permissions and | |
| 15 | + limitations under the License. | |
| 16 | + | |
| 17 | +--> | |
| 18 | +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 19 | + <modelVersion>4.0.0</modelVersion> | |
| 20 | + <parent> | |
| 21 | + <groupId>com.datastax.cassandra</groupId> | |
| 22 | + <artifactId>cassandra-driver-tests-parent</artifactId> | |
| 23 | + <version>3.0.1-SNAPSHOT</version> | |
| 24 | + </parent> | |
| 25 | + | |
| 26 | + <artifactId>cassandra-driver-tests-osgi</artifactId> | |
| 27 | + <packaging>bundle</packaging> | |
| 28 | + <name>DataStax Java Driver for Apache Cassandra Tests - OSGi</name> | |
| 29 | + <description>A test for the DataStax Java Driver in an OSGi container.</description> | |
| 30 | + <url>https://github.com/datastax/java-driver</url> | |
| 31 | + | |
| 32 | + <properties> | |
| 33 | + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> | |
| 34 | + <felix.version>4.6.0</felix.version> | |
| 35 | + <!-- more recent version require JDK7+ --> | |
| 36 | + <pax-exam.version>3.6.0</pax-exam.version> | |
| 37 | + <logback.version>1.1.3</logback.version> | |
| 38 | + <test.groups>none</test.groups> | |
| 39 | + <!-- | |
| 40 | + Skip tests by default, short or long profile is required to run tests in this module | |
| 41 | + since pax-exam will throw exception if it encounters a | |
| 42 | + test with no matching methods. | |
| 43 | + --> | |
| 44 | + <test.skip>true</test.skip> | |
| 45 | + <main.basedir>${project.parent.parent.basedir}</main.basedir> | |
| 46 | + </properties> | |
| 47 | + | |
| 48 | + <dependencies> | |
| 49 | + | |
| 50 | + <dependency> | |
| 51 | + <groupId>com.datastax.cassandra</groupId> | |
| 52 | + <artifactId>cassandra-driver-core</artifactId> | |
| 53 | + <version>${project.parent.version}</version> | |
| 54 | + </dependency> | |
| 55 | + | |
| 56 | + <dependency> | |
| 57 | + <groupId>com.datastax.cassandra</groupId> | |
| 58 | + <artifactId>cassandra-driver-mapping</artifactId> | |
| 59 | + <version>${project.parent.version}</version> | |
| 60 | + </dependency> | |
| 61 | + | |
| 62 | + <dependency> | |
| 63 | + <groupId>com.datastax.cassandra</groupId> | |
| 64 | + <artifactId>cassandra-driver-extras</artifactId> | |
| 65 | + <version>${project.parent.version}</version> | |
| 66 | + </dependency> | |
| 67 | + | |
| 68 | + <dependency> | |
| 69 | + <groupId>org.apache.felix</groupId> | |
| 70 | + <artifactId>org.apache.felix.framework</artifactId> | |
| 71 | + <version>${felix.version}</version> | |
| 72 | + </dependency> | |
| 73 | + | |
| 74 | + <dependency> | |
| 75 | + <groupId>com.datastax.cassandra</groupId> | |
| 76 | + <artifactId>cassandra-driver-core</artifactId> | |
| 77 | + <version>${project.parent.version}</version> | |
| 78 | + <type>test-jar</type> | |
| 79 | + <scope>test</scope> | |
| 80 | + </dependency> | |
| 81 | + | |
| 82 | + <dependency> | |
| 83 | + <groupId>org.ops4j.pax.exam</groupId> | |
| 84 | + <artifactId>pax-exam</artifactId> | |
| 85 | + <version>${pax-exam.version}</version> | |
| 86 | + <scope>test</scope> | |
| 87 | + </dependency> | |
| 88 | + | |
| 89 | + <dependency> | |
| 90 | + <groupId>org.ops4j.pax.exam</groupId> | |
| 91 | + <artifactId>pax-exam-testng</artifactId> | |
| 92 | + <version>${pax-exam.version}</version> | |
| 93 | + <scope>test</scope> | |
| 94 | + </dependency> | |
| 95 | + | |
| 96 | + <dependency> | |
| 97 | + <groupId>org.ops4j.pax.exam</groupId> | |
| 98 | + <artifactId>pax-exam-container-native</artifactId> | |
| 99 | + <version>${pax-exam.version}</version> | |
| 100 | + <scope>test</scope> | |
| 101 | + </dependency> | |
| 102 | + | |
| 103 | + <dependency> | |
| 104 | + <groupId>org.ops4j.pax.exam</groupId> | |
| 105 | + <artifactId>pax-exam-link-mvn</artifactId> | |
| 106 | + <version>${pax-exam.version}</version> | |
| 107 | + <scope>test</scope> | |
| 108 | + </dependency> | |
| 109 | + | |
| 110 | + <dependency> | |
| 111 | + <groupId>javax.transaction</groupId> | |
| 112 | + <artifactId>jta</artifactId> | |
| 113 | + <version>1.1</version> | |
| 114 | + <scope>test</scope> | |
| 115 | + </dependency> | |
| 116 | + | |
| 117 | + <dependency> | |
| 118 | + <groupId>com.jcabi</groupId> | |
| 119 | + <artifactId>jcabi-manifests</artifactId> | |
| 120 | + <version>1.1</version> | |
| 121 | + <scope>test</scope> | |
| 122 | + </dependency> | |
| 123 | + | |
| 124 | + <dependency> | |
| 125 | + <groupId>javax.servlet</groupId> | |
| 126 | + <artifactId>javax.servlet-api</artifactId> | |
| 127 | + <version>3.1.0</version> | |
| 128 | + <scope>test</scope> | |
| 129 | + </dependency> | |
| 130 | + | |
| 131 | + <dependency> | |
| 132 | + <groupId>javax.inject</groupId> | |
| 133 | + <artifactId>javax.inject</artifactId> | |
| 134 | + <version>1</version> | |
| 135 | + <scope>test</scope> | |
| 136 | + </dependency> | |
| 137 | + | |
| 138 | + <dependency> | |
| 139 | + <groupId>org.apache.commons</groupId> | |
| 140 | + <artifactId>commons-exec</artifactId> | |
| 141 | + <version>1.3</version> | |
| 142 | + <scope>test</scope> | |
| 143 | + </dependency> | |
| 144 | + | |
| 145 | + <dependency> | |
| 146 | + <groupId>ch.qos.logback</groupId> | |
| 147 | + <artifactId>logback-classic</artifactId> | |
| 148 | + <version>${logback.version}</version> | |
| 149 | + </dependency> | |
| 150 | + | |
| 151 | + <dependency> | |
| 152 | + <groupId>ch.qos.logback</groupId> | |
| 153 | + <artifactId>logback-core</artifactId> | |
| 154 | + <version>${logback.version}</version> | |
| 155 | + </dependency> | |
| 156 | + | |
| 157 | + </dependencies> | |
| 158 | + | |
| 159 | + <build> | |
| 160 | + | |
| 161 | + <plugins> | |
| 162 | + | |
| 163 | + <!-- | |
| 164 | + this project has no unit tests; | |
| 165 | + this plugin is declared just so that Maven properties | |
| 166 | + get automatically passed to tests run with IntelliJ | |
| 167 | + --> | |
| 168 | + <plugin> | |
| 169 | + <groupId>org.apache.maven.plugins</groupId> | |
| 170 | + <artifactId>maven-surefire-plugin</artifactId> | |
| 171 | + <version>2.18.1</version> | |
| 172 | + <configuration> | |
| 173 | + <skip>true</skip> | |
| 174 | + <systemPropertyVariables> | |
| 175 | + <cassandra.version>${cassandra.version}</cassandra.version> | |
| 176 | + <ipprefix>${ipprefix}</ipprefix> | |
| 177 | + </systemPropertyVariables> | |
| 178 | + </configuration> | |
| 179 | + </plugin> | |
| 180 | + | |
| 181 | + <plugin> | |
| 182 | + <groupId>org.apache.maven.plugins</groupId> | |
| 183 | + <artifactId>maven-failsafe-plugin</artifactId> | |
| 184 | + <version>2.18.1</version> | |
| 185 | + <configuration> | |
| 186 | + <skip>${test.skip}</skip> | |
| 187 | + <groups>${test.groups}</groups> | |
| 188 | + <systemPropertyVariables> | |
| 189 | + <cassandra.version>${cassandra.version}</cassandra.version> | |
| 190 | + <ipprefix>${ipprefix}</ipprefix> | |
| 191 | + </systemPropertyVariables> | |
| 192 | + </configuration> | |
| 193 | + <executions> | |
| 194 | + <execution> | |
| 195 | + <id>default</id> | |
| 196 | + <goals> | |
| 197 | + <goal>integration-test</goal> | |
| 198 | + <goal>verify</goal> | |
| 199 | + </goals> | |
| 200 | + </execution> | |
| 201 | + </executions> | |
| 202 | + </plugin> | |
| 203 | + | |
| 204 | + <plugin> | |
| 205 | + <groupId>org.apache.felix</groupId> | |
| 206 | + <artifactId>maven-bundle-plugin</artifactId> | |
| 207 | + <extensions>true</extensions> | |
| 208 | + <version>2.4.0</version> | |
| 209 | + <configuration> | |
| 210 | + <instructions> | |
| 211 | + <Bundle-SymbolicName>com.datastax.driver.osgi</Bundle-SymbolicName> | |
| 212 | + <Bundle-Version>${project.version}</Bundle-Version> | |
| 213 | + <Export-Package>com.datastax.driver.osgi.api,!com.datastax.driver.osgi.impl</Export-Package> | |
| 214 | + <Bundle-Activator>com.datastax.driver.osgi.impl.Activator</Bundle-Activator> | |
| 215 | + <_include>-osgi.bnd</_include> | |
| 216 | + <Import-Package><![CDATA[com.google.common*;version="[16.0.1,20)",*]]></Import-Package> | |
| 217 | + </instructions> | |
| 218 | + <supportedProjectTypes> | |
| 219 | + <supportedProjectType>jar</supportedProjectType> | |
| 220 | + <supportedProjectType>bundle</supportedProjectType> | |
| 221 | + <supportedProjectType>pom</supportedProjectType> | |
| 222 | + </supportedProjectTypes> | |
| 223 | + </configuration> | |
| 224 | + <executions> | |
| 225 | + <execution> | |
| 226 | + <id>bundle-manifest</id> | |
| 227 | + <phase>compile</phase> | |
| 228 | + <goals> | |
| 229 | + <goal>manifest</goal> | |
| 230 | + </goals> | |
| 231 | + </execution> | |
| 232 | + </executions> | |
| 233 | + </plugin> | |
| 234 | + | |
| 235 | + </plugins> | |
| 236 | + | |
| 237 | + </build> | |
| 238 | + | |
| 239 | + <profiles> | |
| 240 | + | |
| 241 | + <profile> | |
| 242 | + <id>short</id> | |
| 243 | + <properties> | |
| 244 | + <test.groups>unit,short</test.groups> | |
| 245 | + <test.skip>false</test.skip> | |
| 246 | + </properties> | |
| 247 | + </profile> | |
| 248 | + | |
| 249 | + <profile> | |
| 250 | + <id>long</id> | |
| 251 | + <properties> | |
| 252 | + <test.groups>unit,short,long</test.groups> | |
| 253 | + <test.skip>false</test.skip> | |
| 254 | + </properties> | |
| 255 | + </profile> | |
| 256 | + | |
| 257 | + </profiles> | |
| 258 | + | |
| 259 | + <licenses> | |
| 260 | + <license> | |
| 261 | + <name>Apache 2</name> | |
| 262 | + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> | |
| 263 | + <distribution>repo</distribution> | |
| 264 | + <comments>Apache License Version 2.0</comments> | |
| 265 | + </license> | |
| 266 | + </licenses> | |
| 267 | + | |
| 268 | + <scm> | |
| 269 | + <connection>scm:git:git@github.com:datastax/java-driver.git</connection> | |
| 270 | + <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection> | |
| 271 | + <url>https://github.com/datastax/java-driver</url> | |
| 272 | + <tag>HEAD</tag> | |
| 273 | + </scm> | |
| 274 | + | |
| 275 | + <developers> | |
| 276 | + <developer> | |
| 277 | + <name>Various</name> | |
| 278 | + <organization>DataStax</organization> | |
| 279 | + </developer> | |
| 280 | + </developers> | |
| 281 | +</project> | |
| 282 | + |
added driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxException.java +23 −0
| @@ -0,0 +1,23 @@ | ||
| 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.api; | |
| 17 | + | |
| 18 | +public class MailboxException extends Exception { | |
| 19 | + | |
| 20 | + public MailboxException(Throwable cause) { | |
| 21 | + super("Failure interacting with Mailbox", cause); | |
| 22 | + } | |
| 23 | +} |
added driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java +106 −0
| @@ -0,0 +1,106 @@ | ||
| 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.api; | |
| 17 | + | |
| 18 | +import com.datastax.driver.extras.codecs.date.SimpleTimestampCodec; | |
| 19 | +import com.datastax.driver.mapping.annotations.ClusteringColumn; | |
| 20 | +import com.datastax.driver.mapping.annotations.Column; | |
| 21 | +import com.datastax.driver.mapping.annotations.PartitionKey; | |
| 22 | +import com.datastax.driver.mapping.annotations.Table; | |
| 23 | +import com.google.common.base.Objects; | |
| 24 | + | |
| 25 | +import static com.datastax.driver.osgi.api.MailboxMessage.TABLE; | |
| 26 | + | |
| 27 | +/** | |
| 28 | + * A mailbox message entity mapped to the table <code>{@value #TABLE}</code>. | |
| 29 | + */ | |
| 30 | +@SuppressWarnings("unused") | |
| 31 | +@Table(name = TABLE) | |
| 32 | +public class MailboxMessage { | |
| 33 | + | |
| 34 | + public static final String TABLE = "mailbox"; | |
| 35 | + | |
| 36 | + @PartitionKey | |
| 37 | + private String recipient; | |
| 38 | + | |
| 39 | + @ClusteringColumn | |
| 40 | + @Column(name = "time", codec = SimpleTimestampCodec.class) | |
| 41 | + private long date; | |
| 42 | + | |
| 43 | + @Column | |
| 44 | + private String sender; | |
| 45 | + | |
| 46 | + @Column | |
| 47 | + private String body; | |
| 48 | + | |
| 49 | + public MailboxMessage() { | |
| 50 | + } | |
| 51 | + | |
| 52 | + public MailboxMessage(String recipient, long date, String sender, String body) { | |
| 53 | + this.recipient = recipient; | |
| 54 | + this.date = date; | |
| 55 | + this.sender = sender; | |
| 56 | + this.body = body; | |
| 57 | + } | |
| 58 | + | |
| 59 | + public String getRecipient() { | |
| 60 | + return recipient; | |
| 61 | + } | |
| 62 | + | |
| 63 | + public void setRecipient(String recipient) { | |
| 64 | + this.recipient = recipient; | |
| 65 | + } | |
| 66 | + | |
| 67 | + public long getDate() { | |
| 68 | + return date; | |
| 69 | + } | |
| 70 | + | |
| 71 | + public void setDate(long date) { | |
| 72 | + this.date = date; | |
| 73 | + } | |
| 74 | + | |
| 75 | + public String getSender() { | |
| 76 | + return sender; | |
| 77 | + } | |
| 78 | + | |
| 79 | + public void setSender(String sender) { | |
| 80 | + this.sender = sender; | |
| 81 | + } | |
| 82 | + | |
| 83 | + public String getBody() { | |
| 84 | + return body; | |
| 85 | + } | |
| 86 | + | |
| 87 | + public void setBody(String body) { | |
| 88 | + this.body = body; | |
| 89 | + } | |
| 90 | + | |
| 91 | + @Override | |
| 92 | + public boolean equals(Object o) { | |
| 93 | + if (this == o) return true; | |
| 94 | + if (o == null || getClass() != o.getClass()) return false; | |
| 95 | + MailboxMessage that = (MailboxMessage) o; | |
| 96 | + return date == that.date && | |
| 97 | + Objects.equal(recipient, that.recipient) && | |
| 98 | + Objects.equal(sender, that.sender) && | |
| 99 | + Objects.equal(body, that.body); | |
| 100 | + } | |
| 101 | + | |
| 102 | + @Override | |
| 103 | + public int hashCode() { | |
| 104 | + return Objects.hashCode(recipient, date, sender, body); | |
| 105 | + } | |
| 106 | +} |
added driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxService.java +42 −0
| @@ -0,0 +1,42 @@ | ||
| 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.api; | |
| 17 | + | |
| 18 | +public interface MailboxService { | |
| 19 | + | |
| 20 | + /** | |
| 21 | + * Retrieve all messages for a given recipient. | |
| 22 | + * | |
| 23 | + * @param recipient User whose mailbox is being read. | |
| 24 | + * @return All messages in the mailbox. | |
| 25 | + */ | |
| 26 | + public Iterable<MailboxMessage> getMessages(String recipient) throws MailboxException; | |
| 27 | + | |
| 28 | + /** | |
| 29 | + * Stores the given message in the appropriate mailbox. | |
| 30 | + * | |
| 31 | + * @param message Message to send. | |
| 32 | + * @return The timestamp generated for the message (milliseconds since the Epoch). | |
| 33 | + */ | |
| 34 | + public long sendMessage(MailboxMessage message) throws MailboxException; | |
| 35 | + | |
| 36 | + /** | |
| 37 | + * Deletes all mail for the given recipient. | |
| 38 | + * | |
| 39 | + * @param recipient User whose mailbox will be cleared. | |
| 40 | + */ | |
| 41 | + public void clearMailbox(String recipient) throws MailboxException; | |
| 42 | +} |
added driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java +95 −0
| @@ -0,0 +1,95 @@ | ||
| 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.impl; | |
| 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; | |
| 22 | +import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 23 | +import com.datastax.driver.extras.codecs.date.SimpleTimestampCodec; | |
| 24 | +import com.datastax.driver.osgi.api.MailboxService; | |
| 25 | +import org.osgi.framework.BundleActivator; | |
| 26 | +import org.osgi.framework.BundleContext; | |
| 27 | + | |
| 28 | +import java.util.Hashtable; | |
| 29 | + | |
| 30 | +import static com.datastax.driver.osgi.api.MailboxMessage.TABLE; | |
| 31 | + | |
| 32 | +public class Activator implements BundleActivator { | |
| 33 | + | |
| 34 | + private Cluster cluster; | |
| 35 | + | |
| 36 | + @Override | |
| 37 | + public void start(BundleContext context) throws Exception { | |
| 38 | + String contactPointsStr = context.getProperty("cassandra.contactpoints"); | |
| 39 | + if (contactPointsStr == null) { | |
| 40 | + contactPointsStr = "127.0.0.1"; | |
| 41 | + } | |
| 42 | + String[] contactPoints = contactPointsStr.split(","); | |
| 43 | + | |
| 44 | + String keyspace = context.getProperty("cassandra.keyspace"); | |
| 45 | + if (keyspace == null) { | |
| 46 | + keyspace = "mailbox"; | |
| 47 | + } | |
| 48 | + keyspace = Metadata.quote(keyspace); | |
| 49 | + | |
| 50 | + cluster = Cluster.builder() | |
| 51 | + .addContactPoints(contactPoints) | |
| 52 | + .withCodecRegistry(new CodecRegistry().register(SimpleTimestampCodec.instance)) | |
| 53 | + .build(); | |
| 54 | + | |
| 55 | + Session session; | |
| 56 | + try { | |
| 57 | + session = cluster.connect(keyspace); | |
| 58 | + } catch (InvalidQueryException e) { | |
| 59 | + // Create the schema if it does not exist. | |
| 60 | + session = cluster.connect(); | |
| 61 | + session.execute("CREATE KEYSPACE " + keyspace + | |
| 62 | + " with replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}"); | |
| 63 | + session.execute("CREATE TABLE " + keyspace + "." + TABLE + " (" + | |
| 64 | + "recipient text," + | |
| 65 | + "time timestamp," + | |
| 66 | + "sender text," + | |
| 67 | + "body text," + | |
| 68 | + "PRIMARY KEY (recipient, time))"); | |
| 69 | + session.execute("USE " + keyspace); | |
| 70 | + } | |
| 71 | + | |
| 72 | + MailboxImpl mailbox = new MailboxImpl(session, keyspace); | |
| 73 | + mailbox.init(); | |
| 74 | + | |
| 75 | + context.registerService(MailboxService.class.getName(), mailbox, new Hashtable<String, String>()); | |
| 76 | + } | |
| 77 | + | |
| 78 | + @Override | |
| 79 | + public void stop(BundleContext context) throws Exception { | |
| 80 | + if (cluster != null) { | |
| 81 | + cluster.close(); | |
| 82 | + /* | |
| 83 | + Allow Netty ThreadDeathWatcher to terminate; | |
| 84 | + unfortunately we can't explicitly call ThreadDeathWatcher.awaitInactivity() | |
| 85 | + because Netty could be shaded. | |
| 86 | + If this thread isn't terminated when this bundle is closed, | |
| 87 | + we could get exceptions such as this one: | |
| 88 | + Exception in thread "threadDeathWatcher-2-1" java.lang.NoClassDefFoundError: xxx | |
| 89 | + Caused by: java.lang.ClassNotFoundException: Unable to load class 'xxx' because the bundle wiring for xxx is no longer valid. | |
| 90 | + Although ugly, they are harmless and can be safely ignored. | |
| 91 | + */ | |
| 92 | + Thread.sleep(1000); | |
| 93 | + } | |
| 94 | + } | |
| 95 | +} |
added driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java +98 −0
| @@ -0,0 +1,98 @@ | ||
| 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.impl; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.BoundStatement; | |
| 19 | +import com.datastax.driver.core.PreparedStatement; | |
| 20 | +import com.datastax.driver.core.Session; | |
| 21 | +import com.datastax.driver.mapping.Mapper; | |
| 22 | +import com.datastax.driver.mapping.MappingManager; | |
| 23 | +import com.datastax.driver.osgi.api.MailboxException; | |
| 24 | +import com.datastax.driver.osgi.api.MailboxMessage; | |
| 25 | +import com.datastax.driver.osgi.api.MailboxService; | |
| 26 | + | |
| 27 | +import static com.datastax.driver.core.querybuilder.QueryBuilder.*; | |
| 28 | +import static com.datastax.driver.osgi.api.MailboxMessage.TABLE; | |
| 29 | + | |
| 30 | +public class MailboxImpl implements MailboxService { | |
| 31 | + | |
| 32 | + private final Session session; | |
| 33 | + | |
| 34 | + private final String keyspace; | |
| 35 | + | |
| 36 | + private volatile boolean initialized = false; | |
| 37 | + | |
| 38 | + private PreparedStatement retrieveStatement; | |
| 39 | + | |
| 40 | + private PreparedStatement deleteStatement; | |
| 41 | + | |
| 42 | + private Mapper<MailboxMessage> mapper; | |
| 43 | + | |
| 44 | + public MailboxImpl(Session session, String keyspace) { | |
| 45 | + this.session = session; | |
| 46 | + this.keyspace = keyspace; | |
| 47 | + } | |
| 48 | + | |
| 49 | + public synchronized void init() { | |
| 50 | + if (initialized) | |
| 51 | + return; | |
| 52 | + | |
| 53 | + retrieveStatement = session.prepare(select() | |
| 54 | + .from(keyspace, TABLE) | |
| 55 | + .where(eq("recipient", bindMarker()))); | |
| 56 | + | |
| 57 | + deleteStatement = session.prepare(delete().from(keyspace, TABLE) | |
| 58 | + .where(eq("recipient", bindMarker()))); | |
| 59 | + | |
| 60 | + MappingManager mappingManager = new MappingManager(session); | |
| 61 | + | |
| 62 | + mapper = mappingManager.mapper(MailboxMessage.class); | |
| 63 | + | |
| 64 | + initialized = true; | |
| 65 | + } | |
| 66 | + | |
| 67 | + @Override | |
| 68 | + public Iterable<MailboxMessage> getMessages(String recipient) throws MailboxException { | |
| 69 | + try { | |
| 70 | + BoundStatement statement = new BoundStatement(retrieveStatement); | |
| 71 | + statement.setString(0, recipient); | |
| 72 | + return mapper.map(session.execute(statement)); | |
| 73 | + } catch (Exception e) { | |
| 74 | + throw new MailboxException(e); | |
| 75 | + } | |
| 76 | + } | |
| 77 | + | |
| 78 | + @Override | |
| 79 | + public long sendMessage(MailboxMessage message) throws MailboxException { | |
| 80 | + try { | |
| 81 | + mapper.save(message); | |
| 82 | + return message.getDate(); | |
| 83 | + } catch (Exception e) { | |
| 84 | + throw new MailboxException(e); | |
| 85 | + } | |
| 86 | + } | |
| 87 | + | |
| 88 | + @Override | |
| 89 | + public void clearMailbox(String recipient) throws MailboxException { | |
| 90 | + try { | |
| 91 | + BoundStatement statement = new BoundStatement(deleteStatement); | |
| 92 | + statement.setString(0, recipient); | |
| 93 | + session.execute(statement); | |
| 94 | + } catch (Exception e) { | |
| 95 | + throw new MailboxException(e); | |
| 96 | + } | |
| 97 | + } | |
| 98 | +} |
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/BundleOptions.java +93 −0
| @@ -0,0 +1,93 @@ | ||
| 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.core.TestUtils; | |
| 19 | +import org.ops4j.pax.exam.Option; | |
| 20 | +import org.ops4j.pax.exam.options.CompositeOption; | |
| 21 | +import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; | |
| 22 | +import org.ops4j.pax.exam.options.UrlProvisionOption; | |
| 23 | +import org.ops4j.pax.exam.util.PathUtils; | |
| 24 | + | |
| 25 | +import static com.datastax.driver.osgi.VersionProvider.projectVersion; | |
| 26 | +import static org.ops4j.pax.exam.CoreOptions.*; | |
| 27 | + | |
| 28 | +public class BundleOptions { | |
| 29 | + | |
| 30 | + public static UrlProvisionOption driverBundle() { | |
| 31 | + return driverBundle(false); | |
| 32 | + } | |
| 33 | + | |
| 34 | + public static UrlProvisionOption driverBundle(boolean useShaded) { | |
| 35 | + String classifier = useShaded ? "-shaded" : ""; | |
| 36 | + return bundle("reference:file:" + PathUtils.getBaseDir() + "/../../driver-core/target/cassandra-driver-core-" + projectVersion() + classifier + ".jar"); | |
| 37 | + } | |
| 38 | + | |
| 39 | + public static UrlProvisionOption mappingBundle() { | |
| 40 | + return bundle("reference:file:" + PathUtils.getBaseDir() + "/../../driver-mapping/target/cassandra-driver-mapping-" + projectVersion() + ".jar"); | |
| 41 | + } | |
| 42 | + | |
| 43 | + public static UrlProvisionOption extrasBundle() { | |
| 44 | + return bundle("reference:file:" + PathUtils.getBaseDir() + "/../../driver-extras/target/cassandra-driver-extras-" + projectVersion() + ".jar"); | |
| 45 | + } | |
| 46 | + | |
| 47 | + public static MavenArtifactProvisionOption guavaBundle() { | |
| 48 | + return mavenBundle("com.google.guava", "guava", "16.0.1"); | |
| 49 | + } | |
| 50 | + | |
| 51 | + public static CompositeOption nettyBundles() { | |
| 52 | + final String nettyVersion = "4.0.33.Final"; | |
| 53 | + return new CompositeOption() { | |
| 54 | + | |
| 55 | + @Override | |
| 56 | + public Option[] getOptions() { | |
| 57 | + return options( | |
| 58 | + mavenBundle("io.netty", "netty-buffer", nettyVersion), | |
| 59 | + mavenBundle("io.netty", "netty-codec", nettyVersion), | |
| 60 | + mavenBundle("io.netty", "netty-common", nettyVersion), | |
| 61 | + mavenBundle("io.netty", "netty-handler", nettyVersion), | |
| 62 | + mavenBundle("io.netty", "netty-transport", nettyVersion) | |
| 63 | + ); | |
| 64 | + } | |
| 65 | + }; | |
| 66 | + } | |
| 67 | + | |
| 68 | + public static UrlProvisionOption mailboxBundle() { | |
| 69 | + return bundle("reference:file:" + PathUtils.getBaseDir() + "/target/classes"); | |
| 70 | + } | |
| 71 | + | |
| 72 | + public static CompositeOption defaultOptions() { | |
| 73 | + return new CompositeOption() { | |
| 74 | + | |
| 75 | + @Override | |
| 76 | + public Option[] getOptions() { | |
| 77 | + return options( | |
| 78 | + // Delegate javax.security.cert to the parent classloader. javax.security.cert.X509Certificate is used in | |
| 79 | + // io.netty.util.internal.EmptyArrays, but not directly by the driver. | |
| 80 | + bootDelegationPackage("javax.security.cert"), | |
| 81 | + systemProperty("cassandra.contactpoints").value(TestUtils.IP_PREFIX + 1), | |
| 82 | + systemProperty("logback.configurationFile").value("file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"), | |
| 83 | + mavenBundle("org.slf4j", "slf4j-api", "1.7.5"), | |
| 84 | + mavenBundle("ch.qos.logback", "logback-classic", "1.1.3"), | |
| 85 | + mavenBundle("ch.qos.logback", "logback-core", "1.1.3"), | |
| 86 | + mavenBundle("io.dropwizard.metrics", "metrics-core", "3.1.2"), | |
| 87 | + systemPackages("org.testng", "org.junit", "org.junit.runner", "org.junit.runner.manipulation", | |
| 88 | + "org.junit.runner.notification", "com.jcabi.manifests") | |
| 89 | + ); | |
| 90 | + } | |
| 91 | + }; | |
| 92 | + } | |
| 93 | +} |
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java +65 −0
| @@ -0,0 +1,65 @@ | ||
| 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.core.CCMBridge; | |
| 19 | +import org.testng.ITestContext; | |
| 20 | +import org.testng.ITestListener; | |
| 21 | +import org.testng.ITestResult; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * A listener that fires up a single node CCM instance on test class start and tears it | |
| 25 | + * down on test class end. | |
| 26 | + * <p/> | |
| 27 | + * This is needed for tests that use Pax-Exam since it runs some methods in the OSGi container | |
| 28 | + * which we do not want. | |
| 29 | + */ | |
| 30 | +public class CCMBridgeListener implements ITestListener { | |
| 31 | + | |
| 32 | + private CCMBridge ccm; | |
| 33 | + | |
| 34 | + @Override | |
| 35 | + public void onStart(ITestContext context) { | |
| 36 | + ccm = CCMBridge.builder().withNodes(1).withBinaryPort(9042).build(); | |
| 37 | + } | |
| 38 | + | |
| 39 | + @Override | |
| 40 | + public void onFinish(ITestContext context) { | |
| 41 | + if (ccm != null) { | |
| 42 | + ccm.remove(); | |
| 43 | + } | |
| 44 | + } | |
| 45 | + | |
| 46 | + @Override | |
| 47 | + public void onTestStart(ITestResult result) { | |
| 48 | + } | |
| 49 | + | |
| 50 | + @Override | |
| 51 | + public void onTestSuccess(ITestResult result) { | |
| 52 | + } | |
| 53 | + | |
| 54 | + @Override | |
| 55 | + public void onTestFailure(ITestResult result) { | |
| 56 | + } | |
| 57 | + | |
| 58 | + @Override | |
| 59 | + public void onTestSkipped(ITestResult result) { | |
| 60 | + } | |
| 61 | + | |
| 62 | + @Override | |
| 63 | + public void onTestFailedButWithinSuccessPercentage(ITestResult result) { | |
| 64 | + } | |
| 65 | +} |
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceDefaultIT.java +57 −0
| @@ -0,0 +1,57 @@ | ||
| 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 MailboxServiceDefaultIT extends MailboxServiceTests { | |
| 30 | + | |
| 31 | + @Configuration | |
| 32 | + public Option[] defaultConfig() { | |
| 33 | + return options( | |
| 34 | + defaultOptions(), | |
| 35 | + nettyBundles(), | |
| 36 | + guavaBundle(), | |
| 37 | + driverBundle(), | |
| 38 | + extrasBundle(), | |
| 39 | + mappingBundle(), | |
| 40 | + mailboxBundle() | |
| 41 | + ); | |
| 42 | + } | |
| 43 | + | |
| 44 | + /** | |
| 45 | + * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver with | |
| 46 | + * default configuration (driver with all of its regular dependencies). | |
| 47 | + * | |
| 48 | + * @test_category packaging | |
| 49 | + * @expected_result Can create, retrieve and delete data using the mailbox service. | |
| 50 | + * @jira_ticket JAVA-620 | |
| 51 | + * @since 2.0.10, 2.1.5 | |
| 52 | + */ | |
| 53 | + @Test(groups = "short") | |
| 54 | + public void test_default() throws MailboxException { | |
| 55 | + checkService(); | |
| 56 | + } | |
| 57 | +} |
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava17IT.java +57 −0
| @@ -0,0 +1,57 @@ | ||
| 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 MailboxServiceGuava17IT extends MailboxServiceTests { | |
| 30 | + | |
| 31 | + @Configuration | |
| 32 | + public Option[] guava17Config() { | |
| 33 | + return options( | |
| 34 | + defaultOptions(), | |
| 35 | + nettyBundles(), | |
| 36 | + guavaBundle().version("17.0"), | |
| 37 | + driverBundle(), | |
| 38 | + mappingBundle(), | |
| 39 | + extrasBundle(), | |
| 40 | + mailboxBundle() | |
| 41 | + ); | |
| 42 | + } | |
| 43 | + | |
| 44 | + /** | |
| 45 | + * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver with | |
| 46 | + * Guava 17 explicitly enforced. | |
| 47 | + * | |
| 48 | + * @test_category packaging | |
| 49 | + * @expected_result Can create, retrieve and delete data using the mailbox service. | |
| 50 | + * @jira_ticket JAVA-620 | |
| 51 | + * @since 2.0.10, 2.1.5 | |
| 52 | + */ | |
| 53 | + @Test(groups = "short") | |
| 54 | + public void test_guava_17() throws MailboxException { | |
| 55 | + checkService(); | |
| 56 | + } | |
| 57 | +} |
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava18IT.java +57 −0
| @@ -0,0 +1,57 @@ | ||
| 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 MailboxServiceGuava18IT extends MailboxServiceTests { | |
| 30 | + | |
| 31 | + @Configuration | |
| 32 | + public Option[] guava18Config() { | |
| 33 | + return options( | |
| 34 | + defaultOptions(), | |
| 35 | + nettyBundles(), | |
| 36 | + guavaBundle().version("18.0"), | |
| 37 | + driverBundle(), | |
| 38 | + extrasBundle(), | |
| 39 | + mappingBundle(), | |
| 40 | + mailboxBundle() | |
| 41 | + ); | |
| 42 | + } | |
| 43 | + | |
| 44 | + /** | |
| 45 | + * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver with | |
| 46 | + * Guava 18 explicitly enforced. | |
| 47 | + * | |
| 48 | + * @test_category packaging | |
| 49 | + * @expected_result Can create, retrieve and delete data using the mailbox service. | |
| 50 | + * @jira_ticket JAVA-620 | |
| 51 | + * @since 2.0.10, 2.1.5 | |
| 52 | + */ | |
| 53 | + @Test(groups = "short") | |
| 54 | + public void test_guava_18() throws MailboxException { | |
| 55 | + checkService(); | |
| 56 | + } | |
| 57 | +} |
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava19IT.java +57 −0
| @@ -0,0 +1,57 @@ | ||
| 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 MailboxServiceGuava19IT extends MailboxServiceTests { | |
| 30 | + | |
| 31 | + @Configuration | |
| 32 | + public Option[] guava19Config() { | |
| 33 | + return options( | |
| 34 | + defaultOptions(), | |
| 35 | + nettyBundles(), | |
| 36 | + guavaBundle().version("19.0"), | |
| 37 | + driverBundle(), | |
| 38 | + extrasBundle(), | |
| 39 | + mappingBundle(), | |
| 40 | + mailboxBundle() | |
| 41 | + ); | |
| 42 | + } | |
| 43 | + | |
| 44 | + /** | |
| 45 | + * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver with | |
| 46 | + * Guava 19 explicitly enforced. | |
| 47 | + * | |
| 48 | + * @test_category packaging | |
| 49 | + * @expected_result Can create, retrieve and delete data using the mailbox service. | |
| 50 | + * @jira_ticket JAVA-620 | |
| 51 | + * @since 2.0.10, 2.1.5 | |
| 52 | + */ | |
| 53 | + @Test(groups = "short") | |
| 54 | + public void test_guava_19() throws MailboxException { | |
| 55 | + checkService(); | |
| 56 | + } | |
| 57 | +} |
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceShadedIT.java +56 −0
| @@ -0,0 +1,56 @@ | ||
| 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 MailboxServiceShadedIT extends MailboxServiceTests { | |
| 30 | + | |
| 31 | + @Configuration | |
| 32 | + public Option[] shadedConfig() { | |
| 33 | + return options( | |
| 34 | + defaultOptions(), | |
| 35 | + guavaBundle(), | |
| 36 | + extrasBundle(), | |
| 37 | + mappingBundle(), | |
| 38 | + driverBundle(true), | |
| 39 | + mailboxBundle() | |
| 40 | + ); | |
| 41 | + } | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver with | |
| 45 | + * shaded configuration (driver with Netty shaded). | |
| 46 | + * | |
| 47 | + * @test_category packaging | |
| 48 | + * @expected_result Can create, retrieve and delete data using the mailbox service. | |
| 49 | + * @jira_ticket JAVA-620 | |
| 50 | + * @since 2.0.10, 2.1.5 | |
| 51 | + */ | |
| 52 | + @Test(groups = "short") | |
| 53 | + public void test_shaded() throws MailboxException { | |
| 54 | + checkService(); | |
| 55 | + } | |
| 56 | +} |
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceTests.java +81 −0
| @@ -0,0 +1,81 @@ | ||
| 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 com.datastax.driver.osgi.api.MailboxMessage; | |
| 20 | +import com.datastax.driver.osgi.api.MailboxService; | |
| 21 | +import org.osgi.framework.Bundle; | |
| 22 | +import org.osgi.framework.BundleContext; | |
| 23 | +import org.slf4j.Logger; | |
| 24 | +import org.slf4j.LoggerFactory; | |
| 25 | + | |
| 26 | +import javax.inject.Inject; | |
| 27 | +import java.util.ArrayList; | |
| 28 | +import java.util.Collection; | |
| 29 | +import java.util.GregorianCalendar; | |
| 30 | + | |
| 31 | +import static org.testng.Assert.assertEquals; | |
| 32 | + | |
| 33 | +public abstract class MailboxServiceTests { | |
| 34 | + | |
| 35 | + private static final Logger LOGGER = LoggerFactory.getLogger(MailboxServiceTests.class); | |
| 36 | + | |
| 37 | + @Inject | |
| 38 | + MailboxService service; | |
| 39 | + | |
| 40 | + @Inject | |
| 41 | + BundleContext bundleContext; | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * <p> | |
| 45 | + * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver. Ensures that | |
| 46 | + * queries can be made through the service with the current given configuration. | |
| 47 | + * </p> | |
| 48 | + * <p/> | |
| 49 | + * The following configurations are tried (defined via methods with the @Configuration annotation): | |
| 50 | + * <ol> | |
| 51 | + * <li>Default bundle (Driver with all of it's dependencies and Guava 16.0.1)</li> | |
| 52 | + * <li>Shaded bundle (Driver with netty shaded and Guava 16.0.1)</li> | |
| 53 | + * <li>With Guava 17</li> | |
| 54 | + * <li>With Guava 18</li> | |
| 55 | + * <li>With Guava 19</li> | |
| 56 | + * </ol> | |
| 57 | + */ | |
| 58 | + protected void checkService() throws MailboxException { | |
| 59 | + if (LOGGER.isDebugEnabled()) { | |
| 60 | + for (Bundle bundle : bundleContext.getBundles()) { | |
| 61 | + LOGGER.debug("Loaded bundle: {} {}", bundle.getSymbolicName(), bundle.getVersion()); | |
| 62 | + } | |
| 63 | + } | |
| 64 | + // Insert some data into mailbox for a particular user. | |
| 65 | + String recipient = "user@datastax.com"; | |
| 66 | + try { | |
| 67 | + Collection<MailboxMessage> inMessages = new ArrayList<MailboxMessage>(); | |
| 68 | + for (int i = 0; i < 30; i++) { | |
| 69 | + MailboxMessage message = new MailboxMessage(recipient, new GregorianCalendar(2015, 1, i).getTimeInMillis(), recipient, "" + i); | |
| 70 | + inMessages.add(message); | |
| 71 | + service.sendMessage(message); | |
| 72 | + } | |
| 73 | + | |
| 74 | + Iterable<MailboxMessage> messages = service.getMessages(recipient); | |
| 75 | + | |
| 76 | + assertEquals(messages, inMessages); | |
| 77 | + } finally { | |
| 78 | + service.clearMailbox(recipient); | |
| 79 | + } | |
| 80 | + } | |
| 81 | +} |
added driver-tests/osgi/src/test/java/com/datastax/driver/osgi/VersionProvider.java +59 −0
| @@ -0,0 +1,59 @@ | ||
| 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.jcabi.manifests.Manifests; | |
| 19 | + | |
| 20 | +import java.util.regex.Matcher; | |
| 21 | +import java.util.regex.Pattern; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * Attempts to resolve the project version from the Bundle manifest. If not present, will throw RuntimeException | |
| 25 | + * on initialization. If this happens, try building with 'mvn compile' to generate the Bundle manifest. | |
| 26 | + * <p/> | |
| 27 | + * In IntelliJ you can have compile run after make by right clicking on 'compile' in the 'Maven Projects' tool window. | |
| 28 | + */ | |
| 29 | +public class VersionProvider { | |
| 30 | + | |
| 31 | + private static final Pattern versionPattern = Pattern.compile(("(\\d+.\\d+\\.\\d+)(.*)")); | |
| 32 | + | |
| 33 | + private static final String PROJECT_VERSION; | |
| 34 | + | |
| 35 | + static { | |
| 36 | + String bundleName = Manifests.read("Bundle-SymbolicName"); | |
| 37 | + if (bundleName.equals("com.datastax.driver.osgi")) { | |
| 38 | + String bundleVersion = Manifests.read("Bundle-Version"); | |
| 39 | + Matcher matcher = versionPattern.matcher(bundleVersion); | |
| 40 | + if (matcher.matches()) { | |
| 41 | + String majorVersion = matcher.group(1); | |
| 42 | + // Replace all instances of '.' after the main version with '-' to properly | |
| 43 | + // resolve the correct version. | |
| 44 | + String rest = matcher.group(2).replaceAll("\\.", "-"); | |
| 45 | + PROJECT_VERSION = majorVersion + rest; | |
| 46 | + } else { | |
| 47 | + // This should never happen, but if we are using a non X.Y.Z version number | |
| 48 | + // we'll just back off to the bundle version. | |
| 49 | + PROJECT_VERSION = bundleVersion; | |
| 50 | + } | |
| 51 | + } else { | |
| 52 | + throw new RuntimeException("Couldn't resolve bundle manifest (try building with mvn compile)"); | |
| 53 | + } | |
| 54 | + } | |
| 55 | + | |
| 56 | + public static String projectVersion() { | |
| 57 | + return PROJECT_VERSION; | |
| 58 | + } | |
| 59 | +} |
added driver-tests/osgi/src/test/resources/exam.properties +18 −0
| @@ -0,0 +1,18 @@ | ||
| 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 | + | |
| 17 | +pax.exam.system=test | |
| 18 | +pax.exam.logging=none | |
| No newline at the end of the file |
added driver-tests/osgi/src/test/resources/logback.xml +50 −0
| @@ -0,0 +1,50 @@ | ||
| 1 | +<!-- | |
| 2 | + | |
| 3 | + Copyright (C) 2012-2015 DataStax Inc. | |
| 4 | + | |
| 5 | + Licensed under the Apache License, Version 2.0 (the "License"); | |
| 6 | + you may not use this file except in compliance with the License. | |
| 7 | + You may obtain a copy of the License at | |
| 8 | + | |
| 9 | + http://www.apache.org/licenses/LICENSE-2.0 | |
| 10 | + | |
| 11 | + Unless required by applicable law or agreed to in writing, software | |
| 12 | + distributed under the License is distributed on an "AS IS" BASIS, | |
| 13 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 14 | + See the License for the specific language governing permissions and | |
| 15 | + limitations under the License. | |
| 16 | + | |
| 17 | +--> | |
| 18 | +<configuration> | |
| 19 | + | |
| 20 | + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> | |
| 21 | + <encoder> | |
| 22 | + <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> | |
| 23 | + </encoder> | |
| 24 | + </appender> | |
| 25 | + | |
| 26 | + <root level="INFO"> | |
| 27 | + <appender-ref ref="STDOUT"/> | |
| 28 | + </root> | |
| 29 | + | |
| 30 | + <!-- debug Pax Exam --> | |
| 31 | + <!--<logger name="org.ops4j.pax" level="DEBUG" additivity="false">--> | |
| 32 | + <!--<appender-ref ref="STDOUT"/>--> | |
| 33 | + <!--</logger>--> | |
| 34 | + | |
| 35 | + <!-- print loaded bundles --> | |
| 36 | + <!--<logger name="com.datastax.driver.osgi.MailboxServiceTests" level="DEBUG" additivity="false">--> | |
| 37 | + <!--<appender-ref ref="STDOUT"/>--> | |
| 38 | + <!--</logger>--> | |
| 39 | + | |
| 40 | + <!-- this guy is a bit too verbose --> | |
| 41 | + <logger name="org.ops4j.pax.exam.nat.internal.NativeTestContainer" level="WARN" additivity="false"> | |
| 42 | + <appender-ref ref="STDOUT"/> | |
| 43 | + </logger> | |
| 44 | + | |
| 45 | + <!-- this one too --> | |
| 46 | + <logger name="com.jcabi.manifests.Manifests" level="WARN" additivity="false"> | |
| 47 | + <appender-ref ref="STDOUT"/> | |
| 48 | + </logger> | |
| 49 | + | |
| 50 | +</configuration> |
added driver-tests/pom.xml +83 −0
| @@ -0,0 +1,83 @@ | ||
| 1 | +<!-- | |
| 2 | + | |
| 3 | + Copyright (C) 2012-2015 DataStax Inc. | |
| 4 | + | |
| 5 | + Licensed under the Apache License, Version 2.0 (the "License"); | |
| 6 | + you may not use this file except in compliance with the License. | |
| 7 | + You may obtain a copy of the License at | |
| 8 | + | |
| 9 | + http://www.apache.org/licenses/LICENSE-2.0 | |
| 10 | + | |
| 11 | + Unless required by applicable law or agreed to in writing, software | |
| 12 | + distributed under the License is distributed on an "AS IS" BASIS, | |
| 13 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 14 | + See the License for the specific language governing permissions and | |
| 15 | + limitations under the License. | |
| 16 | + | |
| 17 | +--> | |
| 18 | +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 19 | + <modelVersion>4.0.0</modelVersion> | |
| 20 | + <parent> | |
| 21 | + <groupId>com.datastax.cassandra</groupId> | |
| 22 | + <artifactId>cassandra-driver-parent</artifactId> | |
| 23 | + <version>3.0.1-SNAPSHOT</version> | |
| 24 | + </parent> | |
| 25 | + <artifactId>cassandra-driver-tests-parent</artifactId> | |
| 26 | + <packaging>pom</packaging> | |
| 27 | + <name>DataStax Java Driver for Apache Cassandra Tests</name> | |
| 28 | + <description>Tests for the DataStax Java Driver for Apache Cassandra.</description> | |
| 29 | + <url>https://github.com/datastax/java-driver</url> | |
| 30 | + | |
| 31 | + <properties> | |
| 32 | + <main.basedir>${project.parent.basedir}</main.basedir> | |
| 33 | + </properties> | |
| 34 | + | |
| 35 | + <modules> | |
| 36 | + <module>stress</module> | |
| 37 | + <module>osgi</module> | |
| 38 | + </modules> | |
| 39 | + | |
| 40 | + <licenses> | |
| 41 | + <license> | |
| 42 | + <name>Apache 2</name> | |
| 43 | + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> | |
| 44 | + <distribution>repo</distribution> | |
| 45 | + <comments>Apache License Version 2.0</comments> | |
| 46 | + </license> | |
| 47 | + </licenses> | |
| 48 | + | |
| 49 | + <scm> | |
| 50 | + <connection>scm:git:git@github.com:datastax/java-driver.git</connection> | |
| 51 | + <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection> | |
| 52 | + <url>https://github.com/datastax/java-driver</url> | |
| 53 | + <tag>HEAD</tag> | |
| 54 | + </scm> | |
| 55 | + | |
| 56 | + <developers> | |
| 57 | + <developer> | |
| 58 | + <name>Various</name> | |
| 59 | + <organization>DataStax</organization> | |
| 60 | + </developer> | |
| 61 | + </developers> | |
| 62 | + | |
| 63 | + <build> | |
| 64 | + <plugins> | |
| 65 | + <plugin> | |
| 66 | + <groupId>org.apache.maven.plugins</groupId> | |
| 67 | + <artifactId>maven-install-plugin</artifactId> | |
| 68 | + <version>2.5.1</version> | |
| 69 | + <configuration> | |
| 70 | + <skip>true</skip> | |
| 71 | + </configuration> | |
| 72 | + </plugin> | |
| 73 | + <plugin> | |
| 74 | + <groupId>org.apache.maven.plugins</groupId> | |
| 75 | + <artifactId>maven-deploy-plugin</artifactId> | |
| 76 | + <version>2.8.1</version> | |
| 77 | + <configuration> | |
| 78 | + <skip>true</skip> | |
| 79 | + </configuration> | |
| 80 | + </plugin> | |
| 81 | + </plugins> | |
| 82 | + </build> | |
| 83 | +</project> |
added driver-tests/stress/README.md +25 −0
| @@ -0,0 +1,25 @@ | ||
| 1 | +# Stress application | |
| 2 | + | |
| 3 | +A simple example application that uses the Java driver to stress test | |
| 4 | +Cassandra. This also somewhat stress tests the Java driver as a result. | |
| 5 | + | |
| 6 | +Please note that this simple example is far from being a complete stress | |
| 7 | +application. In particular it currently supports a very limited number of | |
| 8 | +stress scenarios. | |
| 9 | + | |
| 10 | +## Usage | |
| 11 | + | |
| 12 | +You will need to build the stress application fist: | |
| 13 | + | |
| 14 | + ./bin/build | |
| 15 | + | |
| 16 | +After which you can run it using for instance: | |
| 17 | + | |
| 18 | + ./bin/stress insert_prepared | |
| 19 | + | |
| 20 | +Of course, you will need to have at least one Cassandra node running (on | |
| 21 | +127.0.0.1 by default) for this to work. Please refer to: | |
| 22 | + | |
| 23 | + ./bin/stress -h | |
| 24 | + | |
| 25 | +for more details on the options available. |
added driver-tests/stress/bin/build +36 −0
| @@ -0,0 +1,36 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | + | |
| 3 | +SCRIPT_DIR=$( cd "$( dirname "$0" )" && pwd ) | |
| 4 | +CURRENT_DIR=$( pwd ) | |
| 5 | + | |
| 6 | +LOG_FILE="$CURRENT_DIR/stress_build.log" | |
| 7 | +[ -f $LOG_FILE ] && rm $LOG_FILE | |
| 8 | + | |
| 9 | +echo "Building java driver ..." | |
| 10 | +echo "-- Driver build --\n" > $LOG_FILE | |
| 11 | + | |
| 12 | +cd $SCRIPT_DIR/../../.. | |
| 13 | +mvn clean install -Dmaven.test.skip=true >> $LOG_FILE 2>&1 | |
| 14 | +EXIT_CODE=$? | |
| 15 | +if [ $EXIT_CODE -ne 0 ]; | |
| 16 | +then | |
| 17 | + echo "Error building driver. See $LOG_FILE for details." 1>&2 | |
| 18 | + cd $CURRENT_DIR | |
| 19 | + exit $EXIT_CODE | |
| 20 | +fi | |
| 21 | + | |
| 22 | +echo "Building stress application ..." | |
| 23 | +echo "\n-- Stress build --\n" >> $LOG_FILE | |
| 24 | + | |
| 25 | +cd $SCRIPT_DIR/.. | |
| 26 | +mvn package assembly:single >> $LOG_FILE 2>&1 | |
| 27 | +EXIT_CODE=$? | |
| 28 | +if [ $EXIT_CODE -ne 0 ]; | |
| 29 | +then | |
| 30 | + echo "Error building stress application. See $LOG_FILE for details." 1>&2 | |
| 31 | + cd $CURRENT_DIR | |
| 32 | + exit $EXIT_CODE | |
| 33 | +fi | |
| 34 | + | |
| 35 | +cd $CURRENT_DIR | |
| 36 | +rm $LOG_FILE |
added driver-tests/stress/bin/stress +30 −0
| @@ -0,0 +1,30 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | + | |
| 3 | +SCRIPT_DIR=$( cd "$( dirname "$0" )" && pwd ) | |
| 4 | +CURRENT_DIR=$( pwd ) | |
| 5 | + | |
| 6 | +# Use $JAVA_HOME if set | |
| 7 | +if [ -n "$JAVA_HOME" ]; then | |
| 8 | + JAVA="$JAVA_HOME/bin/java" | |
| 9 | +else | |
| 10 | + JAVA=java | |
| 11 | +fi | |
| 12 | + | |
| 13 | +if [ "x$STRESS_JAR" = "x" ]; then | |
| 14 | + | |
| 15 | + STRESS_JAR="$SCRIPT_DIR/../target/cassandra-driver-tests-stress-*-jar-with-dependencies.jar" | |
| 16 | + | |
| 17 | + if [ ! -f $STRESS_JAR ]; then | |
| 18 | + # Trash the version file in case there was some crap in it | |
| 19 | + RELATIVE_SCRIPT_DIR=`dirname $0` | |
| 20 | + echo "Stress application does not seem to be build, try $RELATIVE_SCRIPT_DIR/build first" 1>&2 | |
| 21 | + exit 1 | |
| 22 | + fi | |
| 23 | +else | |
| 24 | + if [ ! -f $STRESS_JAR ]; then | |
| 25 | + echo "Cannot find file $STRESS_JAR" 1>&2 | |
| 26 | + exit 1 | |
| 27 | + fi | |
| 28 | +fi | |
| 29 | + | |
| 30 | +"$JAVA" -Dlog4j.configuration="$SCRIPT_DIR/../conf/log4j.properties" -jar $STRESS_JAR $@ |
added driver-tests/stress/pom.xml +109 −0
| @@ -0,0 +1,109 @@ | ||
| 1 | +<!-- | |
| 2 | + | |
| 3 | + Copyright (C) 2012-2015 DataStax Inc. | |
| 4 | + | |
| 5 | + Licensed under the Apache License, Version 2.0 (the "License"); | |
| 6 | + you may not use this file except in compliance with the License. | |
| 7 | + You may obtain a copy of the License at | |
| 8 | + | |
| 9 | + http://www.apache.org/licenses/LICENSE-2.0 | |
| 10 | + | |
| 11 | + Unless required by applicable law or agreed to in writing, software | |
| 12 | + distributed under the License is distributed on an "AS IS" BASIS, | |
| 13 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 14 | + See the License for the specific language governing permissions and | |
| 15 | + limitations under the License. | |
| 16 | + | |
| 17 | +--> | |
| 18 | +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | |
| 19 | + <modelVersion>4.0.0</modelVersion> | |
| 20 | + <parent> | |
| 21 | + <groupId>com.datastax.cassandra</groupId> | |
| 22 | + <artifactId>cassandra-driver-tests-parent</artifactId> | |
| 23 | + <version>3.0.1-SNAPSHOT</version> | |
| 24 | + </parent> | |
| 25 | + <artifactId>cassandra-driver-tests-stress</artifactId> | |
| 26 | + <packaging>jar</packaging> | |
| 27 | + <name>DataStax Java Driver for Apache Cassandra Tests - Stress</name> | |
| 28 | + <description>A stress test example for DataStax Java Driver for Apache Cassandra.</description> | |
| 29 | + <url>https://github.com/datastax/java-driver</url> | |
| 30 | + | |
| 31 | + <properties> | |
| 32 | + <main.basedir>${project.parent.parent.basedir}</main.basedir> | |
| 33 | + </properties> | |
| 34 | + | |
| 35 | + <dependencies> | |
| 36 | + <dependency> | |
| 37 | + <groupId>com.datastax.cassandra</groupId> | |
| 38 | + <artifactId>cassandra-driver-core</artifactId> | |
| 39 | + <version>3.0.1-SNAPSHOT</version> | |
| 40 | + </dependency> | |
| 41 | + | |
| 42 | + <dependency> | |
| 43 | + <groupId>com.yammer.metrics</groupId> | |
| 44 | + <artifactId>metrics-core</artifactId> | |
| 45 | + <version>2.2.0</version> | |
| 46 | + </dependency> | |
| 47 | + | |
| 48 | + <dependency> | |
| 49 | + <groupId>net.sf.jopt-simple</groupId> | |
| 50 | + <artifactId>jopt-simple</artifactId> | |
| 51 | + <version>4.5</version> | |
| 52 | + </dependency> | |
| 53 | + | |
| 54 | + <dependency> | |
| 55 | + <groupId>log4j</groupId> | |
| 56 | + <artifactId>log4j</artifactId> | |
| 57 | + <version>1.2.17</version> | |
| 58 | + </dependency> | |
| 59 | + | |
| 60 | + <dependency> | |
| 61 | + <groupId>org.slf4j</groupId> | |
| 62 | + <artifactId>slf4j-log4j12</artifactId> | |
| 63 | + <version>1.7.5</version> | |
| 64 | + </dependency> | |
| 65 | + </dependencies> | |
| 66 | + | |
| 67 | + <build> | |
| 68 | + <plugins> | |
| 69 | + <plugin> | |
| 70 | + <artifactId>maven-assembly-plugin</artifactId> | |
| 71 | + <version>2.4</version> | |
| 72 | + <configuration> | |
| 73 | + <archive> | |
| 74 | + <manifest> | |
| 75 | + <mainClass>com.datastax.driver.stress.Stress</mainClass> | |
| 76 | + </manifest> | |
| 77 | + </archive> | |
| 78 | + <descriptorRefs> | |
| 79 | + <descriptorRef>jar-with-dependencies</descriptorRef> | |
| 80 | + </descriptorRefs> | |
| 81 | + </configuration> | |
| 82 | + </plugin> | |
| 83 | + </plugins> | |
| 84 | + </build> | |
| 85 | + | |
| 86 | + <licenses> | |
| 87 | + <license> | |
| 88 | + <name>Apache 2</name> | |
| 89 | + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> | |
| 90 | + <distribution>repo</distribution> | |
| 91 | + <comments>Apache License Version 2.0</comments> | |
| 92 | + </license> | |
| 93 | + </licenses> | |
| 94 | + | |
| 95 | + <scm> | |
| 96 | + <connection>scm:git:git@github.com:datastax/java-driver.git</connection> | |
| 97 | + <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection> | |
| 98 | + <url>https://github.com/datastax/java-driver</url> | |
| 99 | + <tag>HEAD</tag> | |
| 100 | + </scm> | |
| 101 | + | |
| 102 | + <developers> | |
| 103 | + <developer> | |
| 104 | + <name>Various</name> | |
| 105 | + <organization>DataStax</organization> | |
| 106 | + </developer> | |
| 107 | + </developers> | |
| 108 | +</project> | |
| 109 | + |
added driver-tests/stress/src/main/java/com/datastax/driver/stress/AsynchronousConsumer.java +98 −0
| @@ -0,0 +1,98 @@ | ||
| 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.stress; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.ResultSet; | |
| 19 | +import com.datastax.driver.core.ResultSetFuture; | |
| 20 | +import com.datastax.driver.core.Session; | |
| 21 | +import com.google.common.util.concurrent.FutureCallback; | |
| 22 | +import com.google.common.util.concurrent.Futures; | |
| 23 | + | |
| 24 | +import java.util.concurrent.CountDownLatch; | |
| 25 | +import java.util.concurrent.ExecutorService; | |
| 26 | +import java.util.concurrent.Executors; | |
| 27 | + | |
| 28 | +import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; | |
| 29 | + | |
| 30 | +public class AsynchronousConsumer implements Consumer { | |
| 31 | + | |
| 32 | + private static final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); | |
| 33 | + | |
| 34 | + private final CountDownLatch shutdownLatch = new CountDownLatch(1); | |
| 35 | + | |
| 36 | + private final Session session; | |
| 37 | + private final QueryGenerator requests; | |
| 38 | + private final Reporter reporter; | |
| 39 | + | |
| 40 | + public AsynchronousConsumer(Session session, | |
| 41 | + QueryGenerator requests, | |
| 42 | + Reporter reporter) { | |
| 43 | + this.session = session; | |
| 44 | + this.requests = requests; | |
| 45 | + this.reporter = reporter; | |
| 46 | + } | |
| 47 | + | |
| 48 | + @Override | |
| 49 | + public void start() { | |
| 50 | + executorService.execute(new Runnable() { | |
| 51 | + @Override | |
| 52 | + public void run() { | |
| 53 | + request(); | |
| 54 | + } | |
| 55 | + }); | |
| 56 | + } | |
| 57 | + | |
| 58 | + private void request() { | |
| 59 | + | |
| 60 | + if (!requests.hasNext()) { | |
| 61 | + shutdown(); | |
| 62 | + return; | |
| 63 | + } | |
| 64 | + | |
| 65 | + handle(requests.next()); | |
| 66 | + } | |
| 67 | + | |
| 68 | + @Override | |
| 69 | + public void join() { | |
| 70 | + awaitUninterruptibly(shutdownLatch); | |
| 71 | + } | |
| 72 | + | |
| 73 | + protected void handle(QueryGenerator.Request request) { | |
| 74 | + | |
| 75 | + final Reporter.Context ctx = reporter.newRequest(); | |
| 76 | + | |
| 77 | + ResultSetFuture resultSetFuture = request.executeAsync(session); | |
| 78 | + Futures.addCallback(resultSetFuture, new FutureCallback<ResultSet>() { | |
| 79 | + @Override | |
| 80 | + public void onSuccess(final ResultSet result) { | |
| 81 | + ctx.done(); | |
| 82 | + request(); | |
| 83 | + } | |
| 84 | + | |
| 85 | + @Override | |
| 86 | + public void onFailure(final Throwable t) { | |
| 87 | + // Could do better I suppose | |
| 88 | + System.err.println("Error during request: " + t); | |
| 89 | + ctx.done(); | |
| 90 | + request(); | |
| 91 | + } | |
| 92 | + }, executorService); | |
| 93 | + } | |
| 94 | + | |
| 95 | + protected void shutdown() { | |
| 96 | + shutdownLatch.countDown(); | |
| 97 | + } | |
| 98 | +} |
added driver-tests/stress/src/main/java/com/datastax/driver/stress/BlockingConsumer.java +74 −0
| @@ -0,0 +1,74 @@ | ||
| 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.stress; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.Session; | |
| 19 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 20 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 21 | + | |
| 22 | +public class BlockingConsumer implements Consumer { | |
| 23 | + | |
| 24 | + private final Runner runner = new Runner(); | |
| 25 | + | |
| 26 | + private final Session session; | |
| 27 | + private final QueryGenerator requests; | |
| 28 | + private final Reporter reporter; | |
| 29 | + | |
| 30 | + public BlockingConsumer(Session session, | |
| 31 | + QueryGenerator requests, | |
| 32 | + Reporter reporter) { | |
| 33 | + this.session = session; | |
| 34 | + this.requests = requests; | |
| 35 | + this.reporter = reporter; | |
| 36 | + this.runner.setDaemon(true); | |
| 37 | + } | |
| 38 | + | |
| 39 | + @Override | |
| 40 | + public void start() { | |
| 41 | + this.runner.start(); | |
| 42 | + } | |
| 43 | + | |
| 44 | + @Override | |
| 45 | + public void join() { | |
| 46 | + Uninterruptibles.joinUninterruptibly(this.runner); | |
| 47 | + } | |
| 48 | + | |
| 49 | + private class Runner extends Thread { | |
| 50 | + | |
| 51 | + public Runner() { | |
| 52 | + super("Consumer Threads"); | |
| 53 | + } | |
| 54 | + | |
| 55 | + @Override | |
| 56 | + public void run() { | |
| 57 | + try { | |
| 58 | + while (requests.hasNext()) | |
| 59 | + handle(requests.next()); | |
| 60 | + } catch (DriverException e) { | |
| 61 | + System.err.println("Error during query: " + e.getMessage()); | |
| 62 | + } | |
| 63 | + } | |
| 64 | + | |
| 65 | + protected void handle(QueryGenerator.Request request) { | |
| 66 | + Reporter.Context ctx = reporter.newRequest(); | |
| 67 | + try { | |
| 68 | + request.execute(session); | |
| 69 | + } finally { | |
| 70 | + ctx.done(); | |
| 71 | + } | |
| 72 | + } | |
| 73 | + } | |
| 74 | +} |
added driver-tests/stress/src/main/java/com/datastax/driver/stress/ConsistencyLevelConverter.java +45 −0
| @@ -0,0 +1,45 @@ | ||
| 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.stress; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | +import joptsimple.ValueConverter; | |
| 20 | + | |
| 21 | +/** | |
| 22 | + * Created by Alram.Lechner on 03.03.2016. | |
| 23 | + */ | |
| 24 | +public class ConsistencyLevelConverter implements ValueConverter<ConsistencyLevel> { | |
| 25 | + | |
| 26 | + @Override | |
| 27 | + public ConsistencyLevel convert(String value) { | |
| 28 | + return ConsistencyLevel.valueOf(value); | |
| 29 | + } | |
| 30 | + | |
| 31 | + @Override | |
| 32 | + public Class<ConsistencyLevel> valueType() { | |
| 33 | + return ConsistencyLevel.class; | |
| 34 | + } | |
| 35 | + | |
| 36 | + @Override | |
| 37 | + public String valuePattern() { | |
| 38 | + StringBuilder pattern = new StringBuilder(); | |
| 39 | + for (ConsistencyLevel level : ConsistencyLevel.values()) { | |
| 40 | + pattern.append("(").append(level.name()).append(")|"); | |
| 41 | + } | |
| 42 | + pattern.setLength(pattern.length() - 1); | |
| 43 | + return pattern.toString(); | |
| 44 | + } | |
| 45 | +} |
added driver-tests/stress/src/main/java/com/datastax/driver/stress/Consumer.java +23 −0
| @@ -0,0 +1,23 @@ | ||
| 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.stress; | |
| 17 | + | |
| 18 | +public interface Consumer { | |
| 19 | + | |
| 20 | + public void start(); | |
| 21 | + | |
| 22 | + public void join(); | |
| 23 | +} |
added driver-tests/stress/src/main/java/com/datastax/driver/stress/Generators.java +227 −0
| @@ -0,0 +1,227 @@ | ||
| 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.stress; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.*; | |
| 19 | +import com.datastax.driver.core.exceptions.QueryValidationException; | |
| 20 | +import com.datastax.driver.core.utils.Bytes; | |
| 21 | +import joptsimple.OptionParser; | |
| 22 | +import joptsimple.OptionSet; | |
| 23 | + | |
| 24 | +import java.nio.ByteBuffer; | |
| 25 | +import java.util.Random; | |
| 26 | + | |
| 27 | +public class Generators { | |
| 28 | + private static ThreadLocal<Random> random = new ThreadLocal<Random>() { | |
| 29 | + @Override | |
| 30 | + protected Random initialValue() { | |
| 31 | + return new Random(); | |
| 32 | + } | |
| 33 | + }; | |
| 34 | + | |
| 35 | + private static ByteBuffer makeValue(final int valueSize) { | |
| 36 | + byte[] value = new byte[valueSize]; | |
| 37 | + random.get().nextBytes(value); | |
| 38 | + return ByteBuffer.wrap(value); | |
| 39 | + } | |
| 40 | + | |
| 41 | + private static abstract class AbstractGenerator extends QueryGenerator { | |
| 42 | + protected int iteration; | |
| 43 | + | |
| 44 | + protected AbstractGenerator(int iterations) { | |
| 45 | + super(iterations); | |
| 46 | + } | |
| 47 | + | |
| 48 | + @Override | |
| 49 | + public int currentIteration() { | |
| 50 | + return iteration; | |
| 51 | + } | |
| 52 | + | |
| 53 | + @Override | |
| 54 | + public boolean hasNext() { | |
| 55 | + return iterations == -1 || iteration < iterations; | |
| 56 | + } | |
| 57 | + | |
| 58 | + @Override | |
| 59 | + public void remove() { | |
| 60 | + throw new UnsupportedOperationException(); | |
| 61 | + } | |
| 62 | + } | |
| 63 | + | |
| 64 | + public static final QueryGenerator.Builder INSERTER = new QueryGenerator.Builder() { | |
| 65 | + | |
| 66 | + @Override | |
| 67 | + public String name() { | |
| 68 | + return "insert"; | |
| 69 | + } | |
| 70 | + | |
| 71 | + @Override | |
| 72 | + public OptionParser addOptions(OptionParser parser) { | |
| 73 | + String msg = "Simple insertion of CQL3 rows (using prepared statements unless the --no-prepare option is used). " | |
| 74 | + + "The inserted rows have a fixed set of columns but no clustering columns."; | |
| 75 | + parser.formatHelpWith(Stress.Help.formatFor(name(), msg)); | |
| 76 | + | |
| 77 | + parser.accepts("no-prepare", "Do no use prepared statement"); | |
| 78 | + parser.accepts("columns-per-row", "Number of columns per CQL3 row").withRequiredArg().ofType(Integer.class).defaultsTo(5); | |
| 79 | + parser.accepts("value-size", "The size in bytes for column values").withRequiredArg().ofType(Integer.class).defaultsTo(34); | |
| 80 | + parser.accepts("with-compact-storage", "Use COMPACT STORAGE on the table used"); | |
| 81 | + return parser; | |
| 82 | + } | |
| 83 | + | |
| 84 | + @Override | |
| 85 | + public void prepare(OptionSet options, Session session) { | |
| 86 | + | |
| 87 | + try { | |
| 88 | + session.execute("DROP KEYSPACE stress;"); | |
| 89 | + } catch (QueryValidationException e) { /* Fine, ignore */ } | |
| 90 | + | |
| 91 | + session.execute("CREATE KEYSPACE stress WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }"); | |
| 92 | + | |
| 93 | + session.execute("USE stress"); | |
| 94 | + | |
| 95 | + StringBuilder sb = new StringBuilder(); | |
| 96 | + sb.append("CREATE TABLE standard1 (key bigint PRIMARY KEY"); | |
| 97 | + for (int i = 0; i < (Integer) options.valueOf("columns-per-row"); ++i) | |
| 98 | + sb.append(", C").append(i).append(" blob"); | |
| 99 | + sb.append(')'); | |
| 100 | + | |
| 101 | + if (options.has("with-compact-storage")) | |
| 102 | + sb.append(" WITH COMPACT STORAGE"); | |
| 103 | + | |
| 104 | + session.execute(sb.toString()); | |
| 105 | + } | |
| 106 | + | |
| 107 | + @Override | |
| 108 | + public QueryGenerator create(int id, int iterations, OptionSet options, Session session) { | |
| 109 | + | |
| 110 | + return options.has("no-prepare") | |
| 111 | + ? createRegular(id, iterations, options, session) | |
| 112 | + : createPrepared(id, iterations, options, session); | |
| 113 | + } | |
| 114 | + | |
| 115 | + public QueryGenerator createRegular(int id, int iterations, OptionSet options, final Session session) { | |
| 116 | + final int valueSize = (Integer) options.valueOf("value-size"); | |
| 117 | + final int columnsPerRow = (Integer) options.valueOf("columns-per-row"); | |
| 118 | + final long prefix = (long) id << 32; | |
| 119 | + | |
| 120 | + return new AbstractGenerator(iterations) { | |
| 121 | + @Override | |
| 122 | + public QueryGenerator.Request next() { | |
| 123 | + StringBuilder sb = new StringBuilder(); | |
| 124 | + sb.append("UPDATE standard1 SET "); | |
| 125 | + for (int i = 0; i < columnsPerRow; ++i) { | |
| 126 | + if (i > 0) sb.append(", "); | |
| 127 | + sb.append('C').append(i).append("='").append(Bytes.toHexString(makeValue(valueSize))).append('\''); | |
| 128 | + } | |
| 129 | + sb.append(" WHERE key = ").append(prefix | iteration); | |
| 130 | + ++iteration; | |
| 131 | + return new QueryGenerator.Request.SimpleQuery(new SimpleStatement(sb.toString())); | |
| 132 | + } | |
| 133 | + }; | |
| 134 | + } | |
| 135 | + | |
| 136 | + public QueryGenerator createPrepared(int id, int iterations, OptionSet options, Session session) { | |
| 137 | + final int valueSize = (Integer) options.valueOf("value-size"); | |
| 138 | + final int columnsPerRow = (Integer) options.valueOf("columns-per-row"); | |
| 139 | + final long prefix = (long) id << 32; | |
| 140 | + | |
| 141 | + StringBuilder sb = new StringBuilder(); | |
| 142 | + sb.append("UPDATE standard1 SET "); | |
| 143 | + for (int i = 0; i < columnsPerRow; ++i) { | |
| 144 | + if (i > 0) sb.append(", "); | |
| 145 | + sb.append('C').append(i).append("=?"); | |
| 146 | + } | |
| 147 | + sb.append(" WHERE key = ?"); | |
| 148 | + | |
| 149 | + final PreparedStatement stmt = session.prepare(sb.toString()); | |
| 150 | + | |
| 151 | + return new AbstractGenerator(iterations) { | |
| 152 | + @Override | |
| 153 | + public QueryGenerator.Request next() { | |
| 154 | + BoundStatement b = stmt.bind(); | |
| 155 | + b.setLong("key", prefix | iteration); | |
| 156 | + for (int i = 0; i < columnsPerRow; ++i) | |
| 157 | + b.setBytes("c" + i, makeValue(valueSize)); | |
| 158 | + ++iteration; | |
| 159 | + return new QueryGenerator.Request.PreparedQuery(b); | |
| 160 | + } | |
| 161 | + }; | |
| 162 | + } | |
| 163 | + }; | |
| 164 | + | |
| 165 | + public static final QueryGenerator.Builder READER = new QueryGenerator.Builder() { | |
| 166 | + | |
| 167 | + @Override | |
| 168 | + public String name() { | |
| 169 | + return "read"; | |
| 170 | + } | |
| 171 | + | |
| 172 | + @Override | |
| 173 | + public OptionParser addOptions(OptionParser parser) { | |
| 174 | + String msg = "Read the rows inserted with the insert generator. Use prepared statements unless the --no-prepare option is used."; | |
| 175 | + parser.formatHelpWith(Stress.Help.formatFor(name(), msg)); | |
| 176 | + | |
| 177 | + parser.accepts("no-prepare", "Do no use prepared statement"); | |
| 178 | + return parser; | |
| 179 | + } | |
| 180 | + | |
| 181 | + @Override | |
| 182 | + public void prepare(OptionSet options, Session session) { | |
| 183 | + KeyspaceMetadata ks = session.getCluster().getMetadata().getKeyspace("stress"); | |
| 184 | + if (ks == null || ks.getTable("standard1") == null) { | |
| 185 | + System.err.println("There is nothing to reads, please run insert/insert_prepared first."); | |
| 186 | + System.exit(1); | |
| 187 | + } | |
| 188 | + | |
| 189 | + session.execute("USE stress"); | |
| 190 | + } | |
| 191 | + | |
| 192 | + @Override | |
| 193 | + public QueryGenerator create(int id, int iterations, OptionSet options, Session session) { | |
| 194 | + return options.has("no-prepare") | |
| 195 | + ? createRegular(id, iterations, session) | |
| 196 | + : createPrepared(id, iterations, session); | |
| 197 | + } | |
| 198 | + | |
| 199 | + public QueryGenerator createRegular(long id, int iterations, final Session session) { | |
| 200 | + final long prefix = (long) id << 32; | |
| 201 | + return new AbstractGenerator(iterations) { | |
| 202 | + @Override | |
| 203 | + public QueryGenerator.Request next() { | |
| 204 | + StringBuilder sb = new StringBuilder(); | |
| 205 | + sb.append("SELECT * FROM standard1 WHERE key = ").append(prefix | iteration); | |
| 206 | + ++iteration; | |
| 207 | + return new QueryGenerator.Request.SimpleQuery(new SimpleStatement(sb.toString())); | |
| 208 | + } | |
| 209 | + }; | |
| 210 | + } | |
| 211 | + | |
| 212 | + public QueryGenerator createPrepared(long id, int iterations, Session session) { | |
| 213 | + final long prefix = (long) id << 32; | |
| 214 | + final PreparedStatement stmt = session.prepare("SELECT * FROM standard1 WHERE key = ?"); | |
| 215 | + | |
| 216 | + return new AbstractGenerator(iterations) { | |
| 217 | + @Override | |
| 218 | + public QueryGenerator.Request next() { | |
| 219 | + BoundStatement bs = stmt.bind(); | |
| 220 | + bs.setLong("key", prefix | iteration); | |
| 221 | + ++iteration; | |
| 222 | + return new QueryGenerator.Request.PreparedQuery(bs); | |
| 223 | + } | |
| 224 | + }; | |
| 225 | + } | |
| 226 | + }; | |
| 227 | +} |
added driver-tests/stress/src/main/java/com/datastax/driver/stress/QueryGenerator.java +92 −0
| @@ -0,0 +1,92 @@ | ||
| 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.stress; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.*; | |
| 19 | +import joptsimple.OptionParser; | |
| 20 | +import joptsimple.OptionSet; | |
| 21 | + | |
| 22 | +import java.util.Iterator; | |
| 23 | + | |
| 24 | +public abstract class QueryGenerator implements Iterator<QueryGenerator.Request> { | |
| 25 | + | |
| 26 | + protected final int iterations; | |
| 27 | + | |
| 28 | + protected QueryGenerator(int iterations) { | |
| 29 | + this.iterations = iterations; | |
| 30 | + } | |
| 31 | + | |
| 32 | + public abstract int currentIteration(); | |
| 33 | + | |
| 34 | + public int totalIterations() { | |
| 35 | + return iterations; | |
| 36 | + } | |
| 37 | + | |
| 38 | + public interface Builder { | |
| 39 | + public String name(); | |
| 40 | + | |
| 41 | + public OptionParser addOptions(OptionParser parser); | |
| 42 | + | |
| 43 | + public void prepare(OptionSet options, Session session); | |
| 44 | + | |
| 45 | + public QueryGenerator create(int id, int iterations, OptionSet options, Session session); | |
| 46 | + } | |
| 47 | + | |
| 48 | + public interface Request { | |
| 49 | + | |
| 50 | + public ResultSet execute(Session session); | |
| 51 | + | |
| 52 | + public ResultSetFuture executeAsync(Session session); | |
| 53 | + | |
| 54 | + public static class SimpleQuery implements Request { | |
| 55 | + | |
| 56 | + private final Statement statement; | |
| 57 | + | |
| 58 | + public SimpleQuery(Statement statement) { | |
| 59 | + this.statement = statement; | |
| 60 | + } | |
| 61 | + | |
| 62 | + @Override | |
| 63 | + public ResultSet execute(Session session) { | |
| 64 | + return session.execute(statement); | |
| 65 | + } | |
| 66 | + | |
| 67 | + @Override | |
| 68 | + public ResultSetFuture executeAsync(Session session) { | |
| 69 | + return session.executeAsync(statement); | |
| 70 | + } | |
| 71 | + } | |
| 72 | + | |
| 73 | + public static class PreparedQuery implements Request { | |
| 74 | + | |
| 75 | + private final BoundStatement query; | |
| 76 | + | |
| 77 | + public PreparedQuery(BoundStatement query) { | |
| 78 | + this.query = query; | |
| 79 | + } | |
| 80 | + | |
| 81 | + @Override | |
| 82 | + public ResultSet execute(Session session) { | |
| 83 | + return session.execute(query); | |
| 84 | + } | |
| 85 | + | |
| 86 | + @Override | |
| 87 | + public ResultSetFuture executeAsync(Session session) { | |
| 88 | + return session.executeAsync(query); | |
| 89 | + } | |
| 90 | + } | |
| 91 | + } | |
| 92 | +} |
added driver-tests/stress/src/main/java/com/datastax/driver/stress/Reporter.java +281 −0
| @@ -0,0 +1,281 @@ | ||
| 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.stress; | |
| 17 | + | |
| 18 | +import com.yammer.metrics.Metrics; | |
| 19 | +import com.yammer.metrics.core.Meter; | |
| 20 | +import com.yammer.metrics.core.Timer; | |
| 21 | +import com.yammer.metrics.core.TimerContext; | |
| 22 | +import com.yammer.metrics.stats.Snapshot; | |
| 23 | + | |
| 24 | +import java.io.File; | |
| 25 | +import java.io.FileOutputStream; | |
| 26 | +import java.io.IOException; | |
| 27 | +import java.io.PrintStream; | |
| 28 | +import java.util.concurrent.Executors; | |
| 29 | +import java.util.concurrent.ScheduledExecutorService; | |
| 30 | +import java.util.concurrent.TimeUnit; | |
| 31 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 32 | + | |
| 33 | +public class Reporter implements Runnable { | |
| 34 | + | |
| 35 | + private Meter requests; | |
| 36 | + private Timer latencies; | |
| 37 | + | |
| 38 | + public Meter requestsMiddle; | |
| 39 | + public Timer latenciesMiddle; | |
| 40 | + | |
| 41 | + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); | |
| 42 | + | |
| 43 | + private final File csvFile; | |
| 44 | + private final String header; | |
| 45 | + private final long period; | |
| 46 | + private final int consoleReportPeriod; | |
| 47 | + private final int iterations; | |
| 48 | + private final AtomicInteger requestsDone = new AtomicInteger(0); | |
| 49 | + | |
| 50 | + private final int middleLowBound; | |
| 51 | + private final int middleHighBound; | |
| 52 | + | |
| 53 | + private volatile double meanMiddleRate = -1.0; | |
| 54 | + | |
| 55 | + private long startTime; | |
| 56 | + private long lastOpCount; | |
| 57 | + | |
| 58 | + private PrintStream csv; | |
| 59 | + | |
| 60 | + private long lastConsoleOpCount; | |
| 61 | + private long lastConsoleTimestamp; | |
| 62 | + private int tickSinceLastConsoleReport; | |
| 63 | + | |
| 64 | + public Reporter(int consoleReportPeriod, String csvFileName, String[] args, int iterations) { | |
| 65 | + this(1, consoleReportPeriod, new File(csvFileName), formatHeader(args), iterations); | |
| 66 | + } | |
| 67 | + | |
| 68 | + private Reporter(int csvPeriod, int consolePeriod, File csvFile, String header, int iterations) { | |
| 69 | + this.period = csvPeriod; | |
| 70 | + this.consoleReportPeriod = consolePeriod / csvPeriod; | |
| 71 | + this.csvFile = csvFile; | |
| 72 | + this.header = header; | |
| 73 | + this.iterations = iterations; | |
| 74 | + | |
| 75 | + // Middle = exclude first and last 10% (note: if requests is -1, we'll end up with negative bounds, which will always exclude. It's fine if we never stop anyway) | |
| 76 | + this.middleLowBound = (int) (0.1 * iterations); | |
| 77 | + this.middleHighBound = (int) (0.9 * iterations); | |
| 78 | + } | |
| 79 | + | |
| 80 | + private static String formatHeader(String[] args) { | |
| 81 | + StringBuilder sb = new StringBuilder(); | |
| 82 | + sb.append("stress"); | |
| 83 | + for (String arg : args) | |
| 84 | + sb.append(' ').append(arg); | |
| 85 | + return sb.toString(); | |
| 86 | + } | |
| 87 | + | |
| 88 | + public void start() { | |
| 89 | + | |
| 90 | + this.requests = Metrics.newMeter(Reporter.class, "requests", "requests", TimeUnit.SECONDS); | |
| 91 | + this.latencies = Metrics.newTimer(Reporter.class, "latencies", TimeUnit.MILLISECONDS, TimeUnit.SECONDS); | |
| 92 | + this.startTime = System.currentTimeMillis(); | |
| 93 | + initConsole(); | |
| 94 | + initCSV(); | |
| 95 | + | |
| 96 | + this.executor.scheduleAtFixedRate(this, period, period, TimeUnit.SECONDS); | |
| 97 | + } | |
| 98 | + | |
| 99 | + public Context newRequest() { | |
| 100 | + int iteration = requestsDone.getAndIncrement(); | |
| 101 | + if (iteration >= middleLowBound) { | |
| 102 | + if (latenciesMiddle == null) { | |
| 103 | + synchronized (this) { | |
| 104 | + if (latenciesMiddle == null) { | |
| 105 | + latenciesMiddle = Metrics.newTimer(Reporter.class, "latencies_middle", TimeUnit.MILLISECONDS, TimeUnit.SECONDS); | |
| 106 | + requestsMiddle = Metrics.newMeter(Reporter.class, "requests_middle", "requests", TimeUnit.SECONDS); | |
| 107 | + } | |
| 108 | + } | |
| 109 | + } | |
| 110 | + if (iteration > middleHighBound) { | |
| 111 | + if (meanMiddleRate < 0) | |
| 112 | + meanMiddleRate = requestsMiddle.meanRate(); | |
| 113 | + | |
| 114 | + return new Context(this, latencies.time(), null); | |
| 115 | + } else { | |
| 116 | + return new Context(this, latencies.time(), latenciesMiddle.time()); | |
| 117 | + } | |
| 118 | + } else { | |
| 119 | + return new Context(this, latencies.time(), null); | |
| 120 | + } | |
| 121 | + } | |
| 122 | + | |
| 123 | + public void stop() { | |
| 124 | + executor.shutdown(); | |
| 125 | + | |
| 126 | + long tstamp = System.currentTimeMillis(); | |
| 127 | + long elapsed = TimeUnit.MILLISECONDS.toSeconds(tstamp - startTime); | |
| 128 | + Report lastReport = new Report(tstamp, elapsed, requests, latencies, lastOpCount); | |
| 129 | + | |
| 130 | + stopCSV(lastReport); | |
| 131 | + stopConsole(lastReport); | |
| 132 | + } | |
| 133 | + | |
| 134 | + @Override | |
| 135 | + public void run() { | |
| 136 | + report(); | |
| 137 | + } | |
| 138 | + | |
| 139 | + private void report() { | |
| 140 | + long tstamp = System.currentTimeMillis(); | |
| 141 | + long elapsed = TimeUnit.MILLISECONDS.toSeconds(tstamp - startTime); | |
| 142 | + | |
| 143 | + Report report = new Report(tstamp, elapsed, requests, latencies, lastOpCount); | |
| 144 | + lastOpCount = report.totalOps; | |
| 145 | + | |
| 146 | + reportToCSV(report); | |
| 147 | + reportToConsole(report); | |
| 148 | + } | |
| 149 | + | |
| 150 | + private void initCSV() { | |
| 151 | + if (csvFile.exists()) | |
| 152 | + if (!csvFile.delete()) | |
| 153 | + throw new RuntimeException("File " + csvFile + " already exists and cannot delete it"); | |
| 154 | + | |
| 155 | + try { | |
| 156 | + if (!csvFile.createNewFile()) | |
| 157 | + throw new RuntimeException("Unable to create report file " + csvFile); | |
| 158 | + | |
| 159 | + csv = new PrintStream(new FileOutputStream(csvFile)); | |
| 160 | + | |
| 161 | + csv.println("# " + header); | |
| 162 | + csv.println("# elapsed,total_ops,interval_rate,mean_rate,mean_latency,95th_latency,99th_latency,std_dev"); | |
| 163 | + | |
| 164 | + } catch (IOException e) { | |
| 165 | + throw new RuntimeException("Error creating report file " + csvFile, e); | |
| 166 | + } | |
| 167 | + } | |
| 168 | + | |
| 169 | + private void reportToCSV(Report report) { | |
| 170 | + csv.println(new StringBuilder() | |
| 171 | + .append(report.elapsed).append(',') | |
| 172 | + .append(report.totalOps).append(',') | |
| 173 | + .append(report.intervalRate).append(',') | |
| 174 | + .append(report.meanRate).append(',') | |
| 175 | + .append(report.meanLatency).append(',') | |
| 176 | + .append(report.latency95th).append(',') | |
| 177 | + .append(report.latency99th).append(',') | |
| 178 | + .append(report.stdDev)); | |
| 179 | + } | |
| 180 | + | |
| 181 | + private void stopCSV(Report lastReport) { | |
| 182 | + reportToCSV(lastReport); | |
| 183 | + } | |
| 184 | + | |
| 185 | + private void initConsole() { | |
| 186 | + this.lastConsoleTimestamp = startTime; | |
| 187 | + | |
| 188 | + System.out.println(" Time (s) | total ops | interval rate | mean rate | mean latency (ms) | 95th latency (ms) | 99th latency (ms) | std dev"); | |
| 189 | + System.out.println("--------------------------------------------------------------------------------------------------------------------------------"); | |
| 190 | + } | |
| 191 | + | |
| 192 | + private void reportToConsole(Report report) { | |
| 193 | + | |
| 194 | + if (++tickSinceLastConsoleReport < consoleReportPeriod) | |
| 195 | + return; | |
| 196 | + | |
| 197 | + printReportToConsole(report); | |
| 198 | + | |
| 199 | + tickSinceLastConsoleReport = 0; | |
| 200 | + lastConsoleTimestamp = report.timestamp; | |
| 201 | + lastConsoleOpCount = report.totalOps; | |
| 202 | + } | |
| 203 | + | |
| 204 | + private void printReportToConsole(Report report) { | |
| 205 | + long delay = report.timestamp - lastConsoleTimestamp; | |
| 206 | + double intervalRate = (((double) (report.totalOps - lastConsoleOpCount)) / delay) * 1000; | |
| 207 | + | |
| 208 | + String msg = String.format(" %8d | %12d | %13.2f | %12.2f | %17.3f | %17.3f | %17.3f | %9.3f", | |
| 209 | + report.elapsed, report.totalOps, intervalRate, report.meanRate, report.meanLatency, report.latency95th, report.latency99th, report.stdDev); | |
| 210 | + System.out.println(msg); | |
| 211 | + } | |
| 212 | + | |
| 213 | + private void stopConsole(Report lastReport) { | |
| 214 | + printReportToConsole(lastReport); | |
| 215 | + | |
| 216 | + if (latenciesMiddle == null) | |
| 217 | + return; | |
| 218 | + | |
| 219 | + Snapshot snapshot = latenciesMiddle.getSnapshot(); | |
| 220 | + | |
| 221 | + System.out.println(); | |
| 222 | + System.out.println("For the middle 80% of values:"); | |
| 223 | + System.out.println(String.format(" Mean rate (ops/sec): %10.1f", meanMiddleRate)); | |
| 224 | + System.out.println(String.format(" Mean latency (ms): %10.3f", latenciesMiddle.mean())); | |
| 225 | + System.out.println(String.format(" Median latency (ms): %10.3f", snapshot.getMedian())); | |
| 226 | + System.out.println(String.format(" 75th percentile latency (ms): %10.3f", snapshot.get75thPercentile())); | |
| 227 | + System.out.println(String.format(" 95th percentile latency (ms): %10.3f", snapshot.get95thPercentile())); | |
| 228 | + System.out.println(String.format(" 99th percentile latency (ms): %10.3f", snapshot.get99thPercentile())); | |
| 229 | + System.out.println(String.format(" Standard latency deviation: %10.3f", latenciesMiddle.stdDev())); | |
| 230 | + } | |
| 231 | + | |
| 232 | + private static class Report { | |
| 233 | + public final long timestamp; | |
| 234 | + public final long elapsed; | |
| 235 | + | |
| 236 | + public final long totalOps; | |
| 237 | + public final long intervalRate; | |
| 238 | + public final double meanRate; | |
| 239 | + | |
| 240 | + public final double meanLatency; | |
| 241 | + public final double latency95th; | |
| 242 | + public final double latency99th; | |
| 243 | + public final double stdDev; | |
| 244 | + | |
| 245 | + public Report(long timestamp, long elapsed, Meter meter, Timer timer, long lastOpCount) { | |
| 246 | + this.timestamp = timestamp; | |
| 247 | + this.elapsed = elapsed; | |
| 248 | + | |
| 249 | + this.totalOps = meter.count(); | |
| 250 | + this.intervalRate = totalOps - lastOpCount; | |
| 251 | + this.meanRate = meter.meanRate(); | |
| 252 | + | |
| 253 | + Snapshot snapshot = timer.getSnapshot(); | |
| 254 | + this.meanLatency = timer.mean(); | |
| 255 | + this.latency95th = snapshot.get95thPercentile(); | |
| 256 | + this.latency99th = snapshot.get99thPercentile(); | |
| 257 | + this.stdDev = timer.stdDev(); | |
| 258 | + } | |
| 259 | + } | |
| 260 | + | |
| 261 | + public static class Context { | |
| 262 | + private final Reporter reporter; | |
| 263 | + private final TimerContext context; | |
| 264 | + private final TimerContext contextMiddle; | |
| 265 | + | |
| 266 | + private Context(Reporter reporter, TimerContext context, TimerContext contextMiddle) { | |
| 267 | + this.reporter = reporter; | |
| 268 | + this.context = context; | |
| 269 | + this.contextMiddle = contextMiddle; | |
| 270 | + } | |
| 271 | + | |
| 272 | + public void done() { | |
| 273 | + context.stop(); | |
| 274 | + reporter.requests.mark(); | |
| 275 | + if (contextMiddle != null) { | |
| 276 | + contextMiddle.stop(); | |
| 277 | + reporter.requestsMiddle.mark(); | |
| 278 | + } | |
| 279 | + } | |
| 280 | + } | |
| 281 | +} |
added driver-tests/stress/src/main/java/com/datastax/driver/stress/Stress.java +285 −0
| @@ -0,0 +1,285 @@ | ||
| 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.stress; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.*; | |
| 19 | +import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 20 | +import joptsimple.*; | |
| 21 | +import org.apache.log4j.PropertyConfigurator; | |
| 22 | + | |
| 23 | +import java.io.IOException; | |
| 24 | +import java.util.HashMap; | |
| 25 | +import java.util.List; | |
| 26 | +import java.util.Map; | |
| 27 | + | |
| 28 | +/** | |
| 29 | + * A simple stress tool to demonstrate the use of the driver. | |
| 30 | + * <p/> | |
| 31 | + * Sample usage: | |
| 32 | + * stress insert -n 100000 | |
| 33 | + * stress read -n 10000 | |
| 34 | + */ | |
| 35 | +public class Stress { | |
| 36 | + | |
| 37 | + private static final Map<String, QueryGenerator.Builder> generators = new HashMap<String, QueryGenerator.Builder>(); | |
| 38 | + | |
| 39 | + static { | |
| 40 | + PropertyConfigurator.configure(System.getProperty("log4j.configuration", "./conf/log4j.properties")); | |
| 41 | + | |
| 42 | + QueryGenerator.Builder[] gs = new QueryGenerator.Builder[]{ | |
| 43 | + Generators.INSERTER, | |
| 44 | + Generators.READER | |
| 45 | + }; | |
| 46 | + | |
| 47 | + for (QueryGenerator.Builder b : gs) | |
| 48 | + register(b.name(), b); | |
| 49 | + } | |
| 50 | + | |
| 51 | + private static OptionParser defaultParser() { | |
| 52 | + OptionParser parser = new OptionParser() {{ | |
| 53 | + accepts("h", "Show this help message"); | |
| 54 | + accepts("n", "Number of requests to perform (default: unlimited)").withRequiredArg().ofType(Integer.class); | |
| 55 | + accepts("t", "Level of concurrency to use").withRequiredArg().ofType(Integer.class).defaultsTo(50); | |
| 56 | + accepts("async", "Make asynchronous requests instead of blocking ones"); | |
| 57 | + accepts("ip", "The hosts ip to connect to").withRequiredArg().ofType(String.class).defaultsTo("127.0.0.1"); | |
| 58 | + accepts("report-file", "The name of csv file to use for reporting results").withRequiredArg().ofType(String.class).defaultsTo("last.csv"); | |
| 59 | + accepts("print-delay", "The delay in seconds at which to report on the console").withRequiredArg().ofType(Integer.class).defaultsTo(5); | |
| 60 | + accepts("compression", "Use compression (SNAPPY)"); | |
| 61 | + accepts("connections-per-host", "The number of connections per hosts (default: based on the number of threads)").withRequiredArg().ofType(Integer.class); | |
| 62 | + accepts("consistency-level", "Consistency level").withRequiredArg().withValuesConvertedBy(new ConsistencyLevelConverter()) | |
| 63 | + .ofType(ConsistencyLevel.class).defaultsTo(ConsistencyLevel.LOCAL_ONE); | |
| 64 | + }}; | |
| 65 | + String msg = "Where <generator> can be one of " + generators.keySet() + '\n' | |
| 66 | + + "You can get more help on a particular generator with: stress <generator> -h"; | |
| 67 | + parser.formatHelpWith(Help.formatFor("<generator>", msg)); | |
| 68 | + return parser; | |
| 69 | + } | |
| 70 | + | |
| 71 | + public static void register(String name, QueryGenerator.Builder generator) { | |
| 72 | + if (generators.containsKey(name)) | |
| 73 | + throw new IllegalStateException("There is already a generator registered with the name " + name); | |
| 74 | + | |
| 75 | + generators.put(name, generator); | |
| 76 | + } | |
| 77 | + | |
| 78 | + private static class Stresser { | |
| 79 | + private final QueryGenerator.Builder genBuilder; | |
| 80 | + private final OptionParser parser; | |
| 81 | + private final OptionSet options; | |
| 82 | + | |
| 83 | + private Stresser(QueryGenerator.Builder genBuilder, OptionParser parser, OptionSet options) { | |
| 84 | + this.genBuilder = genBuilder; | |
| 85 | + this.parser = parser; | |
| 86 | + this.options = options; | |
| 87 | + } | |
| 88 | + | |
| 89 | + public static Stresser forCommandLineArguments(String[] args) { | |
| 90 | + OptionParser parser = defaultParser(); | |
| 91 | + | |
| 92 | + String generatorName = findPotentialGenerator(args); | |
| 93 | + if (generatorName == null) { | |
| 94 | + // Still parse the options to handle -h | |
| 95 | + OptionSet options = parseOptions(parser, args); | |
| 96 | + System.err.println("Missing generator, you need to provide a generator."); | |
| 97 | + printHelp(parser); | |
| 98 | + System.exit(1); | |
| 99 | + } | |
| 100 | + | |
| 101 | + if (!generators.containsKey(generatorName)) { | |
| 102 | + System.err.println(String.format("Unknown generator '%s'", generatorName)); | |
| 103 | + printHelp(parser); | |
| 104 | + System.exit(1); | |
| 105 | + } | |
| 106 | + | |
| 107 | + QueryGenerator.Builder genBuilder = generators.get(generatorName); | |
| 108 | + parser = genBuilder.addOptions(parser); | |
| 109 | + OptionSet options = parseOptions(parser, args); | |
| 110 | + | |
| 111 | + List<?> nonOpts = options.nonOptionArguments(); | |
| 112 | + if (nonOpts.size() > 1) { | |
| 113 | + System.err.println("Too many generators provided. Got " + nonOpts + " but only one generator supported."); | |
| 114 | + printHelp(parser); | |
| 115 | + System.exit(1); | |
| 116 | + } | |
| 117 | + | |
| 118 | + return new Stresser(genBuilder, parser, options); | |
| 119 | + } | |
| 120 | + | |
| 121 | + private static String findPotentialGenerator(String[] args) { | |
| 122 | + for (String arg : args) | |
| 123 | + if (!arg.startsWith("-")) | |
| 124 | + return arg; | |
| 125 | + | |
| 126 | + return null; | |
| 127 | + } | |
| 128 | + | |
| 129 | + private static OptionSet parseOptions(OptionParser parser, String[] args) { | |
| 130 | + try { | |
| 131 | + OptionSet options = parser.parse(args); | |
| 132 | + if (options.has("h")) { | |
| 133 | + printHelp(parser); | |
| 134 | + System.exit(0); | |
| 135 | + } | |
| 136 | + return options; | |
| 137 | + } catch (Exception e) { | |
| 138 | + System.err.println("Error parsing options: " + e.getMessage()); | |
| 139 | + printHelp(parser); | |
| 140 | + System.exit(1); | |
| 141 | + throw new AssertionError(); | |
| 142 | + } | |
| 143 | + } | |
| 144 | + | |
| 145 | + private static void printHelp(OptionParser parser) { | |
| 146 | + try { | |
| 147 | + parser.printHelpOn(System.out); | |
| 148 | + } catch (IOException e) { | |
| 149 | + throw new AssertionError(e); | |
| 150 | + } | |
| 151 | + } | |
| 152 | + | |
| 153 | + public OptionSet getOptions() { | |
| 154 | + return options; | |
| 155 | + } | |
| 156 | + | |
| 157 | + public void prepare(Session session) { | |
| 158 | + genBuilder.prepare(options, session); | |
| 159 | + } | |
| 160 | + | |
| 161 | + public QueryGenerator newGenerator(int id, Session session, int iterations) { | |
| 162 | + return genBuilder.create(id, iterations, options, session); | |
| 163 | + } | |
| 164 | + } | |
| 165 | + | |
| 166 | + public static class Help implements HelpFormatter { | |
| 167 | + | |
| 168 | + private final HelpFormatter defaultFormatter; | |
| 169 | + private final String generator; | |
| 170 | + private final String header; | |
| 171 | + | |
| 172 | + private Help(HelpFormatter defaultFormatter, String generator, String header) { | |
| 173 | + this.defaultFormatter = defaultFormatter; | |
| 174 | + this.generator = generator; | |
| 175 | + this.header = header; | |
| 176 | + } | |
| 177 | + | |
| 178 | + public static Help formatFor(String generator, String header) { | |
| 179 | + // It's a pain in the ass to get the real console width in JAVA so hardcode it. But it's the 21th | |
| 180 | + // century, we're not stuck at 80 characters anymore. | |
| 181 | + int width = 120; | |
| 182 | + return new Help(new BuiltinHelpFormatter(width, 4), generator, header); | |
| 183 | + } | |
| 184 | + | |
| 185 | + @Override | |
| 186 | + public String format(Map<String, ? extends OptionDescriptor> options) { | |
| 187 | + StringBuilder sb = new StringBuilder(); | |
| 188 | + | |
| 189 | + sb.append("Usage: stress ").append(generator).append(" [<option>]*").append("\n\n"); | |
| 190 | + sb.append(header).append("\n\n"); | |
| 191 | + sb.append(defaultFormatter.format(options)); | |
| 192 | + return sb.toString(); | |
| 193 | + } | |
| 194 | + } | |
| 195 | + | |
| 196 | + public static void main(String[] args) throws Exception { | |
| 197 | + | |
| 198 | + Stresser stresser = Stresser.forCommandLineArguments(args); | |
| 199 | + OptionSet options = stresser.getOptions(); | |
| 200 | + | |
| 201 | + int requests = options.has("n") ? (Integer) options.valueOf("n") : -1; | |
| 202 | + int concurrency = (Integer) options.valueOf("t"); | |
| 203 | + ConsistencyLevel consistencyLevel = (ConsistencyLevel) options.valueOf("consistency-level"); | |
| 204 | + | |
| 205 | + String reportFileName = (String) options.valueOf("report-file"); | |
| 206 | + | |
| 207 | + boolean async = options.has("async"); | |
| 208 | + | |
| 209 | + int iterations = (requests == -1 ? -1 : requests / concurrency); | |
| 210 | + | |
| 211 | + final int maxRequestsPerConnection = 128; | |
| 212 | + int maxConnections = options.has("connections-per-host") | |
| 213 | + ? (Integer) options.valueOf("connections-per-host") | |
| 214 | + : concurrency / maxRequestsPerConnection + 1; | |
| 215 | + | |
| 216 | + PoolingOptions pools = new PoolingOptions(); | |
| 217 | + pools.setNewConnectionThreshold(HostDistance.LOCAL, concurrency); | |
| 218 | + pools.setCoreConnectionsPerHost(HostDistance.LOCAL, maxConnections); | |
| 219 | + pools.setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections); | |
| 220 | + pools.setCoreConnectionsPerHost(HostDistance.REMOTE, maxConnections); | |
| 221 | + pools.setMaxConnectionsPerHost(HostDistance.REMOTE, maxConnections); | |
| 222 | + | |
| 223 | + System.out.println("Initializing stress test:"); | |
| 224 | + System.out.println(" request count: " + (requests == -1 ? "unlimited" : requests)); | |
| 225 | + System.out.println(" concurrency: " + concurrency + " (" + iterations + " requests/thread)"); | |
| 226 | + System.out.println(" mode: " + (async ? "asynchronous" : "blocking")); | |
| 227 | + System.out.println(" per-host connections: " + maxConnections); | |
| 228 | + System.out.println(" compression: " + options.has("compression")); | |
| 229 | + System.out.println(" consistency-level: " + consistencyLevel.name()); | |
| 230 | + | |
| 231 | + try { | |
| 232 | + // Create session to hosts | |
| 233 | + Cluster cluster = new Cluster.Builder() | |
| 234 | + .addContactPoints(String.valueOf(options.valueOf("ip"))) | |
| 235 | + .withPoolingOptions(pools) | |
| 236 | + .withSocketOptions(new SocketOptions().setTcpNoDelay(true)) | |
| 237 | + .withQueryOptions(new QueryOptions().setConsistencyLevel(consistencyLevel)) | |
| 238 | + .build(); | |
| 239 | + | |
| 240 | + if (options.has("compression")) | |
| 241 | + cluster.getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.SNAPPY); | |
| 242 | + | |
| 243 | + Session session = cluster.connect(); | |
| 244 | + | |
| 245 | + Metadata metadata = cluster.getMetadata(); | |
| 246 | + System.out.println(String.format("Connected to cluster '%s' on %s.", metadata.getClusterName(), metadata.getAllHosts())); | |
| 247 | + | |
| 248 | + System.out.println("Preparing test..."); | |
| 249 | + stresser.prepare(session); | |
| 250 | + | |
| 251 | + Reporter reporter = new Reporter((Integer) options.valueOf("print-delay"), reportFileName, args, requests); | |
| 252 | + | |
| 253 | + Consumer[] consumers = new Consumer[concurrency]; | |
| 254 | + for (int i = 0; i < concurrency; i++) { | |
| 255 | + QueryGenerator generator = stresser.newGenerator(i, session, iterations); | |
| 256 | + consumers[i] = async ? new AsynchronousConsumer(session, generator, reporter) : | |
| 257 | + new BlockingConsumer(session, generator, reporter); | |
| 258 | + } | |
| 259 | + | |
| 260 | + System.out.println("Starting to stress test..."); | |
| 261 | + System.out.println(); | |
| 262 | + | |
| 263 | + reporter.start(); | |
| 264 | + | |
| 265 | + for (Consumer consumer : consumers) | |
| 266 | + consumer.start(); | |
| 267 | + | |
| 268 | + for (Consumer consumer : consumers) | |
| 269 | + consumer.join(); | |
| 270 | + | |
| 271 | + reporter.stop(); | |
| 272 | + | |
| 273 | + System.out.println("Stress test successful."); | |
| 274 | + System.exit(0); | |
| 275 | + | |
| 276 | + } catch (NoHostAvailableException e) { | |
| 277 | + System.err.println("No alive hosts to use: " + e.getMessage()); | |
| 278 | + System.exit(1); | |
| 279 | + } catch (Exception e) { | |
| 280 | + System.err.println("Unexpected error: " + e.getMessage()); | |
| 281 | + e.printStackTrace(); | |
| 282 | + System.exit(1); | |
| 283 | + } | |
| 284 | + } | |
| 285 | +} |
modified faq/README.md +137 −0
| @@ -10,3 +10,140 @@ | ||
| 10 | 10 | Native protocol v1 does not support paging, but you can emulate it in |
| 11 | 11 | CQL with `LIMIT` and the `token()` function. See |
| 12 | 12 | [this conversation](https://groups.google.com/a/lists.datastax.com/d/msg/java-driver-user/U2KzAHruWO4/6vDmUVDDkOwJ) on the mailing list. |
| 13 | + | |
| 14 | + | |
| 15 | +### Can I check if a conditional statement (lightweight transaction) was successful? | |
| 16 | + | |
| 17 | +When executing a conditional statement, the `ResultSet` will contain a single `Row` with a | |
| 18 | +column named "applied" of type boolean. This tells whether the conditional statement was | |
| 19 | +successful or not. | |
| 20 | + | |
| 21 | +The driver provides a convenience method [wasApplied] to check this on the result set directly: | |
| 22 | + | |
| 23 | +```java | |
| 24 | +ResultSet rset = session.execute(conditionalStatement); | |
| 25 | +rset.wasApplied(); | |
| 26 | +``` | |
| 27 | + | |
| 28 | +You may also inspect the value yourself: | |
| 29 | + | |
| 30 | +```java | |
| 31 | +ResultSet rset = session.execute(conditionalStatement); | |
| 32 | +Row row = rset.one(); | |
| 33 | +row.getBool(0); // this is equivalent row.getBool("applied") | |
| 34 | +``` | |
| 35 | + | |
| 36 | +Note that, unlike manual inspection, `wasApplied` does not consume the first row. | |
| 37 | + | |
| 38 | +[wasApplied]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html#wasApplied-- | |
| 39 | + | |
| 40 | + | |
| 41 | +### What is a parameterized statement and how can I use it? | |
| 42 | + | |
| 43 | +Starting with Cassandra 2.0, normal statements (that is non-prepared statements) do | |
| 44 | +not need to concatenate parameter values inside a query string. Instead you can use | |
| 45 | +`?` markers and provide the values separately: | |
| 46 | + | |
| 47 | +```java | |
| 48 | +session.execute( "INSERT INTO contacts (email, firstname, lastname) | |
| 49 | + VALUES (?, ?, ?)", "clint.barton@hawkeye.com", "Barney", "Barton"); | |
| 50 | +``` | |
| 51 | + | |
| 52 | +See [Simple statements](../manual/statements/simple/) for more information. | |
| 53 | + | |
| 54 | + | |
| 55 | +### Does a parameterized statement escape parameters? | |
| 56 | + | |
| 57 | +A parameterized statement sends the values of parameters separate from the query | |
| 58 | +(similar to the way a prepared statement does) as bytes so there is no need to escape | |
| 59 | +parameters. | |
| 60 | + | |
| 61 | + | |
| 62 | +### What's the difference between a parameterized statement and a Prepared statement? | |
| 63 | + | |
| 64 | +The only similarity between a parameterized statement and a prepared statement is in | |
| 65 | +the way that the parameters are sent. The difference is that a prepared statement: | |
| 66 | + | |
| 67 | +* is already known on the cluster side (it has been compiled and there is an execution | |
| 68 | + plan available for it) which leads to better performance | |
| 69 | +* sends only the statement id and its parameters (thus reducing the amount of data sent | |
| 70 | + to the cluster) | |
| 71 | + | |
| 72 | +See [Prepared statements](../manual/statements/prepared/) for more information. | |
| 73 | + | |
| 74 | + | |
| 75 | +### Can I combine `PreparedStatements` and normal statements in a batch? | |
| 76 | + | |
| 77 | +Yes. A batch can include both bound statements and simple statements: | |
| 78 | + | |
| 79 | +```java | |
| 80 | +PreparedStatement ps = session.prepare( "INSERT INTO contacts (email, firstname, lastname) | |
| 81 | + VALUES (?, ?, ?)"); | |
| 82 | +BatchStatement batch = new BatchStatement(); | |
| 83 | +batch.add(ps.bind(...)); | |
| 84 | +batch.add(ps.bind(...)); | |
| 85 | +// here's a simple statement | |
| 86 | +batch.add(new SimpleStatement( "INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)", ...)); | |
| 87 | +session.execute(batch); | |
| 88 | +``` | |
| 89 | + | |
| 90 | + | |
| 91 | +### Can I get the raw bytes of a text column? | |
| 92 | + | |
| 93 | +If you need to access the raw bytes of a text column, call the | |
| 94 | +`Row.getBytesUnsafe("columnName")` method. | |
| 95 | + | |
| 96 | +Trying to use `Row.getBytes("columnName")` for the same purpose results in an | |
| 97 | +exception, as the `getBytes` method can only be used if the column has the CQL type `BLOB`. | |
| 98 | + | |
| 99 | + | |
| 100 | +### How do I increment counters with `QueryBuilder`? | |
| 101 | + | |
| 102 | +Considering the following query: | |
| 103 | + | |
| 104 | +```java | |
| 105 | +UPDATE clickstream SET clicks = clicks + 1 WHERE userid = id; | |
| 106 | +``` | |
| 107 | + | |
| 108 | +To do this using `QueryBuilder`: | |
| 109 | + | |
| 110 | +```java | |
| 111 | +Statement query = QueryBuilder.update("clickstream") | |
| 112 | + .with(incr("clicks", 1)) // Use incr for counters | |
| 113 | + .where(eq("userid", id)); | |
| 114 | +``` | |
| 115 | + | |
| 116 | + | |
| 117 | +### Is there a way to control the batch size of the results returned from a query? | |
| 118 | + | |
| 119 | +Use the `setFetchSize()` method on your `Statement` object. The fetch size controls | |
| 120 | +how many resulting rows are retrieved simultaneously (the goal being to avoid | |
| 121 | +loading too many results in memory for queries yielding large result sets). | |
| 122 | + | |
| 123 | +Keep in mind that if your code iterates the `ResultSet` entirely, the driver may | |
| 124 | +run additional background queries to fetch the rest of the data. The fetch size | |
| 125 | +only affects what is retrieved at a time, not the overall number of rows. | |
| 126 | + | |
| 127 | +See [Paging](../manual/paging/) for more information. | |
| 128 | + | |
| 129 | + | |
| 130 | +### What's the difference between using `setFetchSize()` and `LIMIT`? | |
| 131 | + | |
| 132 | +Basically, `LIMIT` controls the maximum number of results returned by the query, | |
| 133 | +while the `setFetchSize()` method controls the amount of data transferred at a time. | |
| 134 | + | |
| 135 | +For example, if you limit is 30 and your fetch size is 10, the `ResultSet` will contain | |
| 136 | +30 rows, but under the hood the driver will perform 3 requests that will transfer 10 | |
| 137 | +rows each. | |
| 138 | + | |
| 139 | +See [Paging](../manual/paging/) for more information. | |
| 140 | + | |
| 141 | + | |
| 142 | +### I'm reading a BLOB column and the driver returns incorrect data. | |
| 143 | + | |
| 144 | +Check your code to ensure that you read the returned `ByteBuffer` correctly. `ByteBuffer` is a very error-prone API, | |
| 145 | +and we've had many reports where the problem turned out to be in user code. | |
| 146 | + | |
| 147 | +See [Blobs.java] in the `driver-examples` module for some examples and explanations. | |
| 148 | + | |
| 149 | +[Blobs.java]: https://github.com/datastax/java-driver/tree/3.0/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java | |
| No newline at the end of the file |
modified manual/address_resolution/README.md +76 −24
| @@ -1,19 +1,61 @@ | ||
| 1 | 1 | ## Address resolution |
| 2 | 2 | |
| 3 | -The driver auto-detects new Cassandra nodes added to the cluster through server | |
| 4 | -side push notifications and through checking the system tables. | |
| 3 | +Each node in the Cassandra cluster is uniquely identified by an IP address that the driver will use to establish | |
| 4 | +connections. | |
| 5 | 5 | |
| 6 | -For each node, the address the driver will receive will correspond to the address set as | |
| 7 | -`rpc_address` in the node's `cassandra.yaml` file. In most cases, this is the correct value. | |
| 8 | -However, sometimes the addresses received through this mechanism will either not be | |
| 9 | -reachable directly by the driver, or should not be the preferred address to use | |
| 10 | -(for instance, it might be a private IP, but some clients may have to use a public IP, or | |
| 11 | -go through a router). | |
| 6 | +* for contact points, these are provided as part of configuring the `Cluster` object; | |
| 7 | +* for other nodes, addresses will be discovered dynamically, either by inspecting `system.peers` on already connected | |
| 8 | + nodes, or via push notifications received from the [control host](../control_connection) when new nodes are discovered | |
| 9 | + by gossip. | |
| 12 | 10 | |
| 13 | -### The [AddressTranslator][at] interface | |
| 14 | 11 | |
| 15 | -This interface allows you to deal with such cases, by transforming the address sent by a | |
| 16 | -Cassandra node to another address to be used by the driver for connection. | |
| 12 | +### Cassandra-side configuration | |
| 13 | + | |
| 14 | +The address that each Cassandra node shares with clients is the **broadcast RPC address**; it is controlled by various | |
| 15 | +properties in [cassandra.yaml]: | |
| 16 | + | |
| 17 | +* [rpc_address] or [rpc_interface] is the address that the Cassandra process *binds to*. You must set one or the other, | |
| 18 | + not both (for more details, see the inline comments in the default `cassandra.yaml` that came with your installation); | |
| 19 | +* [broadcast_rpc_address] \(introduced in Cassandra 2.1) is the address to share with clients, if it is different than | |
| 20 | + the previous one (the reason for having a separate property is if the bind address is not public to clients, because | |
| 21 | + there is a router in between). | |
| 22 | + | |
| 23 | +If `broadcast_rpc_address` is not set, it defaults to `rpc_address`/`rpc_interface`. If `rpc_address`/`rpc_interface` | |
| 24 | +is 0.0.0.0 (all interfaces), then `broadcast_rpc_address` *must* be set. | |
| 25 | + | |
| 26 | +If you're not sure which address a Cassandra node is broadcasting, launch cqlsh locally on the node, execute the | |
| 27 | +following query and take node of the result: | |
| 28 | + | |
| 29 | +``` | |
| 30 | +cqlsh> select broadcast_address from system.local; | |
| 31 | + | |
| 32 | + broadcast_address | |
| 33 | +------------------- | |
| 34 | + 172.1.2.3 | |
| 35 | +``` | |
| 36 | + | |
| 37 | +Then connect to *another* node in the cluster and run the following query, injecting the previous result: | |
| 38 | + | |
| 39 | +``` | |
| 40 | +cqlsh> select rpc_address from system.peers where peer = '172.1.2.3'; | |
| 41 | + | |
| 42 | + rpc_address | |
| 43 | +------------- | |
| 44 | + 1.2.3.4 | |
| 45 | +``` | |
| 46 | + | |
| 47 | +That last result is the broadcast RPC address. Ensure that it is accessible from the client machine where the driver | |
| 48 | +will run. | |
| 49 | + | |
| 50 | + | |
| 51 | +### Driver-side address translation | |
| 52 | + | |
| 53 | +Sometimes it's not possible for Cassandra nodes to broadcast addresses that will work for each and every client; for | |
| 54 | +instance, they might broadcast private IPs because most clients are in the same network, but a particular client could | |
| 55 | +be on another network and go through a router. | |
| 56 | + | |
| 57 | +For such cases, you can register a driver-side component that will perform additional address translation. Write a class | |
| 58 | +that implements [AddressTranslator] and register an instance with your `Cluster`: | |
| 17 | 59 | |
| 18 | 60 | ```java |
| 19 | 61 | public class MyAddressTranslator implements AddressTranslator { |
| @@ -31,19 +73,15 @@ | ||
| 31 | 73 | Note: the contact points provided while creating the `Cluster` are not translated, only |
| 32 | 74 | addresses retrieved from or sent by Cassandra nodes are. |
| 33 | 75 | |
| 34 | -[at]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/AddressTranslator.html | |
| 35 | - | |
| 36 | 76 | ### EC2 multi-region |
| 37 | 77 | |
| 38 | -[EC2MultiRegionAddressTranslator][ec2] is provided out of the box. It | |
| 39 | -helps optimize network costs when your infrastructure (both Cassandra | |
| 40 | -nodes *and* clients) is distributed across multiple Amazon EC2 regions: | |
| 78 | +If you deploy both Cassandra and client applications on Amazon EC2, and your cluster spans multiple regions, you'll have | |
| 79 | +to configure your Cassandra nodes to broadcast public RPC addresses. | |
| 41 | 80 | |
| 42 | -* a client communicating with a Cassandra node *in the same EC2 region* should use the node's | |
| 43 | - private IP (which is less expensive); | |
| 44 | -* a client communicating with a node in a different region should use the public IP. | |
| 81 | +However, this is not always the most cost-effective: if a client and a node are in the same region, it would be cheaper | |
| 82 | +to connect over the private IP. Ideally, you'd want to pick the best address in each case. | |
| 45 | 83 | |
| 46 | -To use this implementation, provide an instance when initializing the `Cluster`: | |
| 84 | +The driver provides an address translator that does just that: [EC2MultiRegionAddressTranslator]. | |
| 47 | 85 | |
| 48 | 86 | ```java |
| 49 | 87 | Cluster cluster = Cluster.builder() |
| @@ -52,8 +90,22 @@ | ||
| 52 | 90 | .build(); |
| 53 | 91 | ``` |
| 54 | 92 | |
| 55 | -This class performs a reverse DNS lookup of the origin address, to find the domain name of the | |
| 56 | -target instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the | |
| 57 | -private/public switch automatically based on location. | |
| 93 | +With this configuration, you keep broadcasting public RPC addresses. But each time the driver connects to a new | |
| 94 | +Cassandra node: | |
| 95 | + | |
| 96 | +* if the node is *in the same EC2 region*, the public IP will be translated to the intra-region private IP; | |
| 97 | +* otherwise, it will not be translated. | |
| 98 | + | |
| 99 | +(To achieve this, `EC2MultiRegionAddressTranslator` performs a reverse DNS lookup of the origin address, to find the | |
| 100 | +domain name of the target instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the | |
| 101 | +private/public switch automatically based on location). | |
| 102 | + | |
| 103 | + | |
| 104 | + | |
| 105 | +[AddressTranslator]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/AddressTranslator.html | |
| 106 | +[EC2MultiRegionAddressTranslator]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.html | |
| 58 | 107 | |
| 59 | -[ec2]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.html | |
| 108 | +[cassandra.yaml]: https://docs.datastax.com/en/cassandra/3.x/cassandra/configuration/configCassandra_yaml.html | |
| 109 | +[rpc_address]: https://docs.datastax.com/en/cassandra/3.x/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__rpc_address | |
| 110 | +[rpc_interface]: https://docs.datastax.com/en/cassandra/3.x/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__rpc_interface | |
| 111 | +[broadcast_rpc_address]: https://docs.datastax.com/en/cassandra/3.x/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__broadcast_rpc_address |
added manual/idempotence/README.md +132 −0
| @@ -0,0 +1,132 @@ | ||
| 1 | +## Query idempotence | |
| 2 | + | |
| 3 | +A query is *idempotent* if it can be applied multiple times without changing the result of the initial application. For | |
| 4 | +example: | |
| 5 | + | |
| 6 | +* `update my_table set list_col = [1] where pk = 1` is idempotent: no matter how many times it gets executed, `list_col` | |
| 7 | + will always end up with the value `[1]`; | |
| 8 | +* `update my_table set list_col = [1] + list_col where pk = 1` is not idempotent: if `list_col` was initially empty, | |
| 9 | + it will contain `[1]` after the first execution, `[1, 1]` after the second, etc. | |
| 10 | + | |
| 11 | +Idempotence matters for [retries](../retries/) and [speculative query executions](../speculative_execution/). The | |
| 12 | +corresponding policies inspect the [Statement#isIdempotent()][isIdempotent] flag. | |
| 13 | + | |
| 14 | +In most cases, you must set that flag manually. The driver does not parse query strings, so it can't infer it | |
| 15 | +automatically (except for statements coming from the query builder, see below). | |
| 16 | + | |
| 17 | +Statements start out as non-idempotent by default. You can override the flag on each statement: | |
| 18 | + | |
| 19 | +```java | |
| 20 | +Statement s = new SimpleStatement("SELECT * FROM users WHERE id = 1"); | |
| 21 | +s.setIdempotent(true); | |
| 22 | +``` | |
| 23 | + | |
| 24 | +The default is also configurable: if you want all statements to start out as idempotent, do this: | |
| 25 | + | |
| 26 | +```java | |
| 27 | +// Make all statements idempotent by default: | |
| 28 | +cluster.getConfiguration().getQueryOptions().setDefaultIdempotence(true); | |
| 29 | +``` | |
| 30 | + | |
| 31 | +Any statement on which you didn't call `setIdempotent` gets this default value. | |
| 32 | + | |
| 33 | +Bound statements inherit the flag from the prepared statement they were created from: | |
| 34 | + | |
| 35 | +```java | |
| 36 | +PreparedStatement pst = session.prepare("SELECT * FROM users WHERE id = ?"); | |
| 37 | +// This cast is for backward-compatibility reasons. On 3.0+, you can do pst.setIdempotent(true) directly | |
| 38 | +((IdempotenceAwarePreparedStatement) pst).setIdempotent(true); | |
| 39 | + | |
| 40 | +BoundStatement bst = pst.bind(); | |
| 41 | +assert bst.isIdempotent(); | |
| 42 | +``` | |
| 43 | + | |
| 44 | +### Idempotence in the query builder | |
| 45 | + | |
| 46 | +The [QueryBuilder] DSL tries to infer the `isIdempotent` flag on the statements it generates. The following statements | |
| 47 | +will be marked **non-idempotent**: | |
| 48 | + | |
| 49 | +* counter updates: | |
| 50 | + | |
| 51 | + ```java | |
| 52 | + update("mytable").with(incr("c")).where(eq("k", 1)); | |
| 53 | + ``` | |
| 54 | +* prepend, append or deletion operations on lists: | |
| 55 | + | |
| 56 | + ```java | |
| 57 | + update("mytable").with(append("l", 1)).where(eq("k", 1)); | |
| 58 | + delete().listElt("l", 1).from("mytable").where(eq("k", 1)); | |
| 59 | + ``` | |
| 60 | +* queries that insert the result of a function call or a "raw" string in a column (or as an element in a collection | |
| 61 | + column): | |
| 62 | + | |
| 63 | + ```java | |
| 64 | + update("mytable").with(set("v", now())).where(eq("k", 1)); | |
| 65 | + update("mytable").with(set("v", fcall("myCustomFunc"))).where(eq("k", 1)); | |
| 66 | + update("mytable").with(set("v", raw("myCustomFunc()"))).where(eq("k", 1)); | |
| 67 | + ``` | |
| 68 | + | |
| 69 | + This is a conservative approach, since the driver can't guess whether a function is idempotent, or what a raw string | |
| 70 | + contains. It might yield false negatives, that you'll have to fix manually. | |
| 71 | + | |
| 72 | +* lightweight transactions (see the next section for a detailed explanation): | |
| 73 | + | |
| 74 | + ```java | |
| 75 | + insertInto("mytable").value("k", 1).value("v", 2).ifNotExists(); | |
| 76 | + ``` | |
| 77 | + | |
| 78 | +If these rules produce a false negative, you can manually override the flag on the built statement: | |
| 79 | + | |
| 80 | +```java | |
| 81 | +BuiltStatement s = update("mytable").with(set("v", fcall("anIdempotentFunc"))).where(eq("k", 1)); | |
| 82 | + | |
| 83 | +// False negative because the driver can't guess that anIdempotentFunc() is safe | |
| 84 | +assert !s.isIdempotent(); | |
| 85 | + | |
| 86 | +// Fix it | |
| 87 | +s.setIdempotent(true); | |
| 88 | +``` | |
| 89 | + | |
| 90 | + | |
| 91 | +### Idempotence and lightweight transactions | |
| 92 | + | |
| 93 | +As explained in the previous section, the query builder considers lightweight transactions as non-idempotent. This might | |
| 94 | +sound counter-intuitive, as these queries can sometimes be safe to execute multiple times. For example, consider the | |
| 95 | +following query: | |
| 96 | + | |
| 97 | +``` | |
| 98 | +UPDATE mytable SET v = 4 WHERE k = 1 IF v = 1 | |
| 99 | +``` | |
| 100 | + | |
| 101 | +If we execute it twice, the `IF` condition will fail the second time, so the second execution will do nothing and `v` | |
| 102 | +will still have the value 4. | |
| 103 | + | |
| 104 | +However, the problem appears when we consider multiple clients executing the query with retries: | |
| 105 | + | |
| 106 | +1. `v` has the value 1; | |
| 107 | +2. client 1 executes the query above, performing a a CAS (compare and set) from 1 to 4; | |
| 108 | +3. client 1's connection drops, but the query completes successfully. `v` now has the value 4; | |
| 109 | +4. client 2 executes a CAS from 4 to 2; | |
| 110 | +5. client 2's transaction succeeds. `v` now has the value 2; | |
| 111 | +6. since client 1 lost its connection, it considers the query as failed, and transparently retries the CAS from 1 to 4. | |
| 112 | + But since the column now has value 2, it receives a "not applied" response. | |
| 113 | + | |
| 114 | +One important aspect of lightweight transactions is [linearizability]: given a set of concurrent operations on a column | |
| 115 | +from different clients, there must be a way to reorder them to yield a sequential history that is correct. From our | |
| 116 | +clients' point of view, there were two operations: | |
| 117 | + | |
| 118 | +* client 1 executed a CAS from 1 to 4, that was not applied; | |
| 119 | +* client 2 executed a CAS from 4 to 2, that was applied. | |
| 120 | + | |
| 121 | +But overall the column changed from 1 to 2. There is no ordering of the two operations that can explain that change. We | |
| 122 | +broke linearizability by doing a transparent retry at step 6. | |
| 123 | + | |
| 124 | +To avoid this, the driver considers lightweight transactions as non-idempotent, and provides a | |
| 125 | +[retry policy](../retries/) that doesn't retry non-idempotent statements. If linearizability is important for you, you | |
| 126 | +should use that policy, and ensure that lightweight transactions are appropriately flagged. | |
| 127 | + | |
| 128 | +[isIdempotent]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Statement.html#isIdempotent-- | |
| 129 | +[setDefaultIdempotence]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setDefaultIdempotence-boolean- | |
| 130 | +[QueryBuilder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 131 | + | |
| 132 | +[linearizability]: https://en.wikipedia.org/wiki/Linearizability#Definition_of_linearizability | |
| No newline at the end of the file |
modified manual/object_mapper/creating/README.md +1 −1
| @@ -65,7 +65,7 @@ | ||
| 65 | 65 | |
| 66 | 66 | ``` |
| 67 | 67 | CREATE TABLE sales(countryCode text, areaCode text, sales int, |
| 68 | - PRIMARY KEY((countryCode, area Code))); | |
| 68 | + PRIMARY KEY((countryCode, areaCode))); | |
| 69 | 69 | ``` |
| 70 | 70 | |
| 71 | 71 | ```java |
modified manual/pooling/README.md +4 −3
| @@ -19,9 +19,10 @@ | ||
| 19 | 19 | trigger a callback that will complete the corresponding query (this is |
| 20 | 20 | the point where your `ResultSetFuture` will get completed). |
| 21 | 21 | |
| 22 | -To increase the number of concurrent requests, we use a pool of | |
| 23 | -connections to each host. **For each `Session` object, there is one | |
| 24 | -connection pool per connected host**. | |
| 22 | +You don't need to manage connections yourself. You simply interact with a `Session` object, which takes care of it. | |
| 23 | + | |
| 24 | +**For each `Session`, there is one connection pool per connected host** (a host is connected when it is up and | |
| 25 | +not ignored by the [load balancing policy](../load_balancing)). | |
| 25 | 26 | |
| 26 | 27 | The number of connections per pool is configurable (this will be |
| 27 | 28 | described in the next section). The number of stream ids depends on the |
modified manual/query_timestamps/README.md +1 −1
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | |
| 17 | 17 | ### Client-side generation |
| 18 | 18 | |
| 19 | -This is enabled by default if you're using the driver 3.0 and a version | |
| 19 | +This is enabled by default if you're using the driver 3.0+ and a version | |
| 20 | 20 | of Cassandra that supports [native protocol](../native_protocol) v3 or |
| 21 | 21 | above. |
| 22 | 22 |
modified manual/retries/README.md +189 −2
| @@ -1,6 +1,193 @@ | ||
| 1 | 1 | ## Retries |
| 2 | 2 | |
| 3 | -*Coming soon... In the meantime, see the javadoc for [RetryPolicy].* | |
| 3 | +When a query fails, it sometimes makes sense to retry it: the error might be temporary, or the query might work on a | |
| 4 | +different host, or with different options. | |
| 4 | 5 | |
| 6 | +The driver uses a configurable set of rules to determine when and how to retry. | |
| 5 | 7 | |
| 6 | -[RetryPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html | |
| No newline at the end of the file | ||
| 8 | +### Concepts | |
| 9 | + | |
| 10 | +When the driver executes a statement, it first obtains a [query plan] \(a list of hosts) from the load balancing policy. | |
| 11 | +Then it picks the first host and sends it the request; this host acts as the **coordinator** for the query, it will | |
| 12 | +communicate with the rest of the cluster and reply to the client. | |
| 13 | + | |
| 14 | +If the coordinator can't be reached or replies with an error, there are various things that the driver can do; they are | |
| 15 | +expressed as [RetryDecision] objects: | |
| 16 | + | |
| 17 | +* [retry()]: retry the query on the same host. It's possible to retry with a different consistency level than the one | |
| 18 | + that was originally requested; | |
| 19 | +* [tryNextHost()]: retry on the next host in the query plan. Again, it can be with a different CL; | |
| 20 | +* [rethrow()]: rethrow the exception to the user code. This means it will be thrown from the `session.execute` call (or | |
| 21 | + returned as a failed future if `executeAsync` was used); | |
| 22 | +* [ignore()]: mark the request as successful, and return an empty result set. | |
| 23 | + | |
| 24 | +If the driver retries on every host and reaches the end of the query plan, a [NoHostAvailableException] is thrown to the | |
| 25 | +user code. You can use its [getErrors()] method to find out what went wrong on each host. | |
| 26 | + | |
| 27 | + | |
| 28 | +### Retry policy | |
| 29 | + | |
| 30 | +[RetryPolicy] is a pluggable component that determines the retry decisions for various types of errors. It is configured | |
| 31 | +when initializing the cluster: | |
| 32 | + | |
| 33 | +```java | |
| 34 | +Cluster cluster = Cluster.builder() | |
| 35 | + .addContactPoint("127.0.0.1") | |
| 36 | + .withRetryPolicy(new MyCustomPolicy()) | |
| 37 | + .build(); | |
| 38 | +``` | |
| 39 | + | |
| 40 | +Once the cluster has been built, you can't change the policy, but you may inspect it at runtime: | |
| 41 | + | |
| 42 | +```java | |
| 43 | +RetryPolicy policy = cluster.getConfiguration().getPolicies().getRetryPolicy(); | |
| 44 | +``` | |
| 45 | + | |
| 46 | +If you don't explicitly configure it, you get a [DefaultRetryPolicy]. | |
| 47 | + | |
| 48 | +The policy's methods cover different types of errors: | |
| 49 | + | |
| 50 | +#### [onUnavailable] | |
| 51 | + | |
| 52 | +A request reached the coordinator, but there weren't enough live replicas to achieve the requested consistency level. | |
| 53 | +The coordinator replied with an `UNAVAILABLE` error. | |
| 54 | + | |
| 55 | +If the policy rethrows the error, the user code will get an [UnavailableException]. You can inspect the exception's | |
| 56 | +fields to get the amount of replicas that were *known* to be alive when the error was triggered, as well as the amount | |
| 57 | +of replicas that where *required* by the requested consistency level. | |
| 58 | + | |
| 59 | +#### [onReadTimeout] | |
| 60 | + | |
| 61 | +A read request reached the coordinator, which initially believed that there were enough live replicas to process it. | |
| 62 | +But, for some reason, one or several replicas were too slow to answer within the predefined timeout | |
| 63 | +(`read_request_timeout_in_ms` in `cassandra.yaml`), and the coordinator replied to the client with a `READ_TIMEOUT` | |
| 64 | +error. | |
| 65 | + | |
| 66 | +This could be due to a temporary overloading of these replicas, or even | |
| 67 | +that they just failed or were turned off. During reads, Cassandra doesn't request data from every replica to minimize | |
| 68 | +internal network traffic; instead, some replicas are only asked for a checksum of the data. A read timeout may occur | |
| 69 | +even if enough replicas responded to fulfill the consistency level, but only checksum responses were received (the | |
| 70 | +method's `dataRetrieved` parameter allow you to check if you're in that situation). | |
| 71 | + | |
| 72 | +If the policy rethrows the error, the user code will get a [ReadTimeoutException]. | |
| 73 | + | |
| 74 | +Note: do not confuse this error with a [driver read timeout], which happens when the coordinator didn't reply at all to | |
| 75 | +the client. | |
| 76 | + | |
| 77 | +#### [onWriteTimeout] | |
| 78 | + | |
| 79 | +This is similar to `onReadTimeout`, but for write operations. The reason reads and writes are handled separately is | |
| 80 | +because a read is obviously a non mutating operation, whereas a write is likely to be. If a write times out at the | |
| 81 | +coordinator level, there is no way to know whether the mutation was applied or not on the non-answering replica. | |
| 82 | +Policy implementations are usually more conservative in `onWriteTimeout` in case the write was not idempotent. | |
| 83 | + | |
| 84 | +If the policy rethrows the error, the user code will get a [WriteTimeoutException]. | |
| 85 | + | |
| 86 | +#### [onRequestError] | |
| 87 | + | |
| 88 | +This gets called for any other error occurring after the request was sent. | |
| 89 | + | |
| 90 | +The method receives the exception as a parameter, so that implementations can refine their decision based on what | |
| 91 | +happened. The possible exceptions are: | |
| 92 | + | |
| 93 | +* [ServerError]: thrown by the coordinator when an unexpected error occurs. This is generally a Cassandra bug; | |
| 94 | +* [OperationTimedOutException]: thrown by the client when it didn't hear back from the coordinator within the | |
| 95 | + [driver read timeout]; | |
| 96 | +* [ConnectionException]: thrown by the client for any network issue while or after the request was written; | |
| 97 | +* [OverloadedException]: thrown by the coordinator when replicas are down and the number of hinted handoffs gets too | |
| 98 | + high; the coordinator temporarily refuses writes for these replicas (see [hinted handoffs] in the Cassandra | |
| 99 | + documentation). | |
| 100 | + | |
| 101 | +In all these cases, there is no absolute certainty that the request was not applied by a host, so implementations must | |
| 102 | +consider the risk of retrying non-idempotent statements. | |
| 103 | + | |
| 104 | +### Hard-coded rules | |
| 105 | + | |
| 106 | +There are a few cases where retrying is always the right thing to do. These are not covered by `RetryPolicy`, but | |
| 107 | +hard-coded in the driver: | |
| 108 | + | |
| 109 | +* **any error before a network write was attempted**: to send a query, the driver selects a host, borrows a connection | |
| 110 | + from the host's [connection pool], and then writes the message to the connection. | |
| 111 | + Errors can occur before the write was even attempted, for example if the connection pool is saturated, or if the | |
| 112 | + host went down right after we borrowed. In those cases, it is always safe to retry since the request wasn't sent, so | |
| 113 | + the driver will transparently move to the next host in the query plan. | |
| 114 | + | |
| 115 | +* **re-preparing a statement**: when the driver executes a prepared statement, it may find out that the coordinator | |
| 116 | + doesn't know about it, and need to re-prepare it on the fly (this is described in detail [here][prepared]). The query | |
| 117 | + is then retried on the same host. | |
| 118 | + | |
| 119 | +* **trying to communicate with a host that is bootstrapping**: this is a rare edge case, as in practice the driver | |
| 120 | + should never try to communicate with a bootstrapping host (the only way is if it was specified as a contact point). | |
| 121 | + Anyway, it is again safe to assume that the query was not executed at all, so the driver moves to the next host. | |
| 122 | + | |
| 123 | +Similarly, some errors have no chance of being solved by a retry. They will always be rethrown directly to the user. | |
| 124 | +These include: | |
| 125 | + | |
| 126 | +* [QueryValidationException] and any of its subclasses ([InvalidQueryException], [InvalidConfigurationInQueryException], | |
| 127 | + [UnauthorizedException], [SyntaxError], [AlreadyExistsException]); | |
| 128 | +* [TruncateException]. | |
| 129 | + | |
| 130 | + | |
| 131 | +### Retries and idempotence | |
| 132 | + | |
| 133 | +Retry policies should avoid retrying [idempotent queries] when it's not clear whether the query was applied or not. | |
| 134 | + | |
| 135 | +It's always safe to retry in `onReadTimeout`, since by definition we know that the query is a read, which doesn't mutate | |
| 136 | +any data. Similarly, `onUnavailable` is safe: the coordinator is telling us that it didn't find enough replicas, so we | |
| 137 | +know that it didn't try to apply the query. | |
| 138 | + | |
| 139 | +`onWriteTimeout` is not safe. The default retry policy is very conservative (it only retries batch log writes) so it | |
| 140 | +will never cause any issue. Custom implementations should check the statements' idempotent flag. | |
| 141 | + | |
| 142 | +`onRequestError` isn't safe either. | |
| 143 | + | |
| 144 | +**For historical reasons, the built-in retry policy implementations do not check the idempotent flag in | |
| 145 | +`onRequestError`**. This is based on the fact that: | |
| 146 | + | |
| 147 | +* previous versions of the driver (which did `onRequestError` internally) didn't check the flag either; | |
| 148 | +* the majority of queries in an application should be idempotent; | |
| 149 | +* statements start out as non-idempotent by default. | |
| 150 | + | |
| 151 | +If `onRequestError` enforced idempotence strictly, this would cause a lot of queries that were legitimately retried with | |
| 152 | +previous driver versions to not be retried anymore. This would be a big behavioral change, so we decided to prefer | |
| 153 | +consistency with previous versions. | |
| 154 | + | |
| 155 | +If you prefer strict handling of the idempotent flag, you can wrap your retry policy into an | |
| 156 | +[IdempotenceAwareRetryPolicy]. Make sure to position the flag properly on all statements. | |
| 157 | + | |
| 158 | + | |
| 159 | +[RetryDecision]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html | |
| 160 | +[retry()]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#retry-com.datastax.driver.core.ConsistencyLevel- | |
| 161 | +[tryNextHost()]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#tryNextHost-com.datastax.driver.core.ConsistencyLevel- | |
| 162 | +[rethrow()]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#rethrow-- | |
| 163 | +[ignore()]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#ignore-- | |
| 164 | +[NoHostAvailableException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html | |
| 165 | +[getErrors()]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors-- | |
| 166 | +[RetryPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html | |
| 167 | +[DefaultRetryPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/DefaultRetryPolicy.html | |
| 168 | +[onReadTimeout]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onReadTimeout-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-int-int-boolean-int- | |
| 169 | +[onWriteTimeout]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onWriteTimeout-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-com.datastax.driver.core.WriteType-int-int-int- | |
| 170 | +[onUnavailable]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onUnavailable-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-int-int-int- | |
| 171 | +[onRequestError]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/ExtendedRetryPolicy.html#onRequestError-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-java.lang.Exception-int- | |
| 172 | +[UnavailableException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/UnavailableException.html | |
| 173 | +[ReadTimeoutException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/ReadTimeoutException.html | |
| 174 | +[WriteTimeoutException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/WriteTimeoutException.html | |
| 175 | +[OverloadedException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/OverloadedException.html | |
| 176 | +[ServerError]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/ServerError.html | |
| 177 | +[OperationTimedOutException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/OperationTimedOutException.html | |
| 178 | +[ConnectionException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/ConnectionException.html | |
| 179 | +[QueryValidationException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/QueryValidationException.html | |
| 180 | +[InvalidQueryException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/InvalidQueryException.html | |
| 181 | +[InvalidConfigurationInQueryException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.html | |
| 182 | +[UnauthorizedException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/UnauthorizedException.html | |
| 183 | +[SyntaxError]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/SyntaxError.html | |
| 184 | +[AlreadyExistsException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/AlreadyExistsException.html | |
| 185 | +[TruncateException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/TruncateException.html | |
| 186 | +[IdempotenceAwareRetryPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.html | |
| 187 | + | |
| 188 | +[query plan]: ../load_balancing/#query-plan | |
| 189 | +[connection pool]: ../pooling/ | |
| 190 | +[prepared]: ../statements/prepared/#preparing-on-multiple-nodes | |
| 191 | +[driver read timeout]: ../socket_options/#driver-read-timeout | |
| 192 | +[hinted handoffs]: https://docs.datastax.com/en/cassandra/2.1/cassandra/dml/dml_about_hh_c.html?scroll=concept_ds_ifg_jqx_zj__performance | |
| 193 | +[idempotent queries]: ../idempotence/ | |
| No newline at the end of the file |
modified manual/socket_options/README.md +2 −1
| @@ -103,7 +103,8 @@ | ||
| 103 | 103 | #### Driver read timeout vs. server read timeout |
| 104 | 104 | |
| 105 | 105 | Unfortunately, the term "read timeout" clashes with another concept that is not directly related: a Cassandra node may |
| 106 | -reply with a `Read_timeout` error when it didn't hear back from enough replicas during a read query. | |
| 106 | +reply with a [READ_TIMEOUT](../retries/#on-read-timeout) error when it didn't hear back from enough replicas during a | |
| 107 | +read query. | |
| 107 | 108 | |
| 108 | 109 | To clarify: |
| 109 | 110 |
modified manual/speculative_execution/README.md +2 −58
| @@ -60,57 +60,9 @@ | ||
| 60 | 60 | |
| 61 | 61 | ### Query idempotence |
| 62 | 62 | |
| 63 | -One important aspect to consider is whether queries are idempotent, i.e. | |
| 64 | -whether they can be applied multiple times without changing the result | |
| 65 | -beyond the initial application. **If a query is not idempotent, the | |
| 66 | -driver will never schedule speculative executions for it**, because | |
| 63 | +If a query is [not idempotent](../idempotence/), the driver will never schedule speculative executions for it, because | |
| 67 | 64 | there is no way to guarantee that only one node will apply the mutation. |
| 68 | 65 | |
| 69 | -As of Cassandra 2.1.4, the only queries that are *not* idempotent are: | |
| 70 | - | |
| 71 | -* counter operations; | |
| 72 | -* prepending or appending to a list column; | |
| 73 | -* using non-idempotent CQL functions, like `now()` or `uuid()`. | |
| 74 | - | |
| 75 | -In the driver, this is determined by | |
| 76 | -[Statement#isIdempotent()][isIdempotent]. Unfortunately, the driver | |
| 77 | -doesn't parse query strings, so in most cases it has no information | |
| 78 | -about what the query actually does. Therefore: | |
| 79 | - | |
| 80 | -* **`Statement#isIdempotent()` is only computed automatically for | |
| 81 | - statements built with [QueryBuilder][QueryBuilder]**. | |
| 82 | - Note that the driver takes a rather conservative approach with uses | |
| 83 | - of `fcall()` or `raw()`: whenever they appear in a value to be | |
| 84 | - inserted in the database (like the values of an `Insert` or the | |
| 85 | - right-hand side of an assignment in an `Update`), the statement | |
| 86 | - will be considered non-idempotent by default. If you know that your | |
| 87 | - CQL functions or expressions are safe, force idempotence to `true` | |
| 88 | - on the statement manually (see below); | |
| 89 | -* **for all other types of statements, it defaults to `false`.** You'll | |
| 90 | - need to set it manually, with one of the mechanism described below. | |
| 91 | - | |
| 92 | -You can override the value on each statement: | |
| 93 | - | |
| 94 | -```java | |
| 95 | -Statement s = new SimpleStatement("SELECT * FROM users WHERE id = 1"); | |
| 96 | -s.setIdempotent(true); | |
| 97 | -``` | |
| 98 | - | |
| 99 | -Note that this will also work for built statements (and override the | |
| 100 | -computed value). | |
| 101 | - | |
| 102 | -Additionally, if you know for a fact that your application does not use | |
| 103 | -any of the non-idempotent CQL queries listed above, you can change the | |
| 104 | -default cluster-wide: | |
| 105 | - | |
| 106 | -```java | |
| 107 | -// Make all statements idempotent by default: | |
| 108 | -cluster.getConfiguration().getQueryOptions().setDefaultIdempotence(true); | |
| 109 | -``` | |
| 110 | - | |
| 111 | -[isIdempotent]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Statement.html#isIdempotent-- | |
| 112 | -[QueryBuilder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 113 | - | |
| 114 | 66 | ### Enabling speculative executions |
| 115 | 67 | |
| 116 | 68 | Speculative executions are controlled by an instance of |
| @@ -218,15 +170,7 @@ | ||
| 218 | 170 | |
| 219 | 171 | ### How speculative executions affect retries |
| 220 | 172 | |
| 221 | -Regardless of speculative executions, the driver has a retry mechanism: | |
| 222 | - | |
| 223 | -* on an internal error, it will try the next host; | |
| 224 | -* when the consistency level could not be reached (`unavailable` error | |
| 225 | - or read or write timeout), it will delegate the decision to | |
| 226 | - [RetryPolicy][retry_policy], which might trigger a retry on the same | |
| 227 | - host. | |
| 228 | - | |
| 229 | -Turning speculative executions on doesn't change this behavior. Each | |
| 173 | +Turning speculative executions on doesn't change the driver's [retry](../retries/) behavior. Each | |
| 230 | 174 | parallel execution will trigger retries independently: |
| 231 | 175 | |
| 232 | 176 | ```ditaa |
modified manual/ssl/README.md +7 −3
| @@ -125,8 +125,11 @@ | ||
| 125 | 125 | #### Netty |
| 126 | 126 | |
| 127 | 127 | [NettySSLOptions] allows you to use Netty's `SslContext` instead of |
| 128 | -the JDK directly. The advantage is that Netty can use OpenSSL if | |
| 129 | -available, which provides better performance. | |
| 128 | +the JDK directly. The advantage is that Netty can use OpenSSL directly, | |
| 129 | +which provides better performance and generates less garbage. A disadvantage of | |
| 130 | +using the OpenSSL provider is that it requires platform-specific dependencies, | |
| 131 | +unlike the JDK provider. | |
| 132 | + | |
| 130 | 133 | |
| 131 | 134 | ##### Converting your client certificates for OpenSSL |
| 132 | 135 | |
| @@ -149,7 +152,8 @@ | ||
| 149 | 152 | [these instructions](http://netty.io/wiki/forked-tomcat-native.html) to |
| 150 | 153 | add it to your dependencies. |
| 151 | 154 | |
| 152 | -Note that using netty-tcnative requires JDK 1.7 or above. | |
| 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. | |
| 153 | 157 | |
| 154 | 158 | ##### Configuring the context |
| 155 | 159 |
modified pom.xml +118 −18
| @@ -40,6 +40,7 @@ | ||
| 40 | 40 | <module>driver-mapping</module> |
| 41 | 41 | <module>driver-extras</module> |
| 42 | 42 | <module>driver-examples</module> |
| 43 | + <module>driver-tests</module> | |
| 43 | 44 | <module>driver-dist</module> |
| 44 | 45 | </modules> |
| 45 | 46 | |
| @@ -65,30 +66,25 @@ | ||
| 65 | 66 | <assertj.version>1.7.0</assertj.version> |
| 66 | 67 | <mockito.version>1.10.8</mockito.version> |
| 67 | 68 | <commons-exec.version>1.3</commons-exec.version> |
| 68 | - <scassandra.version>0.11.0</scassandra.version> | |
| 69 | + <scassandra.version>1.0.3</scassandra.version> | |
| 69 | 70 | <main.basedir>${project.basedir}</main.basedir> |
| 70 | 71 | <ipprefix>127.0.1.</ipprefix> |
| 72 | + <test.groups>unit</test.groups> | |
| 71 | 73 | <!-- Set default javadoc.opts, overriden by profiles --> |
| 72 | 74 | <javadoc.opts /> |
| 73 | 75 | </properties> |
| 74 | 76 | |
| 75 | - <dependencies> | |
| 76 | - <dependency> | |
| 77 | - <groupId>log4j</groupId> | |
| 78 | - <artifactId>log4j</artifactId> | |
| 79 | - <version>${log4j.version}</version> | |
| 80 | - <scope>test</scope> | |
| 81 | - </dependency> | |
| 82 | - | |
| 83 | - <dependency> | |
| 84 | - <groupId>org.slf4j</groupId> | |
| 85 | - <artifactId>slf4j-log4j12</artifactId> | |
| 86 | - <version>${slf4j-log4j12.version}</version> | |
| 87 | - <scope>test</scope> | |
| 88 | - </dependency> | |
| 89 | - </dependencies> | |
| 90 | - | |
| 91 | 77 | <profiles> |
| 78 | + <profile> | |
| 79 | + <id>default</id> | |
| 80 | + <properties> | |
| 81 | + <env>default</env> | |
| 82 | + <test.groups>unit</test.groups> | |
| 83 | + </properties> | |
| 84 | + <activation> | |
| 85 | + <activeByDefault>true</activeByDefault> | |
| 86 | + </activation> | |
| 87 | + </profile> | |
| 92 | 88 | |
| 93 | 89 | <profile> |
| 94 | 90 | <id>doclint-java8-disable</id> |
| @@ -100,6 +96,62 @@ | ||
| 100 | 96 | </properties> |
| 101 | 97 | </profile> |
| 102 | 98 | |
| 99 | + <profile> | |
| 100 | + <id>short</id> | |
| 101 | + <properties> | |
| 102 | + <env>default</env> | |
| 103 | + <test.groups>unit,short</test.groups> | |
| 104 | + </properties> | |
| 105 | + </profile> | |
| 106 | + <profile> | |
| 107 | + <id>long</id> | |
| 108 | + <properties> | |
| 109 | + <env>default</env> | |
| 110 | + <test.groups>unit,short,long</test.groups> | |
| 111 | + </properties> | |
| 112 | + </profile> | |
| 113 | + <profile> | |
| 114 | + <id>duration</id> | |
| 115 | + <properties> | |
| 116 | + <env>default</env> | |
| 117 | + <test.groups>unit,short,long,duration</test.groups> | |
| 118 | + </properties> | |
| 119 | + </profile> | |
| 120 | + <profile> | |
| 121 | + <id>doc</id> | |
| 122 | + <properties> | |
| 123 | + <env>default</env> | |
| 124 | + <test.groups>unit,doc</test.groups> | |
| 125 | + </properties> | |
| 126 | + </profile> | |
| 127 | + <profile> | |
| 128 | + <!-- default profile settings for 'isolated' test group, will skip tests unless overridden in child module. --> | |
| 129 | + <id>isolated</id> | |
| 130 | + <properties> | |
| 131 | + <env>default</env> | |
| 132 | + <test.groups>isolated</test.groups> | |
| 133 | + </properties> | |
| 134 | + <build> | |
| 135 | + <plugins> | |
| 136 | + <plugin> | |
| 137 | + <groupId>org.apache.maven.plugins</groupId> | |
| 138 | + <artifactId>maven-surefire-plugin</artifactId> | |
| 139 | + <version>2.16</version> | |
| 140 | + <configuration> | |
| 141 | + <skip>true</skip> | |
| 142 | + <forkCount>1</forkCount> | |
| 143 | + <reuseForks>false</reuseForks> | |
| 144 | + <reportNameSuffix>isolated</reportNameSuffix> | |
| 145 | + <!-- This requires includes to be explicitly specified by implementing classes. | |
| 146 | + This is needed to prevent creating a JVM fork for each test, even those that don't | |
| 147 | + have the isolated group. --> | |
| 148 | + <includes /> | |
| 149 | + </configuration> | |
| 150 | + </plugin> | |
| 151 | + </plugins> | |
| 152 | + </build> | |
| 153 | + </profile> | |
| 154 | + | |
| 103 | 155 | <profile> |
| 104 | 156 | <id>enforce-java8</id> |
| 105 | 157 | <build> |
| @@ -289,7 +341,7 @@ | ||
| 289 | 341 | <plugin> |
| 290 | 342 | <groupId>org.codehaus.mojo</groupId> |
| 291 | 343 | <artifactId>animal-sniffer-maven-plugin</artifactId> |
| 292 | - <version>1.14</version> | |
| 344 | + <version>1.15</version> | |
| 293 | 345 | <configuration> |
| 294 | 346 | <signature> |
| 295 | 347 | <groupId>org.codehaus.mojo.signature</groupId> |
| @@ -307,6 +359,54 @@ | ||
| 307 | 359 | </execution> |
| 308 | 360 | </executions> |
| 309 | 361 | </plugin> |
| 362 | + <plugin> | |
| 363 | + <groupId>org.apache.maven.plugins</groupId> | |
| 364 | + <artifactId>maven-surefire-plugin</artifactId> | |
| 365 | + <version>2.16</version> | |
| 366 | + <configuration> | |
| 367 | + <groups>${test.groups}</groups> | |
| 368 | + <useFile>false</useFile> | |
| 369 | + <systemPropertyVariables> | |
| 370 | + <cassandra.version>${cassandra.version}</cassandra.version> | |
| 371 | + <ipprefix>${ipprefix}</ipprefix> | |
| 372 | + <com.datastax.driver.NEW_NODE_DELAY_SECONDS>60</com.datastax.driver.NEW_NODE_DELAY_SECONDS> | |
| 373 | + </systemPropertyVariables> | |
| 374 | + <classpathDependencyExcludes> | |
| 375 | + <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes> | |
| 376 | + </classpathDependencyExcludes> | |
| 377 | + <properties> | |
| 378 | + <property> | |
| 379 | + <!-- Don't skip tests after a @Before method throws a SkipException --> | |
| 380 | + <name>configfailurepolicy</name> | |
| 381 | + <value>continue</value> | |
| 382 | + </property> | |
| 383 | + </properties> | |
| 384 | + </configuration> | |
| 385 | + </plugin> | |
| 386 | + <plugin> | |
| 387 | + <groupId>org.apache.maven.plugins</groupId> | |
| 388 | + <artifactId>maven-failsafe-plugin</artifactId> | |
| 389 | + <version>2.16</version> | |
| 390 | + <configuration> | |
| 391 | + <groups>${test.groups}</groups> | |
| 392 | + <useFile>false</useFile> | |
| 393 | + <systemPropertyVariables> | |
| 394 | + <cassandra.version>${cassandra.version}</cassandra.version> | |
| 395 | + <ipprefix>${ipprefix}</ipprefix> | |
| 396 | + <com.datastax.driver.NEW_NODE_DELAY_SECONDS>60</com.datastax.driver.NEW_NODE_DELAY_SECONDS> | |
| 397 | + </systemPropertyVariables> | |
| 398 | + <classpathDependencyExcludes> | |
| 399 | + <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes> | |
| 400 | + </classpathDependencyExcludes> | |
| 401 | + <properties> | |
| 402 | + <property> | |
| 403 | + <!-- Don't skip tests after a @Before method throws a SkipException --> | |
| 404 | + <name>configfailurepolicy</name> | |
| 405 | + <value>continue</value> | |
| 406 | + </property> | |
| 407 | + </properties> | |
| 408 | + </configuration> | |
| 409 | + </plugin> | |
| 310 | 410 | </plugins> |
| 311 | 411 | </build> |
| 312 | 412 |
modified upgrade_guide/README.md +5 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | The purpose of this guide is to detail changes made by successive |
| 4 | 4 | versions of the Java driver. |
| 5 | 5 | |
| 6 | -### 3.0 | |
| 6 | +### 3.0.0 | |
| 7 | 7 | |
| 8 | 8 | This version brings parity with Cassandra 2.2 and 3.0. |
| 9 | 9 | |
| @@ -269,6 +269,10 @@ | ||
| 269 | 269 | Again, this is due to the fact that secondary indexes have been completely redesigned |
| 270 | 270 | in Cassandra 3.0. |
| 271 | 271 | |
| 272 | +29. `SSLOptions` has been refactored to allow the option to choose between JDK and Netty-based | |
| 273 | + SSL implementations. See [JAVA-841](https://datastax-oss.atlassian.net/browse/JAVA-841) and | |
| 274 | + the [SSL documentation](../manual/ssl) for more details. | |
| 275 | + | |
| 272 | 276 | |
| 273 | 277 | ### 2.1.8 |
| 274 | 278 |