Elffuss BraidHub

kikocis/java-driver public

Rename 'features' to 'manual'.
Changesetdf354c9a28e1341b209d22565fcdd12410cfec99530ded9f90371492484e90af
Authorolim7t <omichallat+github@gmail.com> · 2016-01-11 17:43 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-01-11 17:45 +01:00
Parentse4f6468d06bf

Browse the files at this changeset

48 files changed

modified README.md +5 −5
@@ -10,7 +10,7 @@
1010 [e.g.
1111 3.0.0-rc1](https://github.com/datastax/java-driver/tree/3.0.0-rc1).*
1212
13-A modern, [feature-rich](features/) and highly tunable Java client
13+A modern, [feature-rich](manual/) and highly tunable Java client
1414 library for Apache Cassandra (1.2+) and DataStax Enterprise (3.1+) using
1515 exclusively Cassandra's binary protocol and Cassandra Query Language v3.
1616
@@ -33,7 +33,7 @@
3333 [simple_st]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SimpleStatement.html
3434 [prepared_st]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#prepare(com.datastax.driver.core.RegularStatement)
3535 [batch_st]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BatchStatement.html
36-[pool]: features/pooling/
36+[pool]: manual/pooling/
3737 [lbp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
3838 [retry_policy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html
3939 [query_builder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/QueryBuilder.html
@@ -62,7 +62,7 @@
6262 other drivers, Cassandra, and DSE.
6363 - DOCS: the [user guide](http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/whatsNew2.html)
6464 has introductory material. We are progressively migrating the doc
65- [here](features/) with more technical details.
65+ [here](manual/) with more technical details.
6666 - API: http://www.datastax.com/drivers/java/3.0
6767
6868 **Feeback requested:** help us focus our efforts, provide your input on the [Platform and Runtime Survey](http://goo.gl/forms/qwUE6qnL7U) (we kept it short).
@@ -101,7 +101,7 @@
101101 ```
102102
103103
104-We also provide a [shaded JAR](features/shaded_jar/)
104+We also provide a [shaded JAR](manual/shaded_jar/)
105105 to avoid the explicit dependency to Netty.
106106
107107 If you can't use a dependency management tool, a
@@ -111,7 +111,7 @@
111111 ## Compatibility
112112
113113 The Java client driver 3.0 ([branch 3.0](https://github.com/datastax/java-driver/tree/3.0)) is compatible with Apache
114-Cassandra 1.2, 2.0, 2.1, 2.2 and 3.0 (see [this page](http://datastax.github.io/java-driver/features/native_protocol) for
114+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
115115 the most up-to-date compatibility information).
116116
117117 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)).
modified docs.yaml +8 −0
@@ -3,6 +3,14 @@
33 homepage: http://datastax.github.io/java-driver/
44 theme: datastax
55 sections:
6+ - title: Manual
7+ prefix: /manual
8+ sources:
9+ - type: markdown
10+ files: 'manual/**/*.md'
11+ # The 'manual' section was called 'features' in older releases. Leave both
12+ # definitions and Documentor will pick up whichever exists and ignore the
13+ # other.
614 - title: Features
715 prefix: /features
816 sources:
modified faq/README.md +2 −2
@@ -2,10 +2,10 @@
22
33 ### How do I implement paging?
44
5-When using [native protocol](../features/native_protocol/) version 2 or
5+When using [native protocol](../manual/native_protocol/) version 2 or
66 higher, the driver automatically pages large result sets under the hood.
77 You can also save the paging state to resume iteration later. See [this
8-page](../features/paging/) for more information.
8+page](../manual/paging/) for more information.
99
1010 Native protocol v1 does not support paging, but you can emulate it in
1111 CQL with `LIMIT` and the `token()` function. See
deleted features/README.md +0 −17
@@ -1,17 +0,0 @@
1-## Features
2-
3-This part of the documentation is organized into sub-sections covering
4-specific topics.
5-
6-If you're reading this from the [generated HTML documentation on
7-github.io](http://datastax.github.io/java-driver/), use the "Read More"
8-menu on the right hand side. If you're [browsing the source files on
9-github.com](https://github.com/datastax/java-driver/tree/3.0/features),
10-simply navigate to each sub-directory.
11-
12-This is a work in progress: new sections will be added to cover existing
13-features or document new ones.
14-
15-You can also find more help in the legacy
16-[user documentation](http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/whatsNew2.html)
17-on the DataStax website.
deleted features/address_resolution/README.md +0 −59
@@ -1,59 +0,0 @@
1-## Address resolution
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.
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).
12-
13-### The [AddressTranslator][at] interface
14-
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.
17-
18-```java
19-public class MyAddressTranslator implements AddressTranslator {
20- public InetSocketAddress translate(InetSocketAddress address) {
21- ... // your custom translation logic
22- }
23-}
24-
25-Cluster cluster = Cluster.builder()
26- .addContactPoint("1.2.3.4")
27- .withAddressTranslator(new MyAddressTranslator())
28- .build();
29-```
30-
31-Note: the contact points provided while creating the `Cluster` are not translated, only
32-addresses retrieved from or sent by Cassandra nodes are.
33-
34-[at]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/AddressTranslator.html
35-
36-### EC2 multi-region
37-
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:
41-
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.
45-
46-To use this implementation, provide an instance when initializing the `Cluster`:
47-
48-```java
49-Cluster cluster = Cluster.builder()
50- .addContactPoint("1.2.3.4")
51- .withAddressTranslator(new EC2MultiRegionAddressTranslator())
52- .build();
53-```
54-
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.
58-
59-[ec2]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.html
deleted features/async/README.md +0 −150
@@ -1,150 +0,0 @@
1-## Asynchronous programming
2-
3-The driver exposes an asynchronous API that allows you to write programs
4-in a fully-non blocking manner. Asynchronous methods return instances of
5-Guava's [ListenableFuture], that can be conveniently chained and
6-composed.
7-
8-Here is a short example that opens a session and runs a query
9-asynchronously:
10-
11-```java
12-import com.google.common.util.concurrent.*;
13-
14-ListenableFuture<Session> session = cluster.connectAsync();
15-
16-// Use transform with an AsyncFunction to chain an async operation after another:
17-ListenableFuture<ResultSet> resultSet = Futures.transform(session,
18- new AsyncFunction<Session, ResultSet>() {
19- public ListenableFuture<ResultSet> apply(Session session) throws Exception {
20- return session.executeAsync("select release_version from system.local");
21- }
22- });
23-
24-// Use transform with a simple Function to apply a synchronous computation on the result:
25-ListenableFuture<String> version = Futures.transform(resultSet,
26- new Function<ResultSet, String>() {
27- public String apply(ResultSet rs) {
28- return rs.one().getString("release_version");
29- }
30- });
31-
32-// Use a callback to perform an action once the future is complete:
33-Futures.addCallback(version, new FutureCallback<String>() {
34- public void onSuccess(String version) {
35- System.out.printf("Cassandra version: %s%n", version);
36- }
37-
38- public void onFailure(Throwable t) {
39- System.out.printf("Failed to retrieve the version: %s%n",
40- t.getMessage());
41- }
42-});
43-```
44-
45-### Async paging
46-
47-If you consume a `ResultSet` in a callback, be aware that iterating the
48-rows will trigger synchronous queries as you page through the results.
49-To avoid this, use [getAvailableWithoutFetching] to limit the iteration
50-to the current page, and [fetchMoreResults] to get a future to the next
51-page (see also the section on [paging](../paging/)).
52-Here is a full example:
53-
54-[getAvailableWithoutFetching]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSet.html#getAvailableWithoutFetching--
55-[fetchMoreResults]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSet.html#fetchMoreResults--
56-
57-```java
58-Statement statement = new SimpleStatement("select * from foo").setFetchSize(20);
59-ListenableFuture<ResultSet> future = Futures.transform(
60- session.executeAsync(statement),
61- iterate(1));
62-
63-private static AsyncFunction<ResultSet, ResultSet> iterate(final int page) {
64- return new AsyncFunction<ResultSet, ResultSet>() {
65- @Override
66- public ListenableFuture<ResultSet> apply(ResultSet rs) throws Exception {
67-
68- // How far we can go without triggering the blocking fetch:
69- int remainingInPage = rs.getAvailableWithoutFetching();
70-
71- System.out.printf("Starting page %d (%d rows)%n", page, remainingInPage);
72-
73- for (Row row : rs) {
74- System.out.printf("[page %d - %d] row = %s%n", page, remainingInPage, row);
75- if (--remainingInPage == 0)
76- break;
77- }
78- System.out.printf("Done page %d%n", page);
79-
80- boolean wasLastPage = rs.getExecutionInfo().getPagingState() == null;
81- if (wasLastPage) {
82- System.out.println("Done iterating");
83- return Futures.immediateFuture(rs);
84- } else {
85- ListenableFuture<ResultSet> future = rs.fetchMoreResults();
86- return Futures.transform(future, iterate(page + 1));
87- }
88- }
89- };
90-}
91-```
92-
93-### Good practices
94-
95-If your callback is slow, consider providing a separate executor.
96-Otherwise the callback might run on one of the driver's I/O threads,
97-blocking I/O operations for other requests while it is running:
98-
99-```java
100-ListenableFuture<String> result = Futures.transform(resultSet,
101- new Function<ResultSet, String>() {
102- public String apply(ResultSet rs) {
103- return someVeryLongComputation(rs);
104- }
105- }, myCustomExecutor);
106-```
107-
108-Avoid blocking operations in callbacks, especially if you don't provide
109-a separate executor. This could easily lead to deadlock if the thread
110-that's supposed to complete the blocking call is also the thread that's
111-waiting on it:
112-
113-```java
114-ListenableFuture<ResultSet> resultSet = Futures.transform(session,
115- new Function<Session, ResultSet>() {
116- public ResultSet apply(Session session) {
117- // Synchronous operation in a callback.
118- // DON'T DO THIS! It might deadlock.
119- return session.execute("select release_version from system.local");
120- }
121- });
122-```
123-
124-### Known limitations
125-
126-There are still a few places where the driver will block internally
127-(mainly for historical reasons):
128-
129-* [Cluster#init][init] performs blocking I/O operations. To avoid
130- issues, you should create your `Cluster` instances while bootstrapping
131- your application, and call `init` immediately. If you need to create new
132- instances at runtime, make sure this does not happen on an I/O thread.
133-* if a connection pool is busy, the driver will block until a connection
134- becomes available. To avoid this, set
135- [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the
136- driver will not block, just move to the next host immediately.
137-* if the session is set to a specific keyspace (either at startup or by
138- issuing a `USE` statement on a running session), the keyspace needs to
139- be propagated to any newly created connection. This is done when the
140- connection is first borrowed from the connection pool, and currently
141- blocks. To avoid any issue, only use a session with no keyspace set
142- (i.e. created by `Cluster#connect()`). This will be addressed in
143- [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893).
144-* trying to read fields from a [query trace] will block if the trace
145- hasn't been fetched already.
146-
147-[ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
148-[init]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#init()
149-[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
150-[query trace]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryTrace.html
deleted features/compression/README.md +0 −88
@@ -1,88 +0,0 @@
1-## Compression
2-
3-Cassandra's binary protocol supports optional compression of
4-transport-level requests and responses, for example:
5-
6-* a query with its serialized parameters;
7-* a [page](../paging/) from a result set, i.e. a list of serialized
8- rows.
9-
10-It reduces network traffic at the cost of CPU overhead, therefore it
11-will likely be beneficial when you have larger payloads.
12-
13-Two algorithms are available:
14-[LZ4](https://github.com/jpountz/lz4-java) and
15-[Snappy](https://code.google.com/p/snappy/).
16-Both rely on third-party libraries, declared by the driver as *optional*
17-dependencies. So If you use a build tool like Maven, you'll need to
18-declare an explicit dependency to pull the appropriate library in your
19-application's classpath. Then you configure compression at driver
20-startup.
21-
22-### LZ4
23-
24-Maven dependency:
25-
26-```xml
27-<dependency>
28- <groupId>net.jpountz.lz4</groupId>
29- <artifactId>lz4</artifactId>
30- <version>1.2.0</version>
31-</dependency>
32-```
33-
34-Always check the exact version of the library: go to the driver's
35-[parent POM][pom] (change the URL to match your driver version) and look
36-for the `lz4.version` property.
37-
38-Driver configuration:
39-
40-```java
41-cluster = Cluster.builder()
42- .addContactPoint("127.0.0.1")
43- .withCompression(ProtocolOptions.Compression.LZ4)
44- .build();
45-```
46-
47-LZ4-java has three internal implementations (from fastest to slowest):
48-
49-* JNI;
50-* pure Java using sun.misc.Unsafe;
51-* pure Java using only "safe" classes.
52-
53-It will pick the best implementation depending on what's possible on
54-your platform. To find out which one was chosen, [enable INFO
55-logs](../logging/) on the category
56-`com.datastax.driver.core.FrameCompressor` and look for a log similar to
57-this:
58-
59-```
60-INFO com.datastax.driver.core.FrameCompressor - Using LZ4Factory:JNI
61-```
62-
63-### Snappy
64-
65-Maven dependency:
66-
67-```xml
68-<dependency>
69- <groupId>org.xerial.snappy</groupId>
70- <artifactId>snappy-java</artifactId>
71- <version>1.0.5</version>
72-</dependency>
73-```
74-
75-Always check the exact version of the library: go to the driver's
76-[parent POM][pom] (change the URL to match your driver version) and look
77-for the `snappy.version` property.
78-
79-Driver configuration:
80-
81-```java
82-cluster = Cluster.builder()
83- .addContactPoint("127.0.0.1")
84- .withCompression(ProtocolOptions.Compression.SNAPPY)
85- .build();
86-```
87-
88-[pom]: https://repo1.maven.org/maven2/com/datastax/cassandra/cassandra-driver-parent/3.0.0-rc1/cassandra-driver-parent-3.0.0-rc1.pom
deleted features/custom_codecs/README.md +0 −468
@@ -1,468 +0,0 @@
1-## Custom Codecs
2-
3-Custom codecs support transparent, user-configurable mapping of CQL types to arbitrary Java objects.
4-
5-Practical use cases that justify such a feature are numerous:
6-
7-* Ability to map CQL timestamp, date and time columns to Java 8 or Joda Time classes (rather than the built-in mappings for Date, [LocalDate] and Long);
8-* Ability to map CQL varchar columns directly to JSON or XML mapped objects (i.e. using frameworks such as Jackson);
9-* Ability to map CQL user-defined types to Java objects;
10-* Ability to map CQL lists directly to Java arrays;
11-* Ability to map CQL collections directly to Scala collections;
12-* etc.
13-
14-### Overview of the serialization mechanism
15-
16-The central piece in the serialization mechanism is [TypeCodec].
17-
18-Each `TypeCodec` supports a bidirectional mapping between a Java type and a CQL type. A `TypeCodec` is thus capable of 4 basic operations:
19-
20-* [Serialize][serialize] a Java object into a CQL value;
21-* [Deserialize][deserialize] a CQL value into a Java object;
22-* [Format][TypeCodec.format] a Java object into a CQL literal;
23-* [Parse][TypeCodec.parse] a CQL literal into a Java object.
24-
25-Additionally, it implements inspection methods that verify if the codec is suitable for a specific
26-CQL type and/or Java object.
27-
28-`TypeCodec` can be freely subclassed by users willing to implement their own serialization logic.
29-However, users are only required to do so when they want to extend
30-the driver's default set of codecs by registering additional codecs that handle
31-Java types that the driver is otherwise unable to process. For all other users,
32-the built-in set of codecs that is bundled with the driver provides
33-exactly the same functionality that the driver used to offer so far,
34-with out-of-the-box conversion from all CQL types to standard Java equivalents.
35-
36-Refer to the [javadocs][TypeCodec] of `TypeCodec` for more information.
37-
38-`TypeCodec`s are centralized in a [CodecRegistry] instance.
39-Whenever the driver needs to perform one of the aforementioned operations,
40-it will lookup for an appropriate codec in a `CodecRegistry`.
41-`CodecRegistry` is also used to manually register user-created codecs (see below for detailed instructions).
42-It also caches codec lookup results for faster execution whenever possible.
43-
44-Refer to the [javadocs][CodecRegistry] of `CodecRegistry` for more information.
45-
46-### Implementing and using custom codecs
47-
48-Let's consider the following scenario: a user has JSON documents stored in a varchar column, and wants
49-the driver to automatically map that column to a Java object using the [Jackson] library,
50-instead of returning the raw JSON string.
51-
52-The (admittedly simplistic) table structure is as follows:
53-
54-```sql
55-CREATE TABLE t (id int PRIMARY KEY, json VARCHAR);
56-```
57-
58-The first step is to implement a suitable codec. Using Jackson, here is what a Json codec could look like:
59-
60-```java
61-/**
62- * A simple Json codec.
63- */
64-public class JsonCodec<T> extends TypeCodec<T> {
65-
66- private final ObjectMapper objectMapper = new ObjectMapper();
67-
68- public JsonCodec(Class<T> javaType) {
69- super(DataType.varchar(), javaType);
70- }
71-
72- @Override
73- public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
74- if (value == null)
75- return null;
76- try {
77- return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
78- } catch (JsonProcessingException e) {
79- throw new InvalidTypeException(e.getMessage(), e);
80- }
81- }
82-
83- @Override
84- @SuppressWarnings("unchecked")
85- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
86- if (bytes == null)
87- return null;
88- try {
89- byte[] b = new byte[bytes.remaining()];
90- // always duplicate the ByteBuffer instance before consuming it!
91- bytes.duplicate().get(b);
92- return (T)objectMapper.readValue(b, toJacksonJavaType());
93- } catch (IOException e) {
94- throw new InvalidTypeException(e.getMessage(), e);
95- }
96- }
97-
98- @Override
99- public String format(T value) throws InvalidTypeException {
100- if (value == null)
101- return NULL;
102- String json;
103- try {
104- json = objectMapper.writeValueAsString(value);
105- } catch (IOException e) {
106- throw new InvalidTypeException(e.getMessage(), e);
107- }
108- return '\'' + json.replace("\'", "''") + '\'';
109- }
110-
111- @Override
112- @SuppressWarnings("unchecked")
113- public T parse(String value) throws InvalidTypeException {
114- if (value == null || value.isEmpty() || value.equals(NULL))
115- return null;
116- if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
117- throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
118- String json = value.substring(1, value.length() - 1).replace("''", "'");
119- try {
120- return (T)objectMapper.readValue(json, toJacksonJavaType());
121- } catch (IOException e) {
122- throw new InvalidTypeException(e.getMessage(), e);
123- }
124- }
125-
126- protected JavaType toJacksonJavaType() {
127- return TypeFactory.defaultInstance().constructType(getJavaType().getType());
128- }
129-
130-}
131-```
132-
133-A few implementation guidelines:
134-
135-* Your codecs should be thread-safe, or better yet, immutable;
136-* Your codecs should be fast: do not forget that codecs are executed often and are usually very "hot" pieces of code;
137-* Your codecs should never block.
138-
139-The second step is to register your codec with a `CodecRegistry` instance:
140-
141-```java
142-ObjectMapper objectMapper = ...
143-JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
144-CodecRegistry myCodecRegistry = cluster.getConfiguration().getCodecRegistry();
145-myCodecRegistry.register(myJsonCodec);
146-```
147-
148-As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`.
149-By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
150-which should be adequate for most users.
151-
152-It is however possible to create a `Cluster` using a different `CodecRegistry`:
153-
154-```java
155-CodecRegistry myCodecRegistry = new CodecRegistry();
156-Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
157-```
158-
159-Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver.
160-This ensures that the new registry will not lack of an essential codec. *You cannot deregister nor override
161-an already-registered codec, only register new ones*. If you try to register a codec that would override
162-an existing one, the driver will log a warning and ignore it.
163-
164-From now on, your custom codec is fully operational. It will be used every time the driver encounters
165-a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
166-
167-For example, here is how to save a `MyPojo` object:
168-
169-```java
170-Cluster cluster = ...
171-Session session = ...
172-MyPojo myPojo = ...
173-// Using SimpleStatement
174-Statement stmt = new SimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
175-// Using the Query Builder
176-BuiltStatement insertStmt = QueryBuilder.insertInto("t")
177- .value("id", 42)
178- .value("json", myPojo);
179-// Using BoundStatements
180-PreparedStatement ps = session.prepare("INSERT INTO t (id, json) VALUES (?, ?)");
181-BoundStatement bs1 = ps.bind(42, myPojo); // or alternatively...
182-BoundStatement bs2 = ps.bind()
183- .setInt(0, 42)
184- .set(1, myPojo, MyPojo.class);
185-```
186-
187-And here is how to retrieve a `MyPojo` object converted from a JSON document:
188-
189-```java
190-ResultSet rows = session.execute(...);
191-Row row = one();
192-// Let the driver convert the string for you...
193-MyPojo myPojo = row.get(1, MyPojo.class);
194-// ... or retrieve the raw string if you need it
195-String json = row.get(1, String.class); // row.getString(1) would have worked too
196-```
197-
198-Tip: `Row` and `BoundStatement` have several methods to set and retrieve values.
199-But if you plan to use custom codecs,
200-make sure that you use preferably the `get()` and `set()` methods: they
201-avoid any ambiguity by requiring the user to explicitly specify the desired Java type,
202-thus forcing the driver to pick the right codec for the right task.
203-
204-### On-the-fly codec generation
205-
206-`CodecRegistry` instances not only store default codecs and user-defined codecs;
207-they can also create new codecs on the fly, based on the set of codecs they currently hold.
208-They can manage the following mappings:
209-
210-* Collections (list, sets and maps) of known types. For example, if you registered a `TypeCodec<A>`, you get `List<A>>` handled for free. This works recursively for nested collections;
211-* [UserType] instances are automatically mapped to [UDTValue] objects. All registered codecs are available recursively to the UDT's fields;
212-* [TupleType] instances are automatically mapped to [TupleValue] objects (with the same rules for nested fields);
213-* [CustomType] instances are automatically mapped to [ByteBuffer] instances.
214-
215-This way, the user does not have to manually register all derived codecs for a given "base" codec.
216-However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly;
217-such codecs must be manually registered.
218-
219-If the codec registry encounters a mapping that it can't handle automatically, a [CodecNotFoundException]
220-is thrown.
221-
222-Thanks to on-the-fly codec generation, it is possible to leverage the `JsonCodec` from our previous
223-example to retrieve lists of `MyPojo` objects stored in a CQL column of type `list<text>`, without
224-the need to explicitly declare a codec for this specific CQL type:
225-
226-```java
227-JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
228-myCodecRegistry.register(myJsonCodec);
229-Row row = ...
230-List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class); // works out of the box!
231-```
232-
233-### Creating custom codecs for user-defined types (UDTs)
234-
235-By default, the driver maps user-defined type values to [UDTValue] instances.
236-
237-If you want to register a custom codec for a specific user-defined type,
238-follow these steps:
239-
240-Let's suppose you have a keyspace containing the following type and table:
241-
242-```sql
243-CREATE TYPE address (street VARCHAR, zipcode INT);
244-CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR, address frozen<address>);
245-```
246-
247-And let's suppose that you want to map the type `address` to an `Address` class:
248-
249-```java
250-public class Address {
251-
252- private final String street;
253-
254- private final int zipcode;
255-
256- public Address(String street, int zipcode) {
257- this.street = street;
258- this.zipcode = zipcode;
259- }
260-
261- // getters, setters, equals() and hashcode() omitted
262-}
263-```
264-
265-First of all, create a codec that knows how to serialize this class; one possible solution
266-(but not necessarily the most efficient one) would be to convert `Address` instances into `UDTValue`
267-instances, then serialize them with another codec:
268-
269-
270-```java
271-public class AddressCodec extends TypeCodec<Address> {
272-
273- private final TypeCodec<UDTValue> innerCodec;
274-
275- private final UserType userType;
276-
277- public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
278- super(innerCodec.getCqlType(), javaType);
279- this.innerCodec = innerCodec;
280- this.userType = (UserType)innerCodec.getCqlType();
281- }
282-
283- @Override
284- public ByteBuffer serialize(Address value, ProtocolVersion protocolVersion) throws InvalidTypeException {
285- return innerCodec.serialize(toUDTValue(value), protocolVersion);
286- }
287-
288- @Override
289- public Address deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
290- return toAddress(innerCodec.deserialize(bytes, protocolVersion));
291- }
292-
293- @Override
294- public Address parse(String value) throws InvalidTypeException {
295- return value == null || value.isEmpty() || value.equals(NULL) ? null : toAddress(innerCodec.parse(value));
296- }
297-
298- @Override
299- public String format(Address value) throws InvalidTypeException {
300- return value == null ? null : innerCodec.format(toUDTValue(value));
301- }
302-
303- protected Address toAddress(UDTValue value) {
304- return value == null ? null : new Address(
305- value.getString("street"),
306- value.getInt("zipcode")
307- );
308- }
309-
310- protected UDTValue toUDTValue(Address value) {
311- return value == null ? null : userType.newValue()
312- .setString("street", value.getStreet())
313- .setInt("zipcode", value.getZipcode());
314- }
315-}
316-```
317-
318-Now (and only if you intend to use your own `CodecRegistry`),
319-create it and register it on your `Cluster` instance:
320-
321-```java
322-// only if you do not intend to use CodecRegistry.DEFAULT_INSTANCE
323-CodecRegistry codecRegistry = new CodecRegistry();
324-Cluster cluster = Cluster.builder()
325- .addContactPoints(...)
326- .withCodecRegistry(codecRegistry)
327- .build();
328-```
329-
330-Now, retrieve the metadata for type `address`:
331-
332-```java
333-UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address");
334-TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType);
335-```
336-
337-And finally, register your `AddressCodec` with the `CodecRegistry`. Note that
338-your codec simply delegates the hard work to an inner codec that knows how to deal with
339-user type values:
340-
341-```java
342-AddressCodec addressCodec = new AddressCodec(addressTypeCodec, Address.class);
343-codecRegistry.register(addressCodec);
344-```
345-
346-And voilà! You can now retrieve `address` values as `Address` instances:
347-
348-```java
349-ResultSet rows = session.execute(...);
350-Row row = rows.one();
351-// let the driver convert it for you...
352-Address address = row.get("address", Address.class);
353-// ...or access the low-level UDTValue, if you need
354-UDTValue addressUdt = row.get("address", UDTValue.class); // row.getUDTValue("address") would have worked too
355-```
356-
357-Note that this solution creates an intermediary `UDTValue` object when
358-serializing and deserializing. It's possible to bypass this step with a
359-lower-level implementation that manipulates the binary stream directly.
360-That's also how the object mapper handles UDTs, and you can rely on the
361-mapper to generate UDT codecs for you; see
362-[this page](../object_mapper/custom_codecs/#implicit-udt-codecs) for more
363-information.
364-
365-### Support for generic (parameterized) types
366-
367-Java generic (parameterized) types are fully supported, through Guava's [TypeToken] API.
368-Be sure to only use `get()` and `set()` methods that take a `TypeToken` argument:
369-
370-```java
371-// this works
372-Foo<Bar> foo = row.get(0, new TypeToken<Foo<Bar>>(){})
373-// this does not work due to type erasure
374-Foo<Bar> foo = row.get(0, Foo.class);
375-```
376-
377-### Support for subtype polymorphism
378-
379-Suppose the following class hierarchy:
380-
381-```java
382-class Animal {}
383-class Cat extends Animal {}
384-```
385-
386-By default, a codec will accept to serialize any object that extends or
387-implements its declared Java type: a codec such as
388-`AnimalCodec extends TypeCodec<Animal>` will accept `Cat` instances as well.
389-
390-This allows a codec to handle interfaces and superclasses
391-in a generic way, regardless of the actual implementation being
392-used by client code; for example, the driver has a built-in codec
393-that handles `List` instances, and this codec is capable of
394-serializing any concrete `List` implementation.
395-
396-But this has one caveat: when setting or retrieving values
397-with `get()` and `set()`, *it is vital to pass the exact
398-Java type the codec handles*:
399-
400-```java
401-codecRegistry.register(new AnimalCodec());
402-BoundStatement bs = ...
403-bs.set(0, new Cat(), Animal.class); // works
404-bs.set(0, new Cat(), Cat.class); // throws CodecNotFoundException
405-```
406-
407-The same is valid when retrieving values:
408-
409-```java
410-codecRegistry.register(new AnimalCodec());
411-Row row = ...
412-Animal animal = row.get(0, Animal.class); // works
413-Cat cat = row.get(0, Cat.class); // throws CodecNotFoundException
414-```
415-
416-### Performance considerations
417-
418-A codec lookup operation may be costly; to mitigate this, the `CodecRegistry`
419-caches lookup results whenever possible.
420-
421-When the cache can be used and the registry looks up a codec, the following rules apply:
422-
423-1. if a result was previously cached for that mapping, it is returned;
424-2. otherwise, the registry checks the list of "basic" codecs: the default ones,
425-and the ones that were explicitly registered (in the order that they were registered).
426-It calls each codec's [accepts] methods to determine if it can handle the mapping,
427-and if so, adds it to the cache and returns it;
428-3. otherwise, the registry tries to generate a codec on the fly, according to the rules outlined above;
429-4. if the creation succeeds, the registry adds the created codec to the cache and returns it;
430-5. otherwise, the registry throws [CodecNotFoundException].
431-
432-The cache can be used as long as *at least the CQL type is known*. The following situations
433-are exceptions where it is *not* possible to cache lookup results:
434-
435-* With [SimpleStatement] instances;
436-* With [BuiltStatement] instances (created via the Query Builder).
437-
438-In these places, the driver has no way to determine the right CQL type to use, so it performs
439-a best-effort heuristic to guess which codec to use. The result of this heuristic is never cached.
440-
441-Beware that in these cases, the lookup performs in average 10x worse. If performance is a key factor for your application,
442-consider using prepared statements all the time.
443-
444-[JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
445-[TypeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html
446-[LocalDate]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/LocalDate.html
447-[ByteBuffer]: http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html
448-[serialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#serialize(T,%20com.datastax.driver.core.ProtocolVersion)
449-[deserialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#deserialize(java.nio.ByteBuffer,%20com.datastax.driver.core.ProtocolVersion)
450-[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#format(T)
451-[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#parse(java.lang.String)
452-[accepts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#accepts-com.datastax.driver.core.DataType-
453-[CodecRegistry]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/CodecRegistry.html
454-[CodecNotFoundException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/CodecNotFoundException.html
455-[Jackson]: http://wiki.fasterxml.com/JacksonHome
456-[AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
457-[UserType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UserType.html
458-[UDTValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UDTValue.html
459-[TupleType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleType.html
460-[TupleValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleValue.html
461-[CustomType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/DataType.CustomType.html
462-[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
463-[SimpleStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SimpleStatement.html
464-[BuiltStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/BuiltStatement.html
465-[setList]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setList(int,%20java.util.List)
466-[setSet]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setSet(int,%20java.util.Set)
467-[setMap]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setMap(int,%20java.util.Map)
468-[setObject]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setObject(int,%20V)
deleted features/custom_payloads/README.md +0 −248
@@ -1,248 +0,0 @@
1-## Custom Payloads
2-
3-The [native protocol](../native_protocol/) version 4 introduces a new feature called [Custom Payloads][CASSANDRA-8553].
4-
5-According to the [protocol V4 specification][v4spec], custom payloads are generic key-value maps
6-where keys are strings and each value is an arbitrary sequence of bytes. Currently payloads
7-can be sent by clients along with all `QUERY`, `PREPARE`, `EXECUTE` and `BATCH` requests.
8-
9-Custom payloads can be used to convey user-specific information from clients to servers and vice versa.
10-_Please note that this is an advanced feature that requires specific server-side configuration (see below)._
11-
12-### Enabling custom payloads on C* nodes
13-
14-What the server is supposed to do with a payload depends on the [QueryHandler][qh] used server-side
15-to decode requests. Unsurprisingly, the default `QueryHandler` implementation used by Cassandra
16-simply ignores all payloads. However, users can replace it with their own implementation,
17-thus being able to to process user-specific payloads; the payload format as well as
18-the serialization and deserialization logic is entirely left for clients to implement.
19-Needless to say, the same encoding and decoding logic should be applied on both client
20-and server endpoints.
21-
22-This section is a small how-to to help driver users getting started with
23-custom payload processing server-side. For more detailed information,
24-please refer to the Cassandra documentation itself.
25-
26-To enable a custom `QueryHandler` for a Cassandra node, its JVM should be
27-started with the system property `cassandra.custom_query_handler_class` set
28-to a fully qualified name of a class implementing `org.apache.cassandra.cql3.QueryHandler`.
29-This class should be of course available on the node's classpath.
30-
31-This can be achieved with the following steps:
32-
33-1. Add your implementation jar to the `CLASSPATH` environment variable;
34-2. Add the following to `$CASSANDRA_CONF/cassandra-env.sh`:
35-
36-```
37-JVM_EXTRA_OPTS="-Dcassandra.custom_query_handler_class=fully.qualified.name.of.MyQueryHandler"
38-```
39-
40-Of course, all nodes in the cluster *must* be started with the same QueryHandler, otherwise
41-payloads sent by the driver could get lost.
42-
43-### Implementation Notes
44-
45-Payloads in the Java driver are represented as `Map<String,ByteBuffer>` instances.
46-It is safe to use any `Map` implementation, including unsynchronized implementations
47-such as `java.util.HashMap`; the driver will create defensive, thread-safe copies of
48-user-supplied maps. However, `ByteBuffer` instances are inherently mutable,
49-so callers should take care not to modify the `ByteBuffer` values in a payload map *after* submitting it
50-to the driver as it could lead to unexpected results.
51-
52-#### Null values
53-
54-Note that, for thread safety reasons, the Java driver does not permit `null` keys nor `null` values in a payload map;
55-including a `null` in your payload will result in a `NullPointerException` being immediately thrown.
56-
57-However, the protocol specification *does* allow `null` values. If you need to include
58-a `null` value in your payload map, this can be achieved with the Java driver
59-by using the special value `Statement.NULL_PAYLOAD_VALUE`.
60-
61-##### Payload length limitations
62-
63-1. Payload maps cannot have more than 65,535 entries.
64-2. Payload map values are limited to a maximum length of `Integer.MAX_VALUE` (2<sup><small>31</small></sup> − 1) bytes each.
65-
66-### Sending custom payloads
67-
68-A custom payload can be attached to any `Statement` via `Statement.setOutgoingPayload()`.
69-
70-Once the payload is set, you can either prepare the statement or execute it;
71-in both cases, the payload will be sent along with the `PREPARE` or `QUERY` request respectively:
72-
73-```java
74-Statement statement = new SimpleStatement("SELECT foo FROM bar WHERE qix = 1");
75-statement.setOutgoingPayload(myCustomPayload);
76-session.execute(statement); // myCustomPayload will be sent with QUERY request
77-session.prepare(statement); // myCustomPayload will be sent with PREPARE request
78-```
79-
80-Naturally, you can also set a payload when using the `QueryBuilder` API:
81-
82-```java
83-Statement statement = QueryBuilder.select("c2").from("t1").where(eq("c1", 1)).setOutgoingPayload(myCustomPayload);
84-session.execute(statement); // myCustomPayload will be sent with EXECUTE request
85-```
86-
87-When sending payloads with batches, please note that payloads must be attached to the
88-`BatchStatement` itself, *not* to internal statements:
89-
90-```java
91-Statement statement = new SimpleStatement("INSERT INTO t1 (c1, c2) values ('foo', 'bar')")
92-// correct
93-Statement batch = new BatchStatement().add(statement);
94-batch.setOutgoingPayload(myCustomPayload);
95-session.execute(batch); // myCustomPayload will be sent with BATCH request
96-// wrong
97-statement.setOutgoingPayload(myCustomPayload);
98-Statement batch = new BatchStatement().add(statement);
99-session.execute(batch); // myCustomPayload will NOT be sent with BATCH request
100-```
101-
102-One important note about paging requests: if your query needs to paginate,
103-any outgoing payload set on the executed statement *will be transparently
104-sent over and over for every new page request*.
105-
106-```java
107-Statement statement = new SimpleStatement("...");
108-statement.setOutgoingPayload(myCustomPayload);
109-ResultSet rows = session.execute(...); // myCustomPayload will be sent with first QUERY request
110-for (Row row : rows) {
111- // if additional QUERY requests are sent, all of them will send the same payload
112-}
113-```
114-
115-And finally, note that custom payloads can only be used with protocol versions >= 4;
116-trying to set a payload under lower protocol versions will result in
117-an [UnsupportedFeatureException][ufe] (wrapped in a [NoHostAvailableException][nhae])
118-when the request is encoded.
119-
120-If you want to defensively protect your code against these errors, you can either:
121-
122-1) Force the protocol version when creating your `Cluster` instance:
123-
124-```java
125-Cluster cluster = Cluster.builder()
126- .addContactPoint("...")
127- .withProtocolVersion(ProtocolVersion.V4)
128- .build();
129-```
130-
131-2) Inspect the current negotiated protocol version, and only send payloads if version is equal to or
132-greater than 4:
133-
134-```java
135-ProtocolVersion myCurrentVersion = cluster.getConfiguration()
136- .getProtocolOptions()
137- .getProtocolVersionEnum();
138-if (myCurrentVersion.compareTo(ProtocolVersion.V4) >= 0) {
139- // only send custom payloads if current protocol version supports it
140- statement.setOutgoingPayload(myCustomPayload);
141-}
142-```
143-
144-### Receiving custom payloads
145-
146-Custom payloads sent back by the server can be retrieved in the following ways:
147-
148-1) From a `ResultSet`: use the `ExecutionInfo` class to retrieve the payload sent by the server.
149-
150-```java
151-Statement statement = new SimpleStatement("...");
152-ResultSet rows = session.execute(...);
153-// last payload sent by the server
154-Map<String,ByteBuffer> serverPayload = rows.getExecutionInfo().getIncomingPayload();
155-```
156-
157-If your query required pagination (multiple `QUERY` requests),
158-the above method would only return the last payload sent by server
159-with its last `RESULT` response. If you need to retrieve all the
160-payloads for all `RESULT` responses, use the following method instead:
161-
162-```java
163-Statement statement = new SimpleStatement("...");
164-ResultSet rows = session.execute(...);
165-//all payloads sent by the server
166-for (ExecutionInfo info : rows.getAllExecutionInfo()) {
167- Map<String,ByteBuffer> serverPayload = info.getIncomingPayload();
168-}
169-```
170-
171-2) From a `PreparedStatement`: to retrieve the payload that the server sent back
172-with its `PREPARED` response, use the following method:
173-
174-```java
175-PreparedStatement ps = session.prepare(...);
176-Map<String,ByteBuffer> serverPayload = ps.getIncomingPayload();
177-```
178-
179-### Custom Payloads and Prepared Statements
180-
181-If you use either `Session.prepare(RegularStatement)` or `Session.prepareAsync(RegularStatement)`
182-to prepare a statement, as with all other properties in the given statement, its outgoing
183-payload, if any, will become the default outgoing payload for the prepared statement.
184-
185-```java
186-Statement statement = new SimpleStatement("...");
187-statement.setOutgoingPayload(myCustomPayload)
188-PreparedStatement ps = session.prepare(...); // myCustomPayload will be sent with PREPARE request
189- // AND become the default outgoing payload
190-```
191-
192-Naturally, you can also set a default outgoing payload on the `PreparedStatement` instance itself.
193-The code below is roughly equivalent to the one above - except that the payload is not sent
194-with the `PREPARE` request:
195-
196-```java
197-Statement statement = new SimpleStatement("...");
198-PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request
199-ps.setOutgoingPayload(myCustomPayload) // default outgoing payload is now myCustomPayload
200-```
201-
202-But `PreparedStatement` has also a `getIncomingPayload()` method, which, as we already know,
203-can be used to retrieve incoming payloads sent back by the server that prepared the request.
204-
205-When binding a statement - with either `PreparedStatement.bind()` or `PreparedStatement.bind(Object...)`) -
206-`BoundStatement` instances will also inherit payloads.
207-
208-To determine which payload is going to be used as outgoing payload for a bound statement,
209-the following rules apply:
210-
211-1. If the prepared statement has a non-null outgoing payload, all instances of `BoundStatement`
212- created out of it will inherit that payload as their outgoing payload;
213-2. Otherwise, if the prepared statement has a non-null incoming payload, all instances of `BoundStatement`
214- created out of it will inherit that payload as their outgoing payload;
215-3. Otherwise, all instances of `BoundStatement` created out of it
216- won't have any outgoing payload set by default; users can however set an outgoing payload on
217- individual `BoundStatement` instances by calling their `setOutgoingPayload()` method,
218- like in the example below:
219-
220-```java
221-Statement statement = new SimpleStatement("...");
222-PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request
223-BoundStatement bs = ps.bind(1); // no outgoing payload by default
224-bs.setOutgoingPayload(myCustomPayload); // outgoing payload for this specific statement
225-session.execute(statement); // myCustomPayload will be sent with EXECUTE request for this bound statement only
226-```
227-
228-### Debugging custom payloads
229-
230-When debugging custom payloads, set the `com.datastax.driver.core.Message` logger to the `TRACE` level, e.g. with Log4J:
231-
232-```xml
233-<logger name="com.datastax.driver.core.Message">
234- <level value="TRACE"/>
235-</logger>
236-```
237-
238-This will log a message for every request and every response that contains a non-null payload.
239-The log message contains a pretty-printed version of the payload itself, and its total length in bytes.
240-
241-[CASSANDRA-8553]: https://issues.apache.org/jira/browse/CASSANDRA-8553
242-[v4spec]: https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec
243-[qh]: https://issues.apache.org/jira/browse/CASSANDRA-6659
244-[nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
245-[chm]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html
246-[immutablemap]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html
247-[ufe]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/UnsupportedFeatureException.html
248-
deleted features/logging/README.md +0 −305
@@ -1,305 +0,0 @@
1-## Logging
2-
3-### Setup
4-
5-DataStax Java driver uses the popular [SLF4J](http://www.slf4j.org) library to emit log messages;
6-SLF4J has the advantage of providing a logging API that is entirely decoupled from concrete
7-implementations, letting client applications free to seamlessly connect SLF4J to their preferred logging backend.
8-
9-The driver itself does not attempt to configure any concrete logging framework.
10-It is up to client applications using the driver to correctly set up their classpath and
11-runtime configuration to be able to capture log messages emitted by the driver.
12-Concretely, client applications need to provide, at runtime, a *binding* to any logging framework
13-of their choice that is [compatible with SLF4J](http://www.slf4j.org/manual.html#swapping).
14-
15-If your application is built with Maven, this usually involves adding one (runtime) dependency to your POM file.
16-For example, if you intend to use [Logback](http://logback.qos.ch), add the following dependency:
17-
18-```xml
19-<dependency>
20- <groupId>ch.qos.logback</groupId>
21- <artifactId>logback-classic</artifactId>
22- <version>1.1.3</version>
23-</dependency>
24-```
25-
26-If you are using Log4J 1.2 instead, add the following dependency:
27-
28-```xml
29-<dependency>
30- <groupId>org.slf4j</groupId>
31- <artifactId>slf4j-log4j12</artifactId>
32- <version>1.7.12</version>
33-</dependency>
34-```
35-
36-Check [SLF4J's documentation](http://www.slf4j.org/manual.html#projectDep) for examples for
37-other logging frameworks, and for troubleshooting dependency resolution problems.
38-
39-### Configuration
40-
41-Each logging framework has its own configuration rules, but all of them provide
42-different levels (DEBUG, INFO, WARN, ERROR...), different *loggers* or *categories*
43-(messages from different categories or loggers can be filtered out separately or printed out
44-differently), and different *appenders* (message receptacles such as the standard console,
45-the error console, a file on disk, a socket...).
46-
47-Check your logging framework documentation for more information about how to properly configure it.
48-You can also find some configuration examples below.
49-
50-### Useful loggers
51-
52-When debugging the Java driver, the following loggers could be particularly useful
53-and provide hints about what's going wrong.
54-
55-* `com.datastax.driver.core.Cluster`
56- * ERROR
57- * Authentication errors
58- * Unexpected errors when handling events, reconnecting, refreshing schemas
59- * Unexpected events
60- * WARN
61- * Cluster name mismatches
62- * Unreachable contact points
63- * Unsupported protocol versions
64- * Schema disagreements
65- * Ignored notifications due to high contention
66- * INFO
67- * Hosts added or removed
68- * DEBUG
69- * Cluster lifecycle (start, shutdown)
70- * Event delivery notifications (schema changes, topology changes)
71- * Topology change events: hosts Up / Down / Added / Removed
72- * Hosts being ignored
73- * Protocol version negotiation
74- * Reconnection attempts
75- * Schema metadata refreshes
76- * TRACE
77- * Connection pools lifecycle (create, renew, refresh)
78-* `com.datastax.driver.core.Session`
79- * ERROR
80- * Errors related to connection pools
81- * WARN
82- * Problems related to connection pools
83- * DEBUG
84- * Connection pools lifecycle (create, renew, refresh)
85-* `com.datastax.driver.core.RequestHandler`
86- * ERROR
87- * Unexpected errors preparing queries
88- * Queries sent to a bootstrapping host
89- * Unexpected server errors
90- * WARN
91- * Queries sent to an overloaded host
92- * INFO
93- * Unprepared queries
94- * DEBUG
95- * Retry attempts
96- * TRACE
97- * Host currently being queried
98-* `com.datastax.driver.core.Connection`
99- * WARN
100- * Problem setting keyspace
101- * Errors closing Netty channel
102- * DEBUG
103- * Connection lifecycle (open, close, defunct)
104- * Error connecting or writing requests
105- * Heartbeats
106- * TRACE
107- * Authentication progress
108- * Sending requests
109- * Receiving responses
110-* `com.datastax.driver.core.Message`
111- * TRACE
112- * Custom payloads
113-
114-### Logging query latencies
115-
116-The `QueryLogger` provides clients with the ability to log queries
117-executed by the driver, and especially, it allows client to track slow
118-queries, i.e. queries that take longer to complete than a configured
119-threshold in milliseconds.
120-
121-To turn on this feature, you first need to instantiate and register a `QueryLogger` instance:
122-
123-```java
124-Cluster cluster = ...
125-QueryLogger queryLogger = QueryLogger.builder()
126- .withConstantThreshold(...)
127- .withMaxQueryStringLength(...)
128-.build();
129-cluster.register(queryLogger);
130-```
131-
132-Note that `QueryLogger` instances are thread-safe and can be shared cluster-wide.
133-Besides, you can adjust several parameters such as the maximum query string length to be printed,
134-the maximum number of parameters to print, etc. Refer to the
135-`QueryLogger` [API docs][query_logger] for more information.
136-
137-Secondly, you need to adjust your logging framework to accept log messages from the `QueryLogger`. The `QueryLogger`
138-uses 3 different loggers:
139-
140-* `com.datastax.driver.core.QueryLogger.NORMAL` : Used to log normal queries, i.e., queries that completed successfully within a configurable threshold in milliseconds.
141-* `com.datastax.driver.core.QueryLogger.SLOW` : Used to log slow queries, i.e., queries that completed successfully but that took longer than a configurable threshold in milliseconds to complete.
142-* `com.datastax.driver.core.QueryLogger.ERROR`: Used to log unsuccessful queries, i.e., queries that did not complete normally and threw an exception. Note this this logger will also print the full stack trace of the reported exception.
143-
144-You need to set the above loggers to DEBUG level to turn them on. E.g. to track queries
145-that take more than 300 ms to complete, configure your `QueryLogger` with that threshold (see above),
146-then set the `com.datastax.driver.core.QueryLogger.SLOW` logger to DEBUG, e.g. with Log4J:
147-
148-```xml
149- <logger name="com.datastax.driver.core.QueryLogger.SLOW">
150- <level value="DEBUG"/>
151- </logger>
152-```
153-
154-The `QueryLogger` would then print messages such as this for every slow query:
155-
156-```
157-DEBUG [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=?;
158-```
159-
160-As you can see, actual query parameters are not logged; if you want them to be printed as well, set the `com.datastax.driver.core.QueryLogger.SLOW` logger
161-to TRACE instead, e.g. with Log4J:
162-
163-```xml
164- <logger name="com.datastax.driver.core.QueryLogger.SLOW">
165- <level value="TRACE"/>
166- </logger>
167-```
168-
169-The `QueryLogger` would then print messages such as this for every slow query:
170-
171-```
172-TRACE [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=? [user_id=42];
173-```
174-
175-Be careful when logging large query strings (specially batches) and/or queries with considerable amounts of parameters.
176-See the `QueryLogger` [API docs][query_logger] for examples of how to truncate the printed message when necessary.
177-
178-#### Constant vs Dynamic thresholds
179-
180-Currently the `QueryLogger` can be configured to track slow queries using either
181-a constant threshold in milliseconds (which is the default behavior), or
182-a dynamic threshold based on per-host latency percentiles, as computed by `PerHostPercentileTracker`.
183-
184-**Dynamic thresholds are still a beta feature: they haven't been extensively
185-tested yet, and the API is still subject to change.**
186-
187-Refer to the `QueryLogger` [API docs][query_logger] for an example of usage.
188-
189-### Performance Tips
190-
191-* Use asynchronous appenders; both [Log4J](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html)
192-and [Logback](http://logback.qos.ch/manual/appenders.html#AsyncAppender) provide asynchronous appenders
193-that can significantly boost latencies when writing log messages.
194-* While the driver does not provide such capability, it is possible for client applications to hot-reload the log configuration
195-without stopping the application. This usually involves JMX and is available for [Logback](http://logback.qos.ch/manual/jmxConfig.html);
196-Log4J provides a `configureAndWatch()` method but it is not recommended to use it inside J2EE containers (see [FAQ](https://logging.apache.org/log4j/1.2/faq.html#a3.6)).
197-
198-### Logback Example
199-
200-Here is a typical example configuration for Logback. *Please adapt it to your specific needs before using it!*
201-
202-It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
203-By default, only messages with ERROR level or higher are logged.
204-
205-It also turns on slow query tracing as described above.
206-
207-```xml
208-<?xml version="1.0" encoding="UTF-8"?>
209-<configuration>
210-
211- <!-- log INFO or higher messages to the console -->
212- <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
213- <encoder>
214- <pattern>%-5p %msg%n</pattern>
215- </encoder>
216- </appender>
217-
218- <!-- log everything to a rolling file -->
219- <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
220- <file>driver.log</file>
221- <encoder>
222- <pattern>%-5p [%d{ISO8601}] [%t] %F:%L - %msg%n</pattern>
223- </encoder>
224- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
225- <!-- daily rollover -->
226- <fileNamePattern>driver.%d{yyyy-MM-dd}.log</fileNamePattern>
227- <!-- keep 30 days' worth of history -->
228- <maxHistory>30</maxHistory>
229- </rollingPolicy>
230- </appender>
231-
232- <!-- use AsyncAppender for lower latencies -->
233- <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
234- <appender-ref ref="console" />
235- <appender-ref ref="file" />
236- </appender>
237-
238- <!--
239- Turn on slow query logging by setting this logger to DEBUG;
240- set level to TRACE to also log query parameters
241- -->
242- <logger name="com.datastax.driver.core.QueryLogger.SLOW" level="DEBUG" />
243-
244- <root level="ERROR">
245- <appender-ref ref="async" />
246- </root>
247-
248-</configuration>
249-```
250-
251-### Log4J Example
252-
253-Here is a typical example configuration for Log4J. *Please adapt it to your specific needs before using it!*
254-
255-It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
256-By default, only messages with ERROR level or higher are logged.
257-
258-It also turns on slow query tracing as described above.
259-
260-```xml
261-<log4j:configuration>
262-
263- <!-- log INFO or higher messages to the console -->
264- <appender name="console" class="org.apache.log4j.ConsoleAppender">
265- <param name="threshold" value="INFO"/>
266- <layout class="org.apache.log4j.PatternLayout">
267- <param name="ConversionPattern" value="%-5p %m%n"/>
268- </layout>
269- </appender>
270-
271- <!-- log everything to a rolling file -->
272- <appender name="file" class="org.apache.log4j.RollingFileAppender">
273- <param name="file" value="driver.log"/>
274- <param name="append" value="false"/>
275- <param name="maxFileSize" value="1GB"/>
276- <param name="maxBackupIndex" value="10"/>
277- <layout class="org.apache.log4j.PatternLayout">
278- <param name="ConversionPattern" value="%-5p [%d{ISO8601}] [%t] %F:%L - %m%n"/>
279- </layout>
280- </appender>
281-
282- <!-- use AsyncAppender for lower latencies -->
283- <appender name="async" class="org.apache.log4j.AsyncAppender">
284- <param name="BufferSize" value="500"/>
285- <appender-ref ref="file"/>
286- <appender-ref ref="console"/>
287- </appender>
288-
289- <!--
290- Turn on slow query logging by setting this logger to DEBUG;
291- set level to TRACE to also log query parameters
292- -->
293- <logger name="com.datastax.driver.core.QueryLogger.SLOW">
294- <level value="DEBUG"/>
295- </logger>
296-
297- <root>
298- <priority value="ERROR"/>
299- <appender-ref ref="async"/>
300- </root>
301-
302-</log4j:configuration>
303-```
304-
305-[query_logger]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryLogger.html
deleted features/metadata/README.md +0 −194
@@ -1,194 +0,0 @@
1-## Metadata
2-
3-The driver maintains global information about the Cassandra cluster it
4-is connected to. It is available via
5-[Cluster#getMetadata()][getMetadata].
6-
7-[getMetadata]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.html#getMetadata()
8-
9-### Schema metadata
10-
11-Use [getKeyspace(String)][getKeyspace] or [getKeyspaces()][getKeyspaces]
12-to get keyspace-level metadata. From there you can access the keyspace's
13-objects (tables, and UDTs and UDFs if relevant).
14-
15-[getKeyspace]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getKeyspace(java.lang.String)
16-[getKeyspaces]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getKeyspaces()
17-
18-#### Refreshes
19-
20-Schema metadata gets refreshed in the following circumstances:
21-
22-* **schema changes via the driver**: after successfully executing a
23- schema-altering query (ex: `CREATE TABLE`), the driver waits for
24- schema agreement (see below), then refreshes the schema.
25-* **third-party schema changes**: if another client (cqlsh, other driver
26- instance...) changes the schema, the driver gets notified by Cassandra
27- via a push notification. It refreshes the schema directly (there is no
28- need to wait for schema agreement since Cassandra has already done it).
29-
30-#### Subscribing to schema changes
31-
32-Users interested in being notified of schema changes can implement the
33-[SchemaChangeListener][SchemaChangeListener] interface.
34-
35-Every listener must [be registered][registerListener] against a `Cluster` instance:
36-
37-```java
38-Cluster cluster = ...
39-SchemaChangeListener myListener = ...
40-cluster.register(myListener);
41-```
42-
43-Once registered, the listener will be notified of all schema changes detected by the driver,
44-regardless of where they originate from.
45-
46-Note that it is preferable to register a listener only *after* the cluster is fully initialized,
47-otherwise the listener could be notified with a great deal of "Added" events as
48-the driver builds the schema metadata from scratch for the first time.
49-
50-[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SchemaChangeListener.html
51-[registerListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#register(com.datastax.driver.core.SchemaChangeListener)
52-
53-#### Schema agreement
54-
55-Schema changes need to be propagated to all nodes in the cluster. Once
56-they have settled on a common version, we say that they are in
57-agreement.
58-
59-As explained above, the driver waits for schema agreement after
60-executing a schema-altering query. This is to ensure that subsequent
61-requests (which might get routed to different nodes) see an up-to-date
62-version of the schema.
63-
64-```ditaa
65- Application Driver Cassandra
66-------+--------------------+------------------+-----
67- | | |
68- | CREATE TABLE... | |
69- |------------------->| |
70- | | send request |
71- | |----------------->|
72- | | |
73- | | success |
74- | |<-----------------|
75- | | |
76- | /--------------------\ |
77- | :Wait until all nodes+------>|
78- | :agree (or timeout) : |
79- | \--------------------/ |
80- | | ^ |
81- | | | |
82- | | +---------|
83- | | |
84- | | refresh schema |
85- | |----------------->|
86- | |<-----------------|
87- | complete query | |
88- |<-------------------| |
89- | | |
90-```
91-
92-The schema agreement wait is performed synchronously, so the `execute`
93-call -- or the completion of the `ResultSetFuture` if you use the async
94-API -- will only return after it has completed.
95-
96-The check is implemented by repeatedly querying system tables for the
97-schema version reported by each node, until they all converge to the
98-same value. If that doesn't happen within a given timeout, the driver
99-will give up waiting. The default timeout is 10 seconds, it can be
100-customized when building your cluster:
101-
102-```java
103-Cluster cluster = Cluster.builder()
104- .addContactPoint("127.0.0.1")
105- .withMaxSchemaAgreementWaitSeconds(20)
106- .build();
107-```
108-
109-After executing a statement, you can check whether schema agreement was
110-successful or timed out:
111-
112-```java
113-ResultSet rs = session.execute("CREATE TABLE...");
114-if (rs.getExecutionInfo().isSchemaInAgreement()) {
115- // schema is in agreement
116-} else {
117- // schema agreement timed out
118-}
119-```
120-
121-You can also perform an on-demand check at any time:
122-
123-```java
124-if (cluster.getMetadata().checkSchemaAgreement()) {
125- // schema is in agreement
126-} else {
127- // schema is not in agreement
128-}
129-```
130-
131-The on-demand check does not retry, it only queries system tables once
132-(so `maxSchemaAgreementWaitSeconds` does not apply). If you need
133-retries, you'll have to schedule them yourself (for example with a
134-custom executor).
135-
136-Check out the API docs for the features in this section:
137-
138-* [withMaxSchemaAgreementWaitSeconds(int)](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.Builder.html#withMaxSchemaAgreementWaitSeconds(int))
139-* [isSchemaInAgreement()](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ExecutionInfo.html#isSchemaInAgreement())
140-* [checkSchemaAgreement()](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#checkSchemaAgreement())
141-
142-
143-### Token metadata
144-
145-This feature is probably of less interest to regular driver users, but
146-it will be useful if you're writing an analytics client on top of the
147-driver.
148-
149-[Metadata][metadata] exposes a number of methods to manipulate tokens
150-and ranges: [getTokenRanges()][getTokenRanges], [getTokenRanges(String
151-keyspace, Host host)][getTokenRanges2], [getReplicas(String keyspace,
152-TokenRange range)][getReplicas], [newToken(String)][newToken] and
153-[newTokenRange(Token start, Token end)][newTokenRange].
154-
155-[TokenRange][TokenRange] provides various operations on ranges
156-(splitting, merging, etc.).
157-
158-Each host exposes its primary tokens as [getTokens()][getTokens].
159-
160-Finally, you can inject tokens in CQL queries with
161-[BoundStatement#setToken][setToken], and retrieve them from results with
162-[Row#getToken][getToken] and [Row#getPartitionKeyToken][getPKToken].
163-
164-As an example, here is how you could compute the splits to partition a
165-job (pseudocode):
166-
167-```
168-metadata = cluster.getMetadata()
169-for range : metadata.getTokenRanges() {
170- hosts = metadata.getReplicas(keyspace, range)
171- int n = estimateNumberOfSplits() // more on that below
172- for split : range.splitEvenly(n)
173- // pick a host to process split
174-}
175-```
176-
177-For `estimateNumberOfSplits`, you need a way to estimate the total
178-number of partition keys (this is what analytics clients would
179-traditionally do with the Thrift operation `describe_splits_ex`).
180-Starting with Cassandra 2.1.5, this information is available in a system
181-table (see
182-[CASSANDRA-7688](https://issues.apache.org/jira/browse/CASSANDRA-7688)).
183-
184-[metadata]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html
185-[getTokenRanges]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getTokenRanges()
186-[getTokenRanges2]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getTokenRanges(java.lang.String,%20com.datastax.driver.core.Host)
187-[getReplicas]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getReplicas(java.lang.String,%20com.datastax.driver.core.TokenRange)
188-[newToken]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#newToken(java.lang.String)
189-[newTokenRange]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#newTokenRange(com.datastax.driver.core.Token,%20com.datastax.driver.core.Token)
190-[TokenRange]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TokenRange.html
191-[getTokens]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Host.html#getTokens()
192-[setToken]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BoundStatement.html#setToken(int,%20com.datastax.driver.core.Token)
193-[getToken]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Row.html#getToken(int)
194-[getPKToken]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Row.html#getPartitionKeyToken()
deleted features/native_protocol/README.md +0 −112
@@ -1,112 +0,0 @@
1-## Native protocol
2-
3-The native protocol defines the format of the binary messages exchanged
4-between the driver and Cassandra over TCP. As a driver user, you don't
5-need to know the fine details (although the protocol spec is [in the
6-Cassandra codebase][native_spec] if you're curious); the most visible
7-aspect is that some features are only available with specific protocol
8-versions.
9-
10-[native_spec]: https://github.com/apache/cassandra/tree/trunk/doc
11-
12-### Compatibility matrix
13-
14-By default, the protocol version is negotiated between the driver and
15-Cassandra when the first connection is established. Both sides are
16-backward-compatible with older versions:
17-
18-<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
19-<tr><td>&nbsp;</td><td>Cassandra: 1.2.x<br/>(DSE 3.2)</td><td>2.0.x<br/>(DSE 4.0 to 4.6)</td><td>2.1.x<br/>(DSE 4.7)</td><td>2.2.x</td><td>3.0.x</td></tr>
20-<tr><td>Driver: 1.0.x</td> <td>v1</td> <td>v1</td> <td>v1</td> <td>v1</td> <td>Unsupported <i>(1)</i></td> </tr>
21-<tr><td>2.0.x to 2.1.1</td> <td>v1</td> <td>v2</td> <td>v2</td> <td>v2</td> <td>Unsupported <i>(1)</i></td> </tr>
22-<tr><td>2.1.2 to 2.1.x</td> <td>v1</td> <td>v2</td> <td>v3</td> <td>v3</td> <td>Unsupported <i>(2)</i></td> </tr>
23-<tr><td>3.x</td> <td>v1</td> <td>v2</td> <td>v3</td> <td>v4</td> <td>v4</td> </tr>
24-</table>
25-
26-*(1) Cassandra 3.0 does not support protocol versions v1 and v2*
27-
28-*(2) There is a matching protocol version (v3), but the driver 2.1.x can't read the new system table format of Cassandra 3.0*
29-
30-For example, if you use version 2.1.5 of the driver to connect to
31-Cassandra 2.0.9, the maximum version you can use (and the one you'll get
32-by default) is protocol v2 (third row, second column). If you use the
33-same version to connect to Cassandra 2.1.4, you can use protocol v3.
34-
35-### Controlling the protocol version
36-
37-To find out which version you're currently using, use
38-[ProtocolOptions#getProtocolVersion()][gpv]:
39-
40-```java
41-ProtocolVersion myCurrentVersion = cluster.getConfiguration()
42- .getProtocolOptions()
43- .getProtocolVersionEnum();
44-```
45-
46-The protocol version can not be changed at runtime. However, you can
47-force a given version at initialization:
48-
49-```java
50-Cluster cluster = Cluster.builder()
51- .addContactPoint("127.0.0.1")
52- .withProtocolVersion(ProtocolVersion.V2)
53- .build();
54-```
55-
56-If you specify a version that is not compatible with your current
57-driver/Cassandra combination, you'll get an error:
58-
59-```
60-Exception in thread "main" com.datastax.driver.core.exceptions.NoHostAvailableException:
61-All host(s) tried for query failed
62-(tried: /127.0.0.1:9042 (com.datastax.driver.core.UnsupportedProtocolVersionException:
63- [/127.0.0.1:9042] Host /127.0.0.1:9042 does not support protocol version V3 but V2))
64-```
65-
66-[gpv]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion()
67-
68-#### Protocol version with mixed clusters
69-
70-If you have a cluster with mixed versions (for example, while doing a
71-rolling upgrade of Cassandra), note that **the protocol version will be
72-negotiated with the first host the driver connects to**.
73-
74-This could lead to the following situation (assuming you use driver
75-2.1.2+):
76-
77-* the first contact point is a 2.1 host, so the driver negotiates
78- protocol v3;
79-* while connecting to the rest of the cluster, the driver contacts a 2.0
80- host using protocol v3, which fails; an error is logged and this host
81- will be permanently ignored.
82-
83-To avoid this issue, you can use one the following workarounds:
84-
85-* always force a protocol version at startup. You keep it at v2 while
86- the rolling upgrade is happening, and only switch to v3 when the whole
87- cluster has switched to Cassandra 2.1;
88-* ensure that the list of initial contact points only contains hosts
89- with the oldest version (2.0 in this example).
90-
91-
92-### New features by protocol version
93-
94-#### v1 to v2
95-
96-* bound variables in simple statements
97- ([Session#execute(String, Object...)](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#execute(java.lang.String,%20java.lang.Object...)))
98-* [batch statements](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BatchStatement.html)
99-* [query paging](../paging/)
100-
101-#### v2 to v3
102-
103-* the number of stream ids per connection goes from 128 to 32768 (see
104- [Connection pooling](../pooling/))
105-* [serial consistency on batch statements](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BatchStatement.html#setSerialConsistencyLevel(com.datastax.driver.core.ConsistencyLevel))
106-* [client-side timestamps](../query_timestamps/)
107-
108-#### v3 to v4
109-
110-* [query warnings](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ExecutionInfo.html#getWarnings())
111-* allowed unset values in bound statements
112-* [Custom payloads](../custom_payloads/)
deleted features/object_mapper/.nav +0 −3
@@ -1,3 +0,0 @@
1-creating
2-using
3-custom_codecs
No newline at the end of the file
deleted features/object_mapper/README.md +0 −18
@@ -1,18 +0,0 @@
1-# Object Mapper
2-
3-Version 2.1 of the driver introduces a simple object mapper, which
4-avoids most of the boilerplate when converting your domain classes to
5-and from query results. It handles basic CRUD operations in Cassandra tables
6-containing UDTs, collections and all native CQL types.
7-
8-The mapper is published as a separate Maven artifact:
9-
10-```xml
11-<dependency>
12- <groupId>com.datastax.cassandra</groupId>
13- <artifactId>cassandra-driver-mapping</artifactId>
14- <version>3.0.0-rc1</version>
15-</dependency>
16-```
17-
18-This documentation is organized in subsections describing mapper features.
deleted features/object_mapper/creating/README.md +0 −224
@@ -1,224 +0,0 @@
1-## Definition of mapped classes
2-
3-The object mapper is configured by annotations on the mapped classes.
4-
5-### Creating a table entity
6-
7-A table entity is a class that will be mapped to a table in Cassandra.
8-It is annotated with [@Table][table]:
9-
10-```
11-CREATE TABLE user (user_id uuid PRIMARY KEY, name text);
12-```
13-
14-```java
15-@Table(keyspace = "ks", name = "users",
16- readConsistency = "QUORUM",
17- writeConsistency = "QUORUM",
18- caseSensitiveKeyspace = false,
19- caseSensitiveTable = false)
20-public static class User {
21- @PartitionKey
22- @Column(name = "user_id")
23- private UUID userId;
24- private String name;
25- // ... constructors / getters / setters
26-}
27-```
28-
29-`@Table` takes the following options:
30-
31-- `keyspace`: the keyspace for the table.
32-- `name`: the name of the table in the database.
33-- `caseSensitiveKeyspace`: whether the keyspace name is [case-sensitive].
34-- `caseSensitiveTable`: whether the table name is [case-sensitive].
35-- `readConsistency`: the [consistency level] that will be used on each
36- get operation in the mapper. (if unspecified, it defaults to the
37- cluster-wide setting)
38-- `writeConsistency`: the [consistency level] that will be used on each
39- save, or delete operation in the mapper. (if unspecified, it defaults
40- to the cluster-wide setting)
41-
42-The class must provide a default constructor, and all fields (except the
43-ones annotated `@Transient`) must have corresponding setters and
44-getters.
45-
46-[table]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Table.html
47-[case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html
48-[consistency level]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ConsistencyLevel.html
49-
50-#### Column names
51-
52-By default, the mapper tries to map each Java property to a
53-case insensitive column of the same name. If you want to use a different
54-name, or [case-sensitive] names, use the [@Column][column] annotation on
55-the field.
56-
57-[column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html
58-
59-#### Primary key fields
60-
61-[@PartitionKey][pk] and [@ClusteringColumn][cc] are used to indicate the
62-[partition key][pks] and [clustering columns][pks]. In the case of a
63-composite partition key or multiple clustering columns, the integer
64-value indicates the position of the column in the key:
65-
66-```
67-CREATE TABLE sales(countryCode text, areaCode text, sales int,
68- PRIMARY KEY((countryCode, area Code)));
69-```
70-
71-```java
72-@PartitionKey(0)
73-private String countryCode;
74-@PartitionKey(1)
75-private String areaCode;
76-```
77-
78-The order of the indices must match that of the columns in the table
79-declaration.
80-
81-[pk]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/PartitionKey.html
82-[cc]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/ClusteringColumn.html
83-[pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html
84-
85-#### Computed fields
86-
87-[@Computed][computed] can be used on fields that are the result of a
88-computation on the Cassandra side. Typically a function call. Native
89-functions in Cassandra like `writetime()` or [User Defined Functions] are
90-supported.
91-
92-```java
93-@Computed("ttl(name)")
94-Integer ttl;
95-```
96-
97-The CQL return type of function must match the type of the field,
98-otherwise an exception will be thrown.
99-
100-Computed fields are ignored when saving an entity.
101-
102-`@Computed` does not support case-sensitivity. If the expression
103-contains case-sensitive column or function names, you'll have to escape
104-them:
105-
106-```java
107-@Computed("\"myFunction\"(\"myColumn\")")
108-int f;
109-```
110-
111-Finally, computed fields are only supported with [basic read
112-operations](../using/#basic-crud-operations) at this time.
113-Support in [accessors](../using/#accessors) in planned for a future
114-version (see
115-[JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)).
116-
117-[User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/
118-[computed]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Computed.html
119-
120-#### Transient fields
121-
122-[@Transient][transient] can be used to prevent a field from being mapped.
123-
124-[transient]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Transient.html
125-
126-### Mapping User Types
127-
128-[User Defined Types] can also be mapped by using [@UDT][udt]:
129-
130-```
131-CREATE TYPE address (street text, zip_code int);
132-```
133-
134-```java
135-@UDT(keyspace = "ks", name = "address")
136-class Address {
137- private String street;
138- @Field(name = "zip_code")
139- private int zipCode;
140- // ... constructors / getters / setters
141-}
142-```
143-
144-`@UDT` takes the following options:
145-
146-- `keyspace`: the keyspace for the UDT.
147-- `name`: the name of the UDT in the database.
148-- `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive.
149-- `caseSensitiveType`: whether the UDT name is case-sensitive.
150-
151-The class must provide a default constructor, and all fields (except the
152-ones annotated `@Transient`) must have corresponding setters and
153-getters.
154-
155-As in table entities, fields are mapped to an UDT field of the same
156-name by default. To declare a different name or use case-sensitivity,
157-use the [@Field][field] annotation:
158-
159-```java
160-@Field(name = "zip_code")
161-private int zipCode;
162-```
163-
164-When a table has a UDT column, the mapper will automatically map it to
165-the corresponding class:
166-
167-```
168-CREATE TABLE company (company_id uuid PRIMARY KEY, name text, address address);
169-```
170-
171-```java
172-public static class Company {
173- @PartitionKey
174- @Column(name = "company_id")
175- private UUID companyId;
176- private String name;
177- private Address address;
178-}
179-```
180-
181-(this also works with UDTs inside collections or other UDTs, with
182-arbitrary level of nesting)
183-
184-[User Defined Types]:http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/reference/userDefinedTypes.html
185-[udt]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/UDT.html
186-[field]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Field.html
187-
188-### Mapping collections
189-
190-Java collections will be automatically mapped into corresponding
191-Cassandra types. As in Cassandra, collections can contain all native
192-types and all [user types](#mapping-user-types) previously defined is
193-the database.
194-
195-Collection and UDT fields should be annotated to indicate whether they are
196-frozen. Currently this is only for informational purposes (the mapper
197-won't check that the declarations match the rules in Cassandra).
198-However it is a good idea to keep using these annotations and make sure
199-they match the schema, in anticipation for the schema generation features
200-that will be added in a future version.
201-The default annotation is [@Frozen][frozen], [@FrozenKey][frozenkey] and
202-[@FrozenValue][frozenvalue]` are also provided for convenience:
203-
204-```java
205-// Will be mapped as a 'list<text>'
206-private List<String> stringList;
207-
208-// Will be mapped as a 'frozen<list<text>>'
209-@Frozen
210-private List<String> frozenStringList;
211-
212-// Will be mapped as 'map<frozen<address>, frozen<list<text>>>'
213-@FrozenKey
214-@FrozenValue
215-private Map<Address, List<String>> frozenKeyValueMap;
216-
217-// Will be mapped as 'map<text, frozen<list<address>>>'
218-@FrozenValue
219-private Map<String, List<Address>> frozenValueMap;
220-```
221-
222-[frozen]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Frozen.html
223-[frozenkey]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenKey.html
224-[frozenvalue]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenValue.html
deleted features/object_mapper/custom_codecs/README.md +0 −147
@@ -1,147 +0,0 @@
1-# Using custom codecs
2-
3-The mapper can take advantage of [custom codecs](../../custom_codecs/)
4-to apply custom conversions to mapped columns and fields.
5-
6-## Declaring codecs
7-
8-Let's assume you have a table containing a timestamp column:
9-
10-```
11-create table user(id int primary key, birth timestamp);
12-```
13-
14-You've created a custom class, and the codec to convert it:
15-
16-```java
17-public class MyCustomDate { ... }
18-
19-public class MyCustomDateCodec extends TypeCodec<MyCustomDate> {
20- public MyCustomDate() {
21- super(DataType.timestamp(), MyCustomDate.class);
22- }
23- ...
24-}
25-```
26-
27-### Pre-registered codecs
28-
29-If you register your codec with the mapper's underlying `Cluster`, it
30-will be automatically available to the mapper:
31-
32-```java
33-Cluster cluster = Cluster.builder()
34- .addContactPoint("127.0.0.1")
35- .withCodecRegistry(
36- new CodecRegistry().register(new MyCustomDateCodec())
37- ).build();
38-
39-MappingManager mappingManager = new MappingManager(cluster.connect());
40-```
41-
42-You can normally create your mapped classes using your custom type,
43-without any additional configuration:
44-
45-```java
46-@Table(name = "user")
47-public class User {
48- @PartitionKey
49- private int id;
50- private MyCustomDate birth;
51-
52- ... // getters and setters
53-}
54-```
55-
56-This also works in accessors:
57-
58-```java
59-@Accessor
60-interface UserAccessor {
61- @Query("update user set birth = :b where id = :i)
62- void updateBirth(@Param("i") int id,
63- @Param("b") MyCustomDate birth);
64-}
65-```
66-
67-### One-time declaration
68-
69-Sometimes you might want to use your codec only for one particular
70-column/field. In that case you won't register it when initializing the
71-`Cluster`:
72-
73-```java
74-Cluster cluster = Cluster.builder()
75- .addContactPoint("127.0.0.1")
76- .build();
77-
78-MappingManager mappingManager = new MappingManager(cluster.connect());
79-```
80-
81-Instead, reference the codec's class in the [@Column][column]
82-annotation:
83-
84-```java
85-@Table(name = "user")
86-public class User {
87- @PartitionKey
88- private int id;
89- @Column(codec = MyCustomDateCodec.class)
90- private MyCustomDate birth;
91-
92- ... // getters and setters
93-}
94-```
95-
96-The class must have a no-arg constructor. The mapper will create an
97-instance (one per column) and cache it for future use.
98-
99-This also works with [@Field][field] and [@Param][param] annotations.
100-
101-[column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html
102-[field]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Field.html
103-[param]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Param.html
104-
105-
106-## Implicit UDT codecs
107-
108-The mapper uses custom codecs internally to handle UDT conversions: when
109-you register an [entity](../using/#entity-mappers), the mapper inspects
110-the type of all fields to find classes annotated with
111-[@UDT](../creating/#mapping-user-types) (this works recursively with
112-nested UDTs and collections). For each class, the mapper creates a codec
113-and registers it with the underlying `Cluster`.
114-
115-```java
116-@UDT(name = "address")
117-public class Address { ... }
118-
119-@Entity(name = "user")
120-public class User {
121- ...
122- private Address address;
123- ...
124-}
125-
126-Mapper<User> userMapper = mappingManager.mapper(User.class);
127-
128-// Codec is now registered for Address <-> CQL address
129-```
130-
131-A nice side-effect is that you can now use the `@UDT`-annotated class
132-with any driver method, not just mapper methods:
133-
134-```java
135-Row row = session.execute("select address from user where id = 1").one();
136-Address address = row.get("address", Address.class);
137-```
138-
139-If you don't use entity mappers but still want the convenience of the
140-UDT codec for core driver methods, the mapper provides a way to create
141-it independently:
142-
143-```java
144-mappingManager.udtCodec(Address.class);
145-
146-// Codec is now registered
147-```
deleted features/object_mapper/using/README.md +0 −295
@@ -1,295 +0,0 @@
1-## Using the mapper
2-
3-First, create a [MappingManager]. It wraps an existing [Session]
4-instance:
5-
6-```java
7-MappingManager manager = new MappingManager(session);
8-```
9-
10-`MappingManager` is thread-safe and can be safely shared throughout your
11-application. You would typically create one instance at startup, right
12-after your `Session`.
13-
14-Note that `MappingManager` will initialize the `Session` if not
15-previously done (this was not the case in previous driver versions; if
16-this is a problem for you, see `MappingManager(session, protocolVersion)`).
17-
18-### Entity mappers
19-
20-Each entity class (annotated with `@Table`) is managed by a dedicated
21-[Mapper] object. You obtain this object from the `MappingManager`:
22-
23-```java
24-Mapper<User> mapper = manager.mapper(User.class);
25-```
26-
27-`Mapper` objects are thread-safe. The manager caches them internally, so
28-calling `manager#mapper` more than once for the same class will return
29-the previously generated mapper.
30-
31-[Mapper]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/Mapper.html
32-[MappingManager]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/MappingManager.html
33-[Session]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html
34-
35-#### Basic CRUD operations
36-
37-To save an object, use `Mapper#save`:
38-
39-```java
40-UUID userId = ...;
41-User u = new User(userId, "John Doe", new Address("street", 01000));
42-mapper.save(u);
43-```
44-
45---------------
46-
47-To retrieve an object, use `Mapper#get`:
48-
49-```java
50-UUID userId = ...;
51-User u = mapper.get(userId);
52-```
53-
54-`get`'s arguments must match the partition key components (number of
55-arguments and their types).
56-
57---------------
58-
59-To delete a row in a table, use `Mapper#delete`. This method support
60-deleting a row given either its primary keys, or the object to delete:
61-
62-```java
63-UUID userId = ...;
64-mapper.delete(userId);
65-mapper.delete(u);
66-```
67-
68---------------
69-
70-All these CRUD operations are synchronous, but the `Mapper` provides
71-their asynchronous equivalents:
72-
73-```java
74-ListenableFuture<Void> saveFuture = mapper.saveAsync(u);
75-ListenableFuture<User> userFuture = mapper.getAsync(userId);
76-ListenableFuture<Void> deleteFuture = mapper.deleteAsync(userId);
77-```
78-
79-#### Mapper options
80-
81-The basic CRUD operations accept additional options to customize the
82-underlying query:
83-
84-- `ttl`: add a time-to-live value for the operation.
85-- `timestamp`: add a timestamp value for the operation.
86-- `consistencyLevel`: specify a consistency level.
87-- `tracing`: set tracing flag for the query.
88-- `saveNullFields`: if set to true, fields with value `null` in an
89- instance that is to be persisted will be explicitly written as `null`
90- in the query. If set to false, fields with null value won't be included
91- in the write query (thus avoiding tombstones). If not specified, the
92- default behavior is to persist `null` fields.
93-
94-To use options, add them to the mapper call after regular parameters:
95-
96-```java
97-import static com.datastax.driver.mapping.Mapper.Option.*;
98-
99-mapper.save(new User(userId, "helloworld"),
100- timestamp(123456L), tracing(true), ttl(42));
101-```
102-
103-Some options don't apply to all operations:
104-
105-<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
106- <tr> <td><b>Option</b></td> <td><b>save/saveQuery</b></td> <td><b>get/getQuery</b></td> <td><b>delete/deleteQuery</b></td></tr>
107- <tr> <td>Ttl</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
108- <tr> <td>Timestamp</td> <td>yes</td> <td>no</td> <td>yes</td> </tr>
109- <tr> <td>ConsistencyLevel</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
110- <tr> <td>Tracing</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
111- <tr> <td>SaveNullFields</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
112-</table>
113-
114-Note that `Option.consistencyLevel` is redundant with the consistency
115-level defined by [@Table](../creating/#creating-a-table-entity).
116-If both are defined, the option will take precedence over the
117-annotation.
118-
119-Default options can be defined for each type of operation:
120-
121-```java
122-mapper.setDefaultGetOption(tracing(true), consistencyLevel(QUORUM));
123-mapper.setDefaultSaveOption(saveNullFields(false));
124-mapper.setDefaultDeleteOption(consistencyLevel(ONE));
125-
126-// Given the defaults above, this will use tracing(true), consistencyLevel(ONE)
127-mapper.get(uuid, consistencyLevel(ONE));
128-```
129-
130-To reset default options, use the following methods:
131-
132-```java
133-mapper.resetDefaultGetOption();
134-mapper.resetDefaultSaveOption();
135-mapper.resetDefaultDeleteOption();
136-```
137-
138-#### Access to underlying `Statement`s
139-
140-Instead of performing an operation directly, it's possible to ask the
141-`Mapper` to just return the corresponding `Statement` object. This gives
142-the client a chance to customize the statement before executing it.
143-
144-- `Mapper.saveQuery(entity)`: returns a statement generated by the
145- mapper to save `entity` into the database.
146-- `Mapper.getQuery(userId)`: returns a statement to select a row in the
147- database, selected on the given `userId`, and matching the mapped
148- object structure.
149-- `Mapper.deleteQuery(userID)`: returns a statement delete a row in the
150- database given the `userId` provided. This method can also accept a
151- mapped object instance.
152-
153-#### Manual mapping
154-
155-`Mapper#map` provides a way to converts the results of a regular query:
156-
157-```java
158-ResultSet results = session.execute("SELECT * FROM user");
159-Result<User> users = mapper.map(results);
160-for (User u : users) {
161- System.out.println("User : " + u.getUserId());
162-}
163-```
164-
165-This method will ignore:
166-
167-* extra columns in the `ResultSet` that are not mapped for this entity.
168-* mapped fields that are not present in the `ResultSet` (setters won't
169- be called so the value will be the one after invocation of the class's
170- default constructor).
171-
172-[Result] is similar to `ResultSet` but for a given mapped class.
173-It provides methods `one()`, `all()`, `iterator()`, `getExecutionInfo()`
174-and `isExhausted()`. Note that iterating the `Result` will consume the
175-`ResultSet`, and vice-versa.
176-
177-[Result]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/Result.html
178-
179-### Accessors
180-
181-`Accessor`s provide a way to map custom queries not supported by the
182-default entity mappers.
183-
184-To create an accessor, define a Java interface and annotate each method
185-to provide the corresponding CQL query:
186-
187-```java
188-@Accessor
189-public interface UserAccessor {
190- @Query("SELECT * FROM user")
191- Result<User> getAll();
192-}
193-```
194-
195-The `MappingManager` can then process this class and generate an
196-implementation:
197-
198-```java
199-UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
200-User user = userAccessor.getOne(uuid);
201-```
202-
203-Like mappers, accessors are cached at the manager level and thus, are
204-thread-safe/sharable.
205-
206-#### Parameters
207-
208-A query can have bind markers, that will be set with the method's
209-arguments.
210-
211-With unnamed markers, the order of the arguments must match the order of
212-the markers:
213-
214-```java
215-@Query("insert into user (id, name) values (?, ?)")
216-ResultSet insert(UUID userId, String name);
217-```
218-
219-With named markers, use [@Param][param] to indicate which parameter
220-corresponds to which marker:
221-
222-```java
223-@Query("insert into user (userId, name) values (:u, :n)")
224-ResultSet insert(@Param("u") UUID userId, @Param("n") String name);
225-```
226-
227-[param]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Param.html
228-
229-If a method argument is a Java enumeration, it must be annotated with
230-`@Enumerated` to indicate how to convert it to a CQL type (the rules are
231-the same as in [mapping definition](../creating/#enumerations)):
232-
233-```java
234-@Query("insert into user (key, gender) values (?,?)")
235-ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value);
236-```
237-
238-#### Return type
239-
240-The declared return type of each method affects how the query will get
241-executed:
242-
243-<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
244- <tr> <td><b>Return type</b></td> <td><b>Effect</b></td> </tr>
245- <tr>
246- <td><code>void</code></td>
247- <td>Synchronous execution, discards the results of the query.</td>
248- </tr>
249- <tr>
250- <td><code>ResultSet</code></td>
251- <td>Synchronous execution, returns unmapped results.</td>
252- </tr>
253- <tr>
254- <td><code>T</code></td>
255- <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns the first row (or <code>null</code> if there are no results).</td>
256- </tr>
257- <tr>
258- <td><code>Result&lt;T&gt;</code></td>
259- <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns a list of mapped objects.</td>
260- </tr>
261- <tr>
262- <td><code>ResultSetFuture</code></td>
263- <td>Asynchronous execution, returns unmapped results.</td>
264- </tr>
265- <tr>
266- <td><code>ListenableFuture&lt;T&gt;</code></td>
267- <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns the first row (or <code>null</code> if there are no results).</td>
268- </tr>
269- <tr>
270- <td><code>ListenableFuture&lt;Result&lt;T&gt;&gt;</code></td>
271- <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns a list of mapped objects.</td>
272- </tr>
273-</table>
274-
275-Example:
276-
277-```java
278-@Query("SELECT * FROM user")
279-public ListenableFuture<Result<User>> getAllAsync();
280-```
281-
282-
283-#### Customizing the statement
284-
285-It is possible to customize query parameters to include in a `Accessor`
286-query with the annotation [@QueryParameters]. Then, options like
287-*consistency level*, *fetchsize* or *tracing* are settable:
288-
289-```java
290-@Query("SELECT * FROM ks.users")
291-@QueryParameters(consistency="QUORUM")
292-public ListenableFuture<Result<User>> getAllAsync();
293-```
294-
295-[@QueryParameters]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/QueryParameters.html
deleted features/paging/README.md +0 −268
@@ -1,268 +0,0 @@
1-## Paging
2-
3-When a query returns many rows, it would be inefficient to return them
4-as a single response message. Instead, the driver breaks the results
5-into *pages* which get returned as they are needed.
6-
7-### Setting the fetch size
8-
9-The *fetch size* specifies how many rows will be returned at once by
10-Cassandra (in other words, it's the size of each page).
11-
12-You can set a default fetch size globally for a `Cluster` instance:
13-
14-```java
15-// At initialization:
16-Cluster cluster = Cluster.builder()
17- .addContactPoint("127.0.0.1")
18- .withQueryOptions(new QueryOptions().setFetchSize(2000))
19- .build();
20-
21-// Or at runtime:
22-cluster.getConfiguration().getQueryOptions().setFetchSize(2000);
23-```
24-
25-The fetch size can also be set on a statement:
26-
27-```java
28-Statement statement = new SimpleStatement("your query");
29-statement.setFetchSize(2000);
30-```
31-
32-If the fetch size is set on a statement, it will take precedence;
33-otherwise, the cluster-wide value (which defaults to 5000) will be used.
34-
35-Note that setting a fetch size doesn't mean that Cassandra will always
36-return the exact number of rows, it is possible that it returns slightly
37-more or less results.
38-
39-### Result set iteration
40-
41-The fetch size limits the number of results that are returned in one
42-page; if you iterate past that, the driver will run background queries
43-to fetch subsequent pages. Here's an example with a fetch size of 20:
44-
45-```ditaa
46- client Session Cassandra
47- --+--------------+---------------------------------+-----
48- |execute(query)| |
49- |------------->| |
50- | | query rows 1 to 20 |
51- | |-------------------------------->|
52- | | |
53- | |create |
54- | |------>ResultSet |
55- | | |
56-+-----+--------+-----------------+-+ |
57-|For i in 1..20| | | |
58-+--------------+ | | |
59-| | get next row | | |
60-| |------------------------->| | |
61-| | row i | | |
62-| |<-------------------------| | |
63-| | | | |
64-+-----+--------------------------+-+ |
65- | | |
66- | | |
67- | get next row | |
68- |------------------------->| |
69- | | query rows 21 to 40 |
70- | |-------------------->|
71- | row 21 | |
72- |<------------------------ | |
73-```
74-
75-By default, the background fetch happens at the last moment, when there
76-are no more "local" rows available. If you need finer control, the
77-[ResultSet][result_set] interface provides the following methods:
78-
79-* `getAvailableWithoutFetching()` and `isFullyFetched()` to check the
80- current state;
81-* `fetchMoreResults()` to force a page fetch.
82-
83-Here's how you could use these methods to pre-fetch the next page in
84-advance, in order to avoid the performance hit at the end of each page:
85-
86-```java
87-ResultSet rs = session.execute("your query");
88-for (Row row : rs) {
89- if (rs.getAvailableWithoutFetching() == 100 && !rs.isFullyFetched())
90- rs.fetchMoreResults(); // this is asynchronous
91- // Process the row ...
92- System.out.println(row);
93-}
94-```
95-
96-If you use paging with the async API, you'll also want to use those
97-methods to avoid triggering synchronous fetches unintentionally; see
98-[async paging](../async/#async-paging).
99-
100-
101-### Saving and reusing the paging state
102-
103-Sometimes it is convenient to save the paging state in order to restore
104-it later. For example, consider a stateless web service that displays a
105-list of results with a link to the next page. When the user clicks that
106-link, we want to run the exact same query, except that the iteration
107-should start where we stopped on the previous page.
108-
109-To do so, the driver exposes a [PagingState][paging_state] object that represents
110-where we were in the result set when the last page was fetched:
111-
112-```java
113-ResultSet resultSet = session.execute("your query");
114-// iterate the result set...
115-PagingState pagingState = resultSet.getExecutionInfo().getPagingState();
116-```
117-
118-This object can be serialized to a `String` or a byte array:
119-
120-```java
121-String string = pagingState.toString();
122-byte[] bytes = pagingState.toBytes();
123-```
124-
125-This serialized form can be saved in some form of persistent storage to
126-be reused later. In our web service example, we would probably save the
127-string version as a query parameter in the URL to the next page
128-(`http://myservice.com/results?page=<...>`). When that value is
129-retrieved later, we can deserialize it and reinject it in a statement:
130-
131-```java
132-PagingState pagingState = PagingState.fromString(string);
133-Statement st = new SimpleStatement("your query");
134-st.setPagingState(pagingState);
135-ResultSet rs = session.execute(st);
136-```
137-
138-Note that the paging state can only be reused with the exact same
139-statement (same query string, same parameters). Also, it is an opaque
140-value that is only meant to be collected, stored an re-used. If you try
141-to modify its contents or reuse it with a different statement, the
142-driver will raise an error.
143-
144-Putting it all together, here's a more comprehensive example
145-implementation for our web service:
146-
147-```java
148-final int RESULTS_PER_PAGE = 100;
149-
150-Statement st = new SimpleStatement("your query");
151-st.setFetchSize(RESULTS_PER_PAGE);
152-
153-String requestedPage = extractPagingStateStringFromURL();
154-// This will be absent for the first page
155-if (requestedPage != null) {
156- st.setPagingState(
157- PagingState.fromString(requestedPage));
158-}
159-
160-ResultSet rs = session.execute(st);
161-PagingState nextPage = rs.getExecutionInfo().getPagingState();
162-
163-// Note that we don't rely on RESULTS_PER_PAGE, since Cassandra might
164-// have not respected it, or we might be at the end of the result set
165-int remaining = rs.getAvailableWithoutFetching();
166-for (Row row : rs) {
167- renderInResponse(row);
168- if (--remaining == 0) {
169- break;
170- }
171-}
172-
173-// This will be null if there are no more pages
174-if (nextPage != null) {
175- renderNextPageLink(nextPage.toString());
176-}
177-```
178-
179-[result_set]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSet.html
180-[paging_state]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PagingState.html
181-
182-
183-Due to internal implementation details, `PagingState` instances are not
184-portable across [native protocol](../native_protocol/) versions. This
185-could become a problem in the following scenario:
186-
187-* you're using the driver 2.0.x and Cassandra 2.0.x, and therefore
188- native protocol v2;
189-* a user bookmarks a link to your web service that contains a serialized
190- paging state;
191-* you upgrade your server stack to use the driver 2.1.x and Cassandra
192- 2.1.x, so you're now using protocol v3;
193-* the user tries to reload their bookmark, but the paging state was
194- serialized with protocol v2, so trying to reuse it will fail.
195-
196-If this is not acceptable for you, you might want to consider the unsafe
197-API described in the next section.
198-
199-#### Unsafe API
200-
201-As an alternative to the standard API, there are two methods that
202-manipulate a raw `byte[]` instead of a `PagingState` object:
203-
204-* [ExecutionInfo#getPagingStateUnsafe()][gpsu]
205-* [Statement#setPagingStateUnsafe(byte[])][spsu]
206-
207-These low-level methods perform no validation on their arguments;
208-therefore nothing protects you from reusing a paging state that was
209-generated from a different statement, or altered in any way. This could
210-result in sending a corrupt paging state to Cassandra, with
211-unpredictable consequences (ranging from wrong results to a query
212-failure).
213-
214-There are two situations where you might want to use the unsafe API:
215-
216-* you never expose the paging state to end users and you are confident
217- that it won't get altered;
218-* you want portability across protocol versions and/or you prefer
219- implementing your own validation logic (for example, signing the raw
220- state with a private key).
221-
222-[gpsu]: http://www.datastax.com/drivers/java/3.0/com/datastax/driver/core/ExecutionInfo.html#getPagingStateUnsafe()
223-[spsu]: http://www.datastax.com/drivers/java/3.0/com/datastax/driver/core/Statement.html#setPagingStateUnsafe(byte[])
224-
225-### Offset queries
226-
227-Saving the paging state works well when you only let the user move from
228-one page to the next. But it doesn't allow random jumps (like "go
229-directly to page 10"), because you can't fetch a page unless you have
230-the paging state of the previous one. Such a feature would require
231-*offset queries*, but they are not natively supported by Cassandra (see
232-[CASSANDRA-6511](https://issues.apache.org/jira/browse/CASSANDRA-6511)).
233-The rationale is that offset queries are inherently inefficient (the
234-performance will always be linear in the number of rows skipped), so the
235-Cassandra team doesn't want to encourage their use.
236-
237-If you really want offset queries, you can emulate them client-side.
238-You'll still get linear performance, but maybe that's acceptable for
239-your use case. For example, if each page holds 10 rows and you show at
240-most 20 pages, this means you'll fetch at most 190 extra rows, which
241-doesn't sound like a big deal.
242-
243-For example, if the page size is 10, the fetch size is 50, and the user
244-asks for page 12 (rows 110 to 119):
245-
246-* execute the statement a first time (the result set contains rows 0 to
247- 49, but you're not going to use them, only the paging state);
248-* execute the statement a second time with the paging state from the
249- first query;
250-* execute the statement a third time with the paging state from the
251- second query. The result set now contains rows 100 to 149;
252-* skip the first 10 rows of the iterator. Read the next 10 rows and
253- discard the remaining ones.
254-
255-You'll want to experiment with the fetch size to find the best balance:
256-too small means many background queries; too big means bigger messages
257-and too many unneeded rows returned (we picked 50 above for the sake of
258-example, but it's probably too small -- the default is 5000).
259-
260-Again, offset queries are inefficient by nature. Emulating them
261-client-side is a compromise when you think you can get away with the
262-performance hit. We recommend that you:
263-
264-* test your code at scale with the expected query patterns, to make sure
265- that your assumptions are correct;
266-* set a hard limit on the highest possible page number, to prevent
267- malicious users from triggering queries that would skip a huge amount
268- of rows.
deleted features/pooling/README.md +0 −290
@@ -1,290 +0,0 @@
1-## Connection pooling
2-
3-### Basics
4-
5-The driver communicates with Cassandra over TCP, using the Cassandra
6-binary protocol. This protocol is asynchronous, which allows each TCP
7-connection to handle multiple simultaneous requests:
8-
9-* when a query gets executed, a *stream id* gets assigned to it. It is a
10- unique identifier on the current connection;
11-* the driver writes a request containing the stream id and the query on
12- the connection, and then proceeds without waiting for the response (if
13- you're using the asynchronous API, this is when the driver will send you
14- back a [ResultSetFuture][result_set_future]).
15- Once the request has been written to the
16- connection, we say that it is *in flight*;
17-* at some point, Cassandra will send back a response on the connection.
18- This response also contains the stream id, which allows the driver to
19- trigger a callback that will complete the corresponding query (this is
20- the point where your `ResultSetFuture` will get completed).
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**.
25-
26-The number of connections per pool is configurable (this will be
27-described in the next section). The number of stream ids depends on the
28-[native protocol version](../native_protocol/):
29-
30-* protocol v2 or below: 128 stream ids per connection.
31-* protocol v3 or above: up to 32768 stream ids per connection.
32-
33-```ditaa
34-+-------+1 n+-------+1 n+----+1 n+----------+1 128/32K+-------+
35-|Cluster+-----+Session+-----+Pool+-----+Connection+-----------+Request+
36-+-------+ +-------+ +----+ +----------+ +-------+
37-```
38-
39-### Configuring the connection pool
40-
41-Connections pools are configured with a [PoolingOptions][pooling_options] object, which
42-is global to a `Cluster` instance. You can pass that object when
43-building the cluster:
44-
45-```java
46-PoolingOptions poolingOptions = new PoolingOptions();
47-// customize options...
48-
49-Cluster cluster = Cluster.builder()
50- .withContactPoints("127.0.0.1")
51- .withPoolingOptions(poolingOptions)
52- .build();
53-```
54-
55-Most options can also be changed at runtime. If you don't have a
56-reference to the `PoolingOptions` instance, here's how you can get it:
57-
58-```java
59-PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
60-// customize options...
61-```
62-
63-#### Pool size
64-
65-Connection pools have a variable size, which gets adjusted automatically
66-depending on the current load. There will always be at least a *core*
67-number of connections, and at most a *max* number. These values can be
68-configured independently by host *distance* (the distance is determined
69-by your [LoadBalancingPolicy][lbp], and will generally indicate whether a
70-host is in the same datacenter or not).
71-
72-```java
73-poolingOptions
74- .setCoreConnectionsPerHost(HostDistance.LOCAL, 4)
75- .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
76- .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
77- .setMaxConnectionsPerHost( HostDistance.REMOTE, 4);
78-```
79-
80-For convenience, core and max can be set simultaneously:
81-
82-```java
83-poolingOptions
84- .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
85- .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
86-```
87-
88-The default settings are:
89-
90-* protocol v2:
91- * `LOCAL` hosts: core = 2, max = 8
92- * `REMOTE` hosts: core = 1, max = 2
93-* protocol v3:
94- * `LOCAL` hosts: core = max = 1
95- * `REMOTE` hosts: core = max = 1
96-
97-[PoolingOptions.setNewConnectionThreshold][nct] determines the threshold
98-that triggers the creation of a new connection when the pool is not at
99-its maximum capacity. In general, you shouldn't need to change its
100-default value.
101-
102-#### Dynamic resizing
103-
104-If core != max, the pool will resize automatically to adjust to the
105-current activity on the host.
106-
107-When activity goes up and there are *n* connections with n < max, the driver
108-will add a connection when the number of concurrent requests is more than
109-(n - 1) * 128 + [PoolingOptions.setNewConnectionThreshold][nct]
110-(in layman's terms, when all but the last connection are full and the last
111-connection is above the threshold).
112-
113-When activity goes down, the driver will "trash" connections if the maximum
114-number of requests in a 10 second time period can be satisfied by less than
115-the number of connections opened. Trashed connections are kept open but do
116-not accept new requests. After a given timeout (defined by
117-[PoolingOptions.setIdleTimeoutSeconds][sits]), trashed connections are closed
118-and removed. If during that idle period activity increases again, those
119-connections will be resurrected back into the active pool and reused. The
120-main intent of that is to not constantly recreate connections if activity
121-changes quickly over an interval.
122-
123-#### Simultaneous requests per connection
124-
125-[PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to
126-throttle the number of concurrent requests per connection.
127-
128-With protocol v2, there is no reason to throttle. It is set to 128 (the
129-max) and you should not change it.
130-
131-With protocol v3, it is set to 1024 for `LOCAL` hosts, and 256 for
132-`REMOTE` hosts. These low defaults were chosen so that the default
133-configuration for protocol v2 and v3 allow the same total number of
134-simultaneous requests (to avoid bad surprises when clients migrate from
135-v2 to v3). You can raise this threshold, or even set it to the max:
136-
137-```java
138-poolingOptions
139- .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768)
140- .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000);
141-```
142-
143-Just keep in mind that high values will give clients more bandwidth and
144-therefore put more pressure on your cluster. This might require some
145-tuning, especially if you have many clients.
146-
147-#### Heartbeat
148-
149-If connections stay idle for too long, they might be dropped by
150-intermediate network devices (routers, firewalls...). Normally, TCP
151-keepalive should take care of this; but tweaking low-level keepalive
152-settings might be impractical in some environments.
153-
154-The driver provides application-side keepalive in the form of a
155-connection heartbeat: when a connection has been idle for a given amount
156-of time, the driver will simulate activity by writing a dummy request to
157-it.
158-
159-This feature is enabled by default. The default heartbeat interval is 30
160-seconds, it can be customized with the following method:
161-
162-```java
163-poolingOptions.setHeartbeatIntervalSeconds(60);
164-```
165-
166-If it gets changed at runtime, only connections created after that will
167-use the new interval. Most users will want to do this at startup.
168-
169-The heartbeat interval should be set higher than
170-[SocketOptions.readTimeoutMillis][rtm]:
171-the read timeout is the maximum time that the driver waits for a regular
172-query to complete, therefore the connection should not be considered
173-idle before it has elapsed.
174-
175-To disable heartbeat, set the interval to 0.
176-
177-Implementation note: the dummy request sent by heartbeat is an
178-[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278)
179-message.
180-
181-
182-#### Acquisition timeout
183-
184-When the driver tries to send a request to a host, it will first try to
185-acquire a connection from this host's pool. If the pool is busy (i.e.
186-all connections are already handling their maximum number of in flight
187-requests), the client thread will block for a while, until a connection
188-becomes available (note that this will block even if you're using the
189-asynchronous API, like [Session.executeAsync][exec_async]).
190-
191-The time that the driver blocks is controlled by
192-[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection
193-available after this timeout, the driver will try the next host.
194-
195-For some applications, blocking is not acceptable, and it is preferable
196-to fail fast if the request cannot be fulfilled. If that's your case,
197-set the pool timeout to 0. If all hosts are busy, you will get a
198-[NoHostAvailableException][nhae] (if you look at the exception's details, you
199-will see a `java.util.concurrent.TimeoutException` for each host).
200-
201-
202-### Monitoring and tuning the pool
203-
204-The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's
205-a simple example that will print the number of open connections, active
206-requests, and maximum capacity for each host, every 5 seconds:
207-
208-```java
209-final LoadBalancingPolicy loadBalancingPolicy =
210- cluster.getConfiguration().getPolicies().getLoadBalancingPolicy();
211-final PoolingOptions poolingOptions =
212-cluster.getConfiguration().getPoolingOptions();
213-
214-ScheduledExecutorService scheduled =
215-Executors.newScheduledThreadPool(1);
216-scheduled.scheduleAtFixedRate(new Runnable() {
217- @Override
218- public void run() {
219- Session.State state = session.getState();
220- for (Host host : state.getConnectedHosts()) {
221- HostDistance distance = loadBalancingPolicy.distance(host);
222- int connections = state.getOpenConnections(host);
223- int inFlightQueries = state.getInFlightQueries(host);
224- System.out.printf("%s connections=%d, current load=%d, max
225-load=%d%n",
226- host, connections, inFlightQueries,
227- connections *
228-poolingOptions.getMaxRequestsPerConnection(distance));
229- }
230- }
231-}, 5, 5, TimeUnit.SECONDS);
232-```
233-
234-In real life, you'll probably want something more sophisticated, like
235-exposing a JMX MBean or sending the data to your favorite monitoring
236-tool.
237-
238-If you find that the current load stays close or equal to the maximum
239-load at all time, it's a sign that your connection pools are saturated
240-and you should raise the max connections per host, or max requests per
241-connection (protocol v3).
242-
243-If you're using protocol v2 and the load is often less than core * 128,
244-your pools are underused and you could get away with less core
245-connections.
246-
247-#### Tuning protocol v3 for very high throughputs
248-
249-As mentioned above, the default pool size for protocol v3 is core = max
250-= 1. This means all requests to a given node will share a single
251-connection, and therefore a single Netty I/O thread.
252-
253-There is a corner case where this I/O thread can max out its CPU core
254-and become a bottleneck in the driver; in our benchmarks, this happened
255-with a single-node cluster and a high throughput (approximately 80K
256-requests / second).
257-
258-It's unlikely that you'll run into this issue: in most real-world
259-deployments, the driver connects to more than one node, so the load will
260-spread across more I/O threads. However if you suspect that you
261-experience the issue, here's what to look out for:
262-
263-* the driver throughput plateaus but the process does not appear to
264- max out any system resource (in particular, overall CPU usage is well
265- below 100%);
266-* one of the driver's I/O threads maxes out its CPU core. You can see
267- that with a profiler, or OS-level tools like `pidstat -tu` on Linux.
268- I/O threads are called `<cluster_name>-nio-worker-<n>`, unless you're
269- injecting your own `EventLoopGroup` with `NettyOptions`.
270-
271-The solution is to add more connections per node. To ensure that
272-additional connections get created before you run into the bottleneck,
273-either:
274-
275-* set core = max;
276-* keep core = 1, but adjust [maxRequestsPerConnection][mrpc] and
277- [newConnectionThreshold][nct] so that enough connections are added by
278- the time you reach the bottleneck.
279-
280-[result_set_future]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html
281-[pooling_options]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html
282-[lbp]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
283-[nct]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
284-[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection(com.datastax.driver.core.HostDistance,%20int)
285-[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds(int)
286-[rtm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis()
287-[exec_async]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement)
288-[ptm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
289-[nhae]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
290-[get_state]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState()
deleted features/query_timestamps/README.md +0 −77
@@ -1,77 +0,0 @@
1-## Query timestamps
2-
3-In Cassandra, each mutation has a microsecond-precision timestamp, which
4-is used to order operations relative to each other.
5-
6-There are various ways to assign it:
7-
8-### CQL `USING TIMESTAMP`
9-
10-You can explicitly provide the timestamp in your CQL query:
11-
12-```java
13-session.execute("INSERT INTO my_table(c1, c2) values (1, 1) " +
14- "USING TIMESTAMP 1432815430948040");
15-```
16-
17-### Client-side generation
18-
19-This is enabled by default if you're using the driver 3.0 and a version
20-of Cassandra that supports [native protocol](../native_protocol) v3 or
21-above.
22-
23-A client timestamp will be sent by each query. It is generated by a
24-[TimestampGenerator][tsg]. The default implementation is
25-[AtomicMonotonicTimestampGenerator][amtsg].
26-
27-You can specify another generator at initialization:
28-
29-```java
30-Cluster.builder().addContactPoint("127.0.0.1")
31- .withTimestampGenerator(new MyCustomTimestampGenerator())
32- .build();
33-```
34-
35-In addition, you can also override the default timestamp on a
36-per-statement basis:
37-
38-```java
39-Statement statement = new SimpleStatement(
40- "UPDATE users SET email = 'x@y.com' where id = 1");
41-statement.setDefaultTimestamp(1234567890);
42-session.execute(statement);
43-```
44-
45-[tsg]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TimestampGenerator.html
46-[amtsg]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.html
47-
48-
49-### Server-side generation
50-
51-This is the "legacy" behavior if you're connected to a Cassandra version
52-that only supports protocol v2 or below. The server will assign a
53-timestamp based on the time it receives the query.
54-
55-This can be a problem when the order of the writes matter: with unlucky
56-timing (different coordinators, network latency, etc.), two successive
57-requests from the same client might be processed in a different order
58-server-side, and end up with out-of-order timestamps. If protocol v3 is
59-not an option, the only workaround is to add `USING TIMESTAMP` in your
60-queries.
61-
62-
63-### Summary
64-
65-As shown in the previous sections, there are multiple ways to provide a
66-timestamp, some of which overlap. The order of precedence is the
67-following:
68-
69-1. if there is a `USING TIMESTAMP` clause in the CQL string, use that
70- over anything else;
71-2. otherwise, if a default timestamp was set on the statement and is
72- different from `Long.MIN_VALUE`, use it;
73-3. otherwise, if a generator is specified, invoke it and use its result
74- if it is different from `Long.MIN_VALUE`;
75-4. otherwise, let the server assign the timestamp.
76-
77-Steps 2 and 3 only apply if native protocol v3 or above is in use.
deleted features/shaded_jar/README.md +0 −55
@@ -1,55 +0,0 @@
1-## Using the shaded JAR
2-
3-The default driver JAR depends on [Netty](http://netty.io/), which is
4-used internally for networking.
5-
6-This explicit dependency can be a problem if your application already
7-uses another Netty version. To avoid conflicts, we provide a "shaded"
8-version of the JAR, which bundles the Netty classes under a different
9-package name:
10-
11-```xml
12-<dependency>
13- <groupId>com.datastax.cassandra</groupId>
14- <artifactId>cassandra-driver-core</artifactId>
15- <version>3.0.0-rc1</version>
16- <classifier>shaded</classifier>
17- <!-- Because the shaded JAR uses the original POM, you still need
18- to exclude this dependency explicitly: -->
19- <exclusions>
20- <exclusion>
21- <groupId>io.netty</groupId>
22- <artifactId>*</artifactId>
23- </exclusion>
24- </exclusions>
25-</dependency>
26-```
27-
28-If you also use the mapper, you need to remove its dependency to the
29-non-shaded JAR:
30-
31-```xml
32-<dependency>
33- <groupId>com.datastax.cassandra</groupId>
34- <artifactId>cassandra-driver-core</artifactId>
35- <version>3.0.0-rc1</version>
36- <classifier>shaded</classifier>
37- <exclusions>
38- <exclusion>
39- <groupId>io.netty</groupId>
40- <artifactId>*</artifactId>
41- </exclusion>
42- </exclusions>
43-</dependency>
44-<dependency>
45- <groupId>com.datastax.cassandra</groupId>
46- <artifactId>cassandra-driver-mapping</artifactId>
47- <version>3.0.0-rc1</version>
48- <exclusions>
49- <exclusion>
50- <groupId>com.datastax.cassandra</groupId>
51- <artifactId>cassandra-driver-core</artifactId>
52- </exclusion>
53- </exclusions>
54-</dependency>
55-```
deleted features/speculative_execution/README.md +0 −343
@@ -1,343 +0,0 @@
1-## Speculative query execution
2-
3-Sometimes a Cassandra node might be experiencing difficulties (ex: long
4-GC pause) and take longer than usual to reply. Queries sent to that node
5-will experience bad latency.
6-
7-One thing we can do to improve that is pre-emptively start a second
8-execution of the query against another node, before the first node has
9-replied or errored out. If that second node replies faster, we can send
10-the response back to the client (we also cancel the first query):
11-
12-```ditaa
13-client driver exec1 exec2
14---+----------------+--------------+------+---
15- | execute(query) |
16- |--------------->|
17- | | query host1
18- | |------------->|
19- | | |
20- | | |
21- | | query host2
22- | |-------------------->|
23- | | | |
24- | | | |
25- | | host2 replies |
26- | |<--------------------|
27- | complete | |
28- |<---------------| |
29- | | cancel |
30- | |------------->|
31-```
32-
33-Or the first node could reply just after the second execution was
34-started. In this case, we cancel the second execution. In other words,
35-whichever node replies faster "wins" and completes the client query:
36-
37-```ditaa
38-client driver exec1 exec2
39---+----------------+--------------+------+---
40- | execute(query) |
41- |--------------->|
42- | | query host1
43- | |------------->|
44- | | |
45- | | |
46- | | query host2
47- | |-------------------->|
48- | | | |
49- | | | |
50- | | host1 replies| |
51- | |<-------------| |
52- | complete | |
53- |<---------------| |
54- | | cancel |
55- | |-------------------->|
56-```
57-
58-Speculative executions are **disabled** by default. The following
59-sections cover the practical details and how to enable them.
60-
61-### Query idempotence
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
67-there is no way to guarantee that only one node will apply the mutation.
68-
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-### Enabling speculative executions
115-
116-Speculative executions are controlled by an instance of
117-[SpeculativeExecutionPolicy][sep] provided when initializing the
118-`Cluster`. This policy defines the threshold after which a new
119-speculative execution will be triggered.
120-
121-[sep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html
122-
123-Two implementations are provided with the driver:
124-
125-#### [ConstantSpeculativeExecutionPolicy][csep]
126-
127-This simple policy uses a constant threshold:
128-
129-```java
130-Cluster cluster = Cluster.builder()
131- .addContactPoint("127.0.0.1")
132- .withSpeculativeExecutionPolicy(
133- new ConstantSpeculativeExecutionPolicy(
134- 500, // delay before a new execution is launched
135- 2 // maximum number of executions
136- ))
137- .build();
138-```
139-
140-Given the above configuration, an idempotent query would be handled this
141-way:
142-
143-* start the initial execution at t0;
144-* if no response has been received at t0 + 500 milliseconds, start a
145- speculative execution on another node;
146-* if no response has been received at t0 + 1000 milliseconds, start
147- another speculative execution on a third node.
148-
149-[csep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.html
150-
151-#### [PercentileSpeculativeExecutionPolicy][psep]
152-
153-This policy sets the threshold at a given latency percentile for the
154-current host, based on recent statistics.
155-
156-**As of 2.1.6, this class is provided as a beta preview: it hasn't been
157-extensively tested yet, and the API is still subject to change.**
158-
159-First and foremost, make sure that the [HdrHistogram][hdr] library (used
160-under the hood to collect latencies) is in your classpath. It's defined
161-as an optional dependency in the driver's POM, so you'll need to
162-explicitly depend on it:
163-
164-```xml
165-<dependency>
166- <groupId>org.hdrhistogram</groupId>
167- <artifactId>HdrHistogram</artifactId>
168- <version>2.1.4</version>
169-</dependency>
170-```
171-
172-Then create an instance of [PerHostPercentileTracker][phpt] that will collect
173-latency statistics for your `Cluster`:
174-
175-```java
176-// There are more options than shown here, please refer to the API docs
177-// for more information
178-PerHostPercentileTracker tracker = PerHostPercentileTracker
179- .builderWithHighestTrackableLatencyMillis(15000)
180- .build();
181-```
182-
183-Create an instance of the policy with the tracker, and pass it to your
184-cluster:
185-
186-```java
187-PercentileSpeculativeExecutionPolicy policy =
188- new PercentileSpeculativeExecutionPolicy(
189- tracker,
190- 99.0, // percentile
191- 2); // maximum number of executions
192-
193-Cluster cluster = Cluster.builder()
194- .addContactPoint("127.0.0.1")
195- .withSpeculativeExecutionPolicy(policy)
196- .build();
197-```
198-
199-Finally, don't forget to register your tracker with the cluster (the
200-policy does not do this itself):
201-
202-```java
203-cluster.register(tracker);
204-```
205-
206-Note that `PerHostPercentileTracker` may also be used with a slow query
207-logger (see the [Logging](../logging/) section). In that case, you would
208-create a single tracker object and share it with both components.
209-
210-[psep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html
211-[hdr]: http://hdrhistogram.github.io/HdrHistogram/
212-[phpt]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PerHostPercentileTracker.html
213-
214-#### Using your own
215-
216-As with all policies, you are free to provide your own by implementing
217-`SpeculativeExecutionPolicy`.
218-
219-### How speculative executions affect retries
220-
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
230-parallel execution will trigger retries independently:
231-
232-```ditaa
233-client driver exec1 exec2
234---+----------------+--------------+------+---
235- | execute(query) |
236- |--------------->|
237- | | query host1
238- | |------------->|
239- | | |
240- | | unavailable |
241- | |<-------------|
242- | |
243- | |retry at lower CL
244- | |------------->|
245- | | |
246- | | query host2
247- | |-------------------->|
248- | | | |
249- | | server error |
250- | |<--------------------|
251- | | |
252- | | retry on host3
253- | |-------------------->|
254- | | | |
255- | | host1 replies| |
256- | |<-------------| |
257- | complete | |
258- |<---------------| |
259- | | cancel |
260- | |-------------------->|
261-```
262-
263-The only impact is that all executions of the same query always share
264-the same query plan, so each host will be used by at most one execution.
265-
266-[retry_policy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html
267-
268-### Tuning and practical details
269-
270-The goal of speculative executions is to improve overall latency (the
271-time between `execute(query)` and `complete` in the diagrams above) at
272-high percentiles. On the flipside, they cause the driver to send more
273-individual requests, so throughput will not necessarily improve.
274-
275-You can monitor how many speculative executions were triggered with the
276-`speculative-executions` metric (exposed in the Java API as
277-[cluster.getMetrics().getErrors().getSpeculativeExecutions()][se_metric]).
278-It should only be a few percents of the total number of requests
279-([cluster.getMetrics().getRequestsTimer().getCount()][request_metric]).
280-
281-[se_metric]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions()
282-[request_metric]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metrics.html#getRequestsTimer()
283-
284-#### Stream id exhaustion
285-
286-One side-effect of speculative executions is that many requests are
287-cancelled, which can lead to a phenomenon called *stream id exhaustion*:
288-each TCP connection can handle multiple simultaneous requests,
289-identified by a unique number called *stream id*. When a request gets
290-cancelled, we can't reuse its stream id immediately because we might
291-still receive a response from the server later. If this happens often,
292-the number of available stream ids diminishes over time, and when it
293-goes below a given threshold we close the connection and create a new
294-one. If requests are often cancelled, so will see connections being
295-recycled at a high rate.
296-
297-One way to detect this is to monitor open connections per host
298-([Session.getState().getOpenConnections(host)][session_state]) against
299-TCP connections at the OS level. If open connections stay constant but
300-you see many TCP connections in closing states, you might be running
301-into this issue. Try raising the speculative execution threshold.
302-
303-This problem is more likely to happen with version 2 of the native
304-protocol, because each TCP connection only has 128 stream ids. With
305-version 3 (driver 2.1.2 or above with Cassandra 2.1 or above), there are
306-32K stream ids per connection, so higher cancellation rates can be
307-sustained. If you're unsure of which native protocol version you're
308-using, you can check with
309-[cluster.getConfiguration().getProtocolOptions().getProtocolVersion()][protocol_version].
310-
311-[session_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.State.html
312-[protocol_version]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion()
313-
314-#### Request ordering and client timestamps
315-
316-Another issue that might arise is that you get unintuitive results
317-because of request ordering. Suppose you run the following query with
318-speculative executions enabled:
319-
320- insert into my_table (k, v) values (1, 1);
321-
322-The first execution is a bit too slow, so a second execution gets
323-triggered. Finally, the first execution completes, so the client code
324-gets back an acknowledgement, and the second execution is cancelled.
325-However, cancelling only means that the driver stops waiting for the
326-server's response, the request could still be "on the wire"; let's
327-assume that this is the case.
328-
329-Now you run the following query, which completes successfully:
330-
331- delete from my_table where k = 1;
332-
333-But now the second execution of the first query finally reaches its
334-target node, which applies the mutation. The row that you've just
335-deleted is back!
336-
337-The workaround is to use a timestamp with your queries:
338-
339- insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000;
340-
341-If you're using native protocol v3, you can also enable [client-side
342-timestamps](../query_timestamps/#client-side-generation) to have this done
343-automatically.
deleted features/ssl/README.md +0 −184
@@ -1,184 +0,0 @@
1-## SSL
2-
3-You can secure traffic between the driver and Cassandra with SSL. There
4-are two aspects to that:
5-
6-* **client-to-node encryption**, where the traffic is encrypted, and the
7- client verifies the identity of the Cassandra nodes it connects to;
8-* optionally, **client certificate authentication**, where Cassandra
9- nodes also verify the identity of the client.
10-
11-This section describes the driver-side configuration; it assumes that
12-you've already configured SSL in Cassandra:
13-
14-* [the Cassandra documentation](http://docs.datastax.com/en/cassandra/2.0/cassandra/security/secureSSLClientToNode_t.html)
15- covers a basic approach with self-signed certificates, which is fine
16- for development and tests.
17-* [this blog post](http://thelastpickle.com/blog/2015/09/30/hardening-cassandra-step-by-step-part-1-server-to-server.html)
18- details a more advanced solution based on a Certificate Authority
19- (CA).
20-
21-### Preparing the certificates
22-
23-#### Client truststore
24-
25-This is required for client-to-node encryption.
26-
27-If you're using self-signed certificates, you need to export the public
28-part of each node's certificate from that node's keystore:
29-
30-```
31-keytool -export -alias cassandra -file cassandranode0.cer -keystore .keystore
32-```
33-
34-Then add all public certificates to the client truststore:
35-
36-```
37-keytool -import -v -trustcacerts -alias <cassandra_node0> -file cassandranode0.cer -keystore client.truststore
38-keytool -import -v -trustcacerts -alias <cassandra_node1> -file cassandranode1.cer -keystore client.truststore
39-...
40-```
41-
42-If you're using a Certificate Authority, the client truststore only
43-needs to contain the CA's certificate:
44-
45-```
46-keytool -import -v -trustcacerts -alias CARoot -file ca.cer -keystore client.truststore
47-```
48-
49-#### Client keystore
50-
51-If you also intend to use client certificate authentication, generate
52-the public and private key pair for the client:
53-
54-```
55-keytool -genkey -keyalg RSA -alias client -keystore client.keystore
56-```
57-
58-If you're using self-signed certificates, extract the public part of the
59-client certificate, and import it in the truststore of each Cassandra
60-node:
61-
62-```
63-keytool -export -alias client -file client.cer -keystore client.keystore
64-keytool -import -v -trustcacerts -alias client -file client.cer -keystore server.truststore
65-```
66-
67-If you're using a CA, sign the client certificate with it (see the blog
68-post linked at the top of this page). Then the nodes' truststores only
69-need to contain the CA's certificate (which should already be the case
70-if you've followed the steps for inter-node encryption).
71-
72-### Driver configuration
73-
74-The base class to configure SSL is [SSLOptions]. It's very generic, but
75-you don't necessarily need to deal with it directly: the default
76-instance, or the provided subclasses, might be enough for your needs.
77-
78-#### JSSE, Property-based
79-
80-`withSSL()` gives you a basic JSSE configuration:
81-
82-```java
83-Cluster cluster = Cluster.builder()
84- .addContactPoint("127.0.0.1")
85- .withSSL()
86- .build();
87-```
88-
89-You can then use
90-[JSSE system properties](http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization)
91-for specific details, like keystore locations and passwords:
92-
93-```
94--Djavax.net.ssl.trustStore=/path/to/client.truststore
95--Djavax.net.ssl.trustStorePassword=password123
96-# If you're using client authentication:
97--Djavax.net.ssl.keyStore=/path/to/client.keystore
98--Djavax.net.ssl.keyStorePassword=password123
99-```
100-
101-#### JSSE, programmatic
102-
103-If you need more control than what system properties allow, you can
104-configure SSL programmatically with [JdkSSLOptions]:
105-
106-```java
107-SSLContext sslContext = ... // create and configure SSL context
108-
109-JdkSSLOptions sslOptions = JdkSSLOptions.builder()
110- .withSSLContext(context)
111- .build();
112-
113-Cluster cluster = Cluster.builder()
114- .addContactPoint("127.0.0.1")
115- .withSSL(sslOptions)
116- .build();
117-```
118-
119-Note that you can also extend the class and override
120-[newSSLEngine(SocketChannel)][newSSLEngine] if you need specific
121-configuration on the `SSLEngine` (for example hostname verification).
122-
123-[newSSLEngine]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/JdkSSLOptions.html#newSSLEngine(io.netty.channel.socket.SocketChannel)
124-
125-#### Netty
126-
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.
130-
131-##### Converting your client certificates for OpenSSL
132-
133-OpenSSL doesn't use keystores, so if you use client authentication and
134-generated your certificates with keytool, you need to convert them.
135-
136-* use this command to extract the public certificate chain:
137-
138- ```
139- keytool -export -keystore client.keystore -alias client -rfc -file client.crt
140- ```
141-* follow
142- [this tutorial](http://www.herongyang.com/crypto/Migrating_Keys_keytool_to_OpenSSL_3.html)
143- to extract your client's private key from `client.keystore` to a text
144- file `client.key` in PEM format.
145-
146-##### Updating your dependencies
147-
148-Netty-tcnative provides the native integration with OpenSSL. Follow
149-[these instructions](http://netty.io/wiki/forked-tomcat-native.html) to
150-add it to your dependencies.
151-
152-Note that using netty-tcnative requires JDK 1.7 or above.
153-
154-##### Configuring the context
155-
156-Use the following Java code to configure OpenSSL with your certificates:
157-
158-```java
159-KeyStore ks = KeyStore.getInstance("JKS");
160-// make sure you close this stream properly (not shown here for brevity)
161-InputStream trustStore = new FileInputStream("client.truststore");
162-ks.load(trustStore, "password123".toCharArray());
163-TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
164-tmf.init(ks);
165-
166-SslContextBuilder builder = SslContextBuilder
167- .forClient()
168- .sslProvider(SslProvider.OPENSSL)
169- .trustManager(tmf);
170- // only if you use client authentication
171- .keyManager(new File("client.crt"), new File("client.key"));
172-
173-SSLOptions sslOptions = new NettySSLOptions(builder.build());
174-
175-Cluster cluster = Cluster.builder()
176- .addContactPoint("127.0.0.1")
177- .withSSL(sslOptions)
178- .build();
179-```
180-
181-[SSLOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SSLOptions.html
182-[JdkSSLOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/JdkSSLOptions.html
183-[NettySSLOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/NettySSLOptions.html
184-[NettyOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/NettyOptions.html
deleted features/statements/README.md +0 −54
@@ -1,54 +0,0 @@
1-## Statements
2-
3-To execute a query, you create a [Statement] instance and pass it to
4-`Session#execute()`. The driver provides various implementations:
5-
6-* [SimpleStatement]: a simple implementation built directly from a
7- character string. Typically used for queries that are executed only
8- once or a few times.
9-* [BoundStatement]: obtained by binding values to a [prepared
10- statement](prepared/). Typically used for queries that are executed
11- often, with different values.
12-* [BuiltStatement]: a statement built with the [QueryBuilder] DSL. It
13- can be executed directly like a simple statement, or prepared.
14-* [BatchStatement]: a statement that groups multiple statements to be
15- executed as a batch.
16-
17-`Session` also has a shortcut to build and execute a simple statement in
18-a single call:
19-
20-```java
21-session.execute("select release_version from system.local");
22-
23-// Is equivalent to:
24-Statement s = new SimpleStatement("select release_version from system.local");
25-session.execute(s);
26-```
27-
28-### Customizing execution
29-
30-Before executing a statement, you might want to customize certain
31-aspects of its execution. `Statement` provides a number of methods for
32-this, for example:
33-
34-```java
35-Statement s = new SimpleStatement("select release_version from system.local");
36-s.enableTracing();
37-session.execute(s);
38-```
39-
40-If you use custom policies ([RetryPolicy], [LoadBalancingPolicy],
41-[SpeculativeExecutionPolicy]...), you might also want to have custom
42-properties that influence statement execution. To achieve this, you can
43-wrap your statements in a custom [StatementWrapper] implementation.
44-
45-[Statement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Statement.html
46-[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SimpleStatement.html
47-[BoundStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BoundStatement.html
48-[BatchStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html
49-[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/QueryBuilder.html
50-[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/BuiltStatement.html
51-[StatementWrapper]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/StatementWrapper.html
52-[RetryPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/RetryPolicy.html
53-[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html
54-[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html
deleted features/statements/prepared/README.md +0 −188
@@ -1,188 +0,0 @@
1-## Prepared statements
2-
3-When Cassandra executes a query, the first thing it does is parse the
4-query string to an internal representation. If the same query is used
5-often, you can use a prepared statement, which allows Cassandra to cache
6-that representation, and save time and resources for subsequent
7-executions. Prepared statements are typically parameterized, using
8-different values for each execution:
9-
10-```java
11-PreparedStatement prepared = session.prepare(
12- "insert into product (sku, description) values (?, ?)");
13-
14-BoundStatement bound;
15-
16-bound = prepared.bind("234827", "Mouse");
17-session.execute(bound);
18-
19-bound = prepared.bind("987274", "Keyboard");
20-session.execute(bound);
21-```
22-
23-Statements should be be prepared only once. If you call `prepare`
24-multiple times with the same query string, the driver will log a
25-warning. So your application should cache the `PreparedStatement` object
26-once it's been created (this can be as simple as storing it as a field
27-in a DAO).
28-
29-### Parameters and binding
30-
31-Parameters can be either anonymous or named (named parameters are only
32-available with [native protocol](../../native_protocol) v2 or above):
33-
34-```java
35-ps1 = session.prepare("insert into product (sku, description) values (?, ?)");
36-ps2 = session.prepare("insert into product (sku, description) values (:s, :d)");
37-```
38-
39-To turn the statement into its executable form, you need to *bind* it
40-and provide values for the parameters. As shown previously, there is a
41-shorthand form to do it all in one call:
42-
43-```java
44-BoundStatement bound = ps1.bind("324378", "LCD screen");
45-```
46-
47-You can also bind first, then use setters, which is slightly more
48-explicit:
49-
50-```java
51-// Positional setters:
52-BoundStatement bound = ps1.bind()
53- .setString(0, "324378")
54- .setString(1, "LCD screen");
55-
56-// Named setters:
57-BoundStatement bound = ps2.bind()
58- .setString("s", "324378")
59- .setString("d", "LCD screen");
60-```
61-
62-You can use named setters even if the query uses anonymous parameters;
63-Cassandra will name the parameters after the column they apply to:
64-
65-```java
66-BoundStatement bound = ps1.bind()
67- .setString("sku", "324378")
68- .setString("description", "LCD screen");
69-```
70-
71-This can be ambiguous if the query uses the same column multiple times,
72-for example: `select * from sales where sku = ? and date > ? and date <
73-?`. In these situations, use positional setters or named parameters.
74-
75-For native protocol V3 or below, all variables must be bound. With native
76-protocol V4 or above, variables can be left unset, in which case they
77-will be ignored server side (no tombstones will be generated). If you're
78-reusing a bound statement you can use the `unset` method to unset variables
79-that were previously set:
80-
81-```java
82-BoundStatement bound = ps1.bind()
83- .setString("sku", "324378")
84- .setString("description", "LCD screen")
85-
86-// Using the unset method to unset previously set value.
87-// Positional setter:
88-bound.unset("description");
89-
90-// Named setter:
91-bound.unset(1);
92-```
93-
94-A bound statement also has getters to retrieve the values. Note that
95-this has a small performance overhead since values are stored in their
96-serialized form.
97-
98-### How the driver handles prepared statements
99-
100-When the driver prepares a statement, it sends the query string to
101-Cassandra, which caches the statement and returns an identifier. Later,
102-when the driver needs to execute the statement, it just sends the
103-identifier and parameter values. Note that the identifier is
104-deterministic, so it will always be the same for all nodes (it's a
105-actually a hash of the query string).
106-
107-Prepared statements are not replicated across the cluster. It is the
108-driver's responsibility to ensure that each node's cache is up to
109-date. It uses a number of strategies to achieve this:
110-
111-1. When a statement is initially prepared, it is first sent to a single
112- node in the cluster (this prevents from hitting all nodes in case
113- the query string is wrong). Once that node replies successfully, the
114- driver re-prepares on all remaining nodes:
115-
116- ```ditaa
117- client driver node1 node2 node3
118- --+------------------------+----------------+--------------+------+---
119- | | | | |
120- | session.prepare(query) | | | |
121- |----------------------->| | | |
122- | | PREPARE(query) | | |
123- | |--------------->| | |
124- | | | | |
125- | | PREPARED(id) | | |
126- | |<---------------| | |
127- | | | | |
128- | | | | |
129- | | PREPARE(query) | |
130- | |------------------------------>| |
131- | | | | |
132- | | PREPARE(query) | |
133- | |------------------------------------->|
134- | | | | |
135- |<-----------------------| | | |
136- ```
137-
138-2. if a node crashes, it loses all of its prepared statements. So the
139- driver keeps a client-side cache; anytime a node is marked back up,
140- the driver re-prepares all statements on it;
141-
142-3. finally, if the driver tries to execute a statement and finds out
143- that the coordinator doesn't know about it, it will re-prepare the
144- statement on the fly (this is transparent for the client, but will cost
145- two extra roundtrips):
146-
147- ```ditaa
148- client driver node1
149- --+-------------------------------+------------------------------+--
150- | | |
151- |session.execute(boundStatement)| |
152- +------------------------------>| |
153- | | EXECUTE(id, values) |
154- | |----------------------------->|
155- | | |
156- | | UNPREPARED |
157- | |<-----------------------------|
158- | | |
159- | | |
160- | | PREPARE(query) |
161- | |----------------------------->|
162- | | |
163- | | PREPARED(id) |
164- | |<-----------------------------|
165- | | |
166- | | |
167- | | EXECUTE(id, values) |
168- | |----------------------------->|
169- | | |
170- | | ROWS |
171- | |<-----------------------------|
172- | | |
173- |<------------------------------| |
174- ```
175-
176-You can customize these strategies through `QueryOptions`:
177-
178-* [setPrepareOnAllHosts] controls whether statements are initially
179- re-prepared on other hosts (step 1 above);
180-* [setReprepareOnUp] controls whether statements are re-prepared on a
181- node that comes back up (step 2 above).
182-
183-Changing the driver's defaults should be done with care and only in
184-specific situations; read each method's Javadoc for detailed
185-explanations.
186-
187-[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts(boolean)
188-[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp(boolean)
added manual/README.md +17 −0
@@ -0,0 +1,17 @@
1+## Manual
2+
3+This part of the documentation is organized into sub-sections covering
4+specific topics.
5+
6+If you're reading this from the [generated HTML documentation on
7+github.io](http://datastax.github.io/java-driver/), use the "Read More"
8+menu on the right hand side. If you're [browsing the source files on
9+github.com](https://github.com/datastax/java-driver/tree/3.0/manual),
10+simply navigate to each sub-directory.
11+
12+This is a work in progress: new sections will be added to cover existing
13+features or document new ones.
14+
15+You can also find more help in the legacy
16+[user documentation](http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/whatsNew2.html)
17+on the DataStax website.
added manual/address_resolution/README.md +59 −0
@@ -0,0 +1,59 @@
1+## Address resolution
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.
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).
12+
13+### The [AddressTranslator][at] interface
14+
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.
17+
18+```java
19+public class MyAddressTranslator implements AddressTranslator {
20+ public InetSocketAddress translate(InetSocketAddress address) {
21+ ... // your custom translation logic
22+ }
23+}
24+
25+Cluster cluster = Cluster.builder()
26+ .addContactPoint("1.2.3.4")
27+ .withAddressTranslator(new MyAddressTranslator())
28+ .build();
29+```
30+
31+Note: the contact points provided while creating the `Cluster` are not translated, only
32+addresses retrieved from or sent by Cassandra nodes are.
33+
34+[at]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/AddressTranslator.html
35+
36+### EC2 multi-region
37+
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:
41+
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.
45+
46+To use this implementation, provide an instance when initializing the `Cluster`:
47+
48+```java
49+Cluster cluster = Cluster.builder()
50+ .addContactPoint("1.2.3.4")
51+ .withAddressTranslator(new EC2MultiRegionAddressTranslator())
52+ .build();
53+```
54+
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.
58+
59+[ec2]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.html
added manual/async/README.md +150 −0
@@ -0,0 +1,150 @@
1+## Asynchronous programming
2+
3+The driver exposes an asynchronous API that allows you to write programs
4+in a fully-non blocking manner. Asynchronous methods return instances of
5+Guava's [ListenableFuture], that can be conveniently chained and
6+composed.
7+
8+Here is a short example that opens a session and runs a query
9+asynchronously:
10+
11+```java
12+import com.google.common.util.concurrent.*;
13+
14+ListenableFuture<Session> session = cluster.connectAsync();
15+
16+// Use transform with an AsyncFunction to chain an async operation after another:
17+ListenableFuture<ResultSet> resultSet = Futures.transform(session,
18+ new AsyncFunction<Session, ResultSet>() {
19+ public ListenableFuture<ResultSet> apply(Session session) throws Exception {
20+ return session.executeAsync("select release_version from system.local");
21+ }
22+ });
23+
24+// Use transform with a simple Function to apply a synchronous computation on the result:
25+ListenableFuture<String> version = Futures.transform(resultSet,
26+ new Function<ResultSet, String>() {
27+ public String apply(ResultSet rs) {
28+ return rs.one().getString("release_version");
29+ }
30+ });
31+
32+// Use a callback to perform an action once the future is complete:
33+Futures.addCallback(version, new FutureCallback<String>() {
34+ public void onSuccess(String version) {
35+ System.out.printf("Cassandra version: %s%n", version);
36+ }
37+
38+ public void onFailure(Throwable t) {
39+ System.out.printf("Failed to retrieve the version: %s%n",
40+ t.getMessage());
41+ }
42+});
43+```
44+
45+### Async paging
46+
47+If you consume a `ResultSet` in a callback, be aware that iterating the
48+rows will trigger synchronous queries as you page through the results.
49+To avoid this, use [getAvailableWithoutFetching] to limit the iteration
50+to the current page, and [fetchMoreResults] to get a future to the next
51+page (see also the section on [paging](../paging/)).
52+Here is a full example:
53+
54+[getAvailableWithoutFetching]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSet.html#getAvailableWithoutFetching--
55+[fetchMoreResults]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSet.html#fetchMoreResults--
56+
57+```java
58+Statement statement = new SimpleStatement("select * from foo").setFetchSize(20);
59+ListenableFuture<ResultSet> future = Futures.transform(
60+ session.executeAsync(statement),
61+ iterate(1));
62+
63+private static AsyncFunction<ResultSet, ResultSet> iterate(final int page) {
64+ return new AsyncFunction<ResultSet, ResultSet>() {
65+ @Override
66+ public ListenableFuture<ResultSet> apply(ResultSet rs) throws Exception {
67+
68+ // How far we can go without triggering the blocking fetch:
69+ int remainingInPage = rs.getAvailableWithoutFetching();
70+
71+ System.out.printf("Starting page %d (%d rows)%n", page, remainingInPage);
72+
73+ for (Row row : rs) {
74+ System.out.printf("[page %d - %d] row = %s%n", page, remainingInPage, row);
75+ if (--remainingInPage == 0)
76+ break;
77+ }
78+ System.out.printf("Done page %d%n", page);
79+
80+ boolean wasLastPage = rs.getExecutionInfo().getPagingState() == null;
81+ if (wasLastPage) {
82+ System.out.println("Done iterating");
83+ return Futures.immediateFuture(rs);
84+ } else {
85+ ListenableFuture<ResultSet> future = rs.fetchMoreResults();
86+ return Futures.transform(future, iterate(page + 1));
87+ }
88+ }
89+ };
90+}
91+```
92+
93+### Good practices
94+
95+If your callback is slow, consider providing a separate executor.
96+Otherwise the callback might run on one of the driver's I/O threads,
97+blocking I/O operations for other requests while it is running:
98+
99+```java
100+ListenableFuture<String> result = Futures.transform(resultSet,
101+ new Function<ResultSet, String>() {
102+ public String apply(ResultSet rs) {
103+ return someVeryLongComputation(rs);
104+ }
105+ }, myCustomExecutor);
106+```
107+
108+Avoid blocking operations in callbacks, especially if you don't provide
109+a separate executor. This could easily lead to deadlock if the thread
110+that's supposed to complete the blocking call is also the thread that's
111+waiting on it:
112+
113+```java
114+ListenableFuture<ResultSet> resultSet = Futures.transform(session,
115+ new Function<Session, ResultSet>() {
116+ public ResultSet apply(Session session) {
117+ // Synchronous operation in a callback.
118+ // DON'T DO THIS! It might deadlock.
119+ return session.execute("select release_version from system.local");
120+ }
121+ });
122+```
123+
124+### Known limitations
125+
126+There are still a few places where the driver will block internally
127+(mainly for historical reasons):
128+
129+* [Cluster#init][init] performs blocking I/O operations. To avoid
130+ issues, you should create your `Cluster` instances while bootstrapping
131+ your application, and call `init` immediately. If you need to create new
132+ instances at runtime, make sure this does not happen on an I/O thread.
133+* if a connection pool is busy, the driver will block until a connection
134+ becomes available. To avoid this, set
135+ [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the
136+ driver will not block, just move to the next host immediately.
137+* if the session is set to a specific keyspace (either at startup or by
138+ issuing a `USE` statement on a running session), the keyspace needs to
139+ be propagated to any newly created connection. This is done when the
140+ connection is first borrowed from the connection pool, and currently
141+ blocks. To avoid any issue, only use a session with no keyspace set
142+ (i.e. created by `Cluster#connect()`). This will be addressed in
143+ [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893).
144+* trying to read fields from a [query trace] will block if the trace
145+ hasn't been fetched already.
146+
147+[ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
148+[init]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#init()
149+[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
150+[query trace]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryTrace.html
added manual/compression/README.md +88 −0
@@ -0,0 +1,88 @@
1+## Compression
2+
3+Cassandra's binary protocol supports optional compression of
4+transport-level requests and responses, for example:
5+
6+* a query with its serialized parameters;
7+* a [page](../paging/) from a result set, i.e. a list of serialized
8+ rows.
9+
10+It reduces network traffic at the cost of CPU overhead, therefore it
11+will likely be beneficial when you have larger payloads.
12+
13+Two algorithms are available:
14+[LZ4](https://github.com/jpountz/lz4-java) and
15+[Snappy](https://code.google.com/p/snappy/).
16+Both rely on third-party libraries, declared by the driver as *optional*
17+dependencies. So If you use a build tool like Maven, you'll need to
18+declare an explicit dependency to pull the appropriate library in your
19+application's classpath. Then you configure compression at driver
20+startup.
21+
22+### LZ4
23+
24+Maven dependency:
25+
26+```xml
27+<dependency>
28+ <groupId>net.jpountz.lz4</groupId>
29+ <artifactId>lz4</artifactId>
30+ <version>1.2.0</version>
31+</dependency>
32+```
33+
34+Always check the exact version of the library: go to the driver's
35+[parent POM][pom] (change the URL to match your driver version) and look
36+for the `lz4.version` property.
37+
38+Driver configuration:
39+
40+```java
41+cluster = Cluster.builder()
42+ .addContactPoint("127.0.0.1")
43+ .withCompression(ProtocolOptions.Compression.LZ4)
44+ .build();
45+```
46+
47+LZ4-java has three internal implementations (from fastest to slowest):
48+
49+* JNI;
50+* pure Java using sun.misc.Unsafe;
51+* pure Java using only "safe" classes.
52+
53+It will pick the best implementation depending on what's possible on
54+your platform. To find out which one was chosen, [enable INFO
55+logs](../logging/) on the category
56+`com.datastax.driver.core.FrameCompressor` and look for a log similar to
57+this:
58+
59+```
60+INFO com.datastax.driver.core.FrameCompressor - Using LZ4Factory:JNI
61+```
62+
63+### Snappy
64+
65+Maven dependency:
66+
67+```xml
68+<dependency>
69+ <groupId>org.xerial.snappy</groupId>
70+ <artifactId>snappy-java</artifactId>
71+ <version>1.0.5</version>
72+</dependency>
73+```
74+
75+Always check the exact version of the library: go to the driver's
76+[parent POM][pom] (change the URL to match your driver version) and look
77+for the `snappy.version` property.
78+
79+Driver configuration:
80+
81+```java
82+cluster = Cluster.builder()
83+ .addContactPoint("127.0.0.1")
84+ .withCompression(ProtocolOptions.Compression.SNAPPY)
85+ .build();
86+```
87+
88+[pom]: https://repo1.maven.org/maven2/com/datastax/cassandra/cassandra-driver-parent/3.0.0-rc1/cassandra-driver-parent-3.0.0-rc1.pom
added manual/custom_codecs/README.md +468 −0
@@ -0,0 +1,468 @@
1+## Custom Codecs
2+
3+Custom codecs support transparent, user-configurable mapping of CQL types to arbitrary Java objects.
4+
5+Practical use cases that justify such a feature are numerous:
6+
7+* Ability to map CQL timestamp, date and time columns to Java 8 or Joda Time classes (rather than the built-in mappings for Date, [LocalDate] and Long);
8+* Ability to map CQL varchar columns directly to JSON or XML mapped objects (i.e. using frameworks such as Jackson);
9+* Ability to map CQL user-defined types to Java objects;
10+* Ability to map CQL lists directly to Java arrays;
11+* Ability to map CQL collections directly to Scala collections;
12+* etc.
13+
14+### Overview of the serialization mechanism
15+
16+The central piece in the serialization mechanism is [TypeCodec].
17+
18+Each `TypeCodec` supports a bidirectional mapping between a Java type and a CQL type. A `TypeCodec` is thus capable of 4 basic operations:
19+
20+* [Serialize][serialize] a Java object into a CQL value;
21+* [Deserialize][deserialize] a CQL value into a Java object;
22+* [Format][TypeCodec.format] a Java object into a CQL literal;
23+* [Parse][TypeCodec.parse] a CQL literal into a Java object.
24+
25+Additionally, it implements inspection methods that verify if the codec is suitable for a specific
26+CQL type and/or Java object.
27+
28+`TypeCodec` can be freely subclassed by users willing to implement their own serialization logic.
29+However, users are only required to do so when they want to extend
30+the driver's default set of codecs by registering additional codecs that handle
31+Java types that the driver is otherwise unable to process. For all other users,
32+the built-in set of codecs that is bundled with the driver provides
33+exactly the same functionality that the driver used to offer so far,
34+with out-of-the-box conversion from all CQL types to standard Java equivalents.
35+
36+Refer to the [javadocs][TypeCodec] of `TypeCodec` for more information.
37+
38+`TypeCodec`s are centralized in a [CodecRegistry] instance.
39+Whenever the driver needs to perform one of the aforementioned operations,
40+it will lookup for an appropriate codec in a `CodecRegistry`.
41+`CodecRegistry` is also used to manually register user-created codecs (see below for detailed instructions).
42+It also caches codec lookup results for faster execution whenever possible.
43+
44+Refer to the [javadocs][CodecRegistry] of `CodecRegistry` for more information.
45+
46+### Implementing and using custom codecs
47+
48+Let's consider the following scenario: a user has JSON documents stored in a varchar column, and wants
49+the driver to automatically map that column to a Java object using the [Jackson] library,
50+instead of returning the raw JSON string.
51+
52+The (admittedly simplistic) table structure is as follows:
53+
54+```sql
55+CREATE TABLE t (id int PRIMARY KEY, json VARCHAR);
56+```
57+
58+The first step is to implement a suitable codec. Using Jackson, here is what a Json codec could look like:
59+
60+```java
61+/**
62+ * A simple Json codec.
63+ */
64+public class JsonCodec<T> extends TypeCodec<T> {
65+
66+ private final ObjectMapper objectMapper = new ObjectMapper();
67+
68+ public JsonCodec(Class<T> javaType) {
69+ super(DataType.varchar(), javaType);
70+ }
71+
72+ @Override
73+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
74+ if (value == null)
75+ return null;
76+ try {
77+ return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
78+ } catch (JsonProcessingException e) {
79+ throw new InvalidTypeException(e.getMessage(), e);
80+ }
81+ }
82+
83+ @Override
84+ @SuppressWarnings("unchecked")
85+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
86+ if (bytes == null)
87+ return null;
88+ try {
89+ byte[] b = new byte[bytes.remaining()];
90+ // always duplicate the ByteBuffer instance before consuming it!
91+ bytes.duplicate().get(b);
92+ return (T)objectMapper.readValue(b, toJacksonJavaType());
93+ } catch (IOException e) {
94+ throw new InvalidTypeException(e.getMessage(), e);
95+ }
96+ }
97+
98+ @Override
99+ public String format(T value) throws InvalidTypeException {
100+ if (value == null)
101+ return NULL;
102+ String json;
103+ try {
104+ json = objectMapper.writeValueAsString(value);
105+ } catch (IOException e) {
106+ throw new InvalidTypeException(e.getMessage(), e);
107+ }
108+ return '\'' + json.replace("\'", "''") + '\'';
109+ }
110+
111+ @Override
112+ @SuppressWarnings("unchecked")
113+ public T parse(String value) throws InvalidTypeException {
114+ if (value == null || value.isEmpty() || value.equals(NULL))
115+ return null;
116+ if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
117+ throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
118+ String json = value.substring(1, value.length() - 1).replace("''", "'");
119+ try {
120+ return (T)objectMapper.readValue(json, toJacksonJavaType());
121+ } catch (IOException e) {
122+ throw new InvalidTypeException(e.getMessage(), e);
123+ }
124+ }
125+
126+ protected JavaType toJacksonJavaType() {
127+ return TypeFactory.defaultInstance().constructType(getJavaType().getType());
128+ }
129+
130+}
131+```
132+
133+A few implementation guidelines:
134+
135+* Your codecs should be thread-safe, or better yet, immutable;
136+* Your codecs should be fast: do not forget that codecs are executed often and are usually very "hot" pieces of code;
137+* Your codecs should never block.
138+
139+The second step is to register your codec with a `CodecRegistry` instance:
140+
141+```java
142+ObjectMapper objectMapper = ...
143+JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
144+CodecRegistry myCodecRegistry = cluster.getConfiguration().getCodecRegistry();
145+myCodecRegistry.register(myJsonCodec);
146+```
147+
148+As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`.
149+By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
150+which should be adequate for most users.
151+
152+It is however possible to create a `Cluster` using a different `CodecRegistry`:
153+
154+```java
155+CodecRegistry myCodecRegistry = new CodecRegistry();
156+Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
157+```
158+
159+Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver.
160+This ensures that the new registry will not lack of an essential codec. *You cannot deregister nor override
161+an already-registered codec, only register new ones*. If you try to register a codec that would override
162+an existing one, the driver will log a warning and ignore it.
163+
164+From now on, your custom codec is fully operational. It will be used every time the driver encounters
165+a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
166+
167+For example, here is how to save a `MyPojo` object:
168+
169+```java
170+Cluster cluster = ...
171+Session session = ...
172+MyPojo myPojo = ...
173+// Using SimpleStatement
174+Statement stmt = new SimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
175+// Using the Query Builder
176+BuiltStatement insertStmt = QueryBuilder.insertInto("t")
177+ .value("id", 42)
178+ .value("json", myPojo);
179+// Using BoundStatements
180+PreparedStatement ps = session.prepare("INSERT INTO t (id, json) VALUES (?, ?)");
181+BoundStatement bs1 = ps.bind(42, myPojo); // or alternatively...
182+BoundStatement bs2 = ps.bind()
183+ .setInt(0, 42)
184+ .set(1, myPojo, MyPojo.class);
185+```
186+
187+And here is how to retrieve a `MyPojo` object converted from a JSON document:
188+
189+```java
190+ResultSet rows = session.execute(...);
191+Row row = one();
192+// Let the driver convert the string for you...
193+MyPojo myPojo = row.get(1, MyPojo.class);
194+// ... or retrieve the raw string if you need it
195+String json = row.get(1, String.class); // row.getString(1) would have worked too
196+```
197+
198+Tip: `Row` and `BoundStatement` have several methods to set and retrieve values.
199+But if you plan to use custom codecs,
200+make sure that you use preferably the `get()` and `set()` methods: they
201+avoid any ambiguity by requiring the user to explicitly specify the desired Java type,
202+thus forcing the driver to pick the right codec for the right task.
203+
204+### On-the-fly codec generation
205+
206+`CodecRegistry` instances not only store default codecs and user-defined codecs;
207+they can also create new codecs on the fly, based on the set of codecs they currently hold.
208+They can manage the following mappings:
209+
210+* Collections (list, sets and maps) of known types. For example, if you registered a `TypeCodec<A>`, you get `List<A>>` handled for free. This works recursively for nested collections;
211+* [UserType] instances are automatically mapped to [UDTValue] objects. All registered codecs are available recursively to the UDT's fields;
212+* [TupleType] instances are automatically mapped to [TupleValue] objects (with the same rules for nested fields);
213+* [CustomType] instances are automatically mapped to [ByteBuffer] instances.
214+
215+This way, the user does not have to manually register all derived codecs for a given "base" codec.
216+However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly;
217+such codecs must be manually registered.
218+
219+If the codec registry encounters a mapping that it can't handle automatically, a [CodecNotFoundException]
220+is thrown.
221+
222+Thanks to on-the-fly codec generation, it is possible to leverage the `JsonCodec` from our previous
223+example to retrieve lists of `MyPojo` objects stored in a CQL column of type `list<text>`, without
224+the need to explicitly declare a codec for this specific CQL type:
225+
226+```java
227+JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
228+myCodecRegistry.register(myJsonCodec);
229+Row row = ...
230+List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class); // works out of the box!
231+```
232+
233+### Creating custom codecs for user-defined types (UDTs)
234+
235+By default, the driver maps user-defined type values to [UDTValue] instances.
236+
237+If you want to register a custom codec for a specific user-defined type,
238+follow these steps:
239+
240+Let's suppose you have a keyspace containing the following type and table:
241+
242+```sql
243+CREATE TYPE address (street VARCHAR, zipcode INT);
244+CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR, address frozen<address>);
245+```
246+
247+And let's suppose that you want to map the type `address` to an `Address` class:
248+
249+```java
250+public class Address {
251+
252+ private final String street;
253+
254+ private final int zipcode;
255+
256+ public Address(String street, int zipcode) {
257+ this.street = street;
258+ this.zipcode = zipcode;
259+ }
260+
261+ // getters, setters, equals() and hashcode() omitted
262+}
263+```
264+
265+First of all, create a codec that knows how to serialize this class; one possible solution
266+(but not necessarily the most efficient one) would be to convert `Address` instances into `UDTValue`
267+instances, then serialize them with another codec:
268+
269+
270+```java
271+public class AddressCodec extends TypeCodec<Address> {
272+
273+ private final TypeCodec<UDTValue> innerCodec;
274+
275+ private final UserType userType;
276+
277+ public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
278+ super(innerCodec.getCqlType(), javaType);
279+ this.innerCodec = innerCodec;
280+ this.userType = (UserType)innerCodec.getCqlType();
281+ }
282+
283+ @Override
284+ public ByteBuffer serialize(Address value, ProtocolVersion protocolVersion) throws InvalidTypeException {
285+ return innerCodec.serialize(toUDTValue(value), protocolVersion);
286+ }
287+
288+ @Override
289+ public Address deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
290+ return toAddress(innerCodec.deserialize(bytes, protocolVersion));
291+ }
292+
293+ @Override
294+ public Address parse(String value) throws InvalidTypeException {
295+ return value == null || value.isEmpty() || value.equals(NULL) ? null : toAddress(innerCodec.parse(value));
296+ }
297+
298+ @Override
299+ public String format(Address value) throws InvalidTypeException {
300+ return value == null ? null : innerCodec.format(toUDTValue(value));
301+ }
302+
303+ protected Address toAddress(UDTValue value) {
304+ return value == null ? null : new Address(
305+ value.getString("street"),
306+ value.getInt("zipcode")
307+ );
308+ }
309+
310+ protected UDTValue toUDTValue(Address value) {
311+ return value == null ? null : userType.newValue()
312+ .setString("street", value.getStreet())
313+ .setInt("zipcode", value.getZipcode());
314+ }
315+}
316+```
317+
318+Now (and only if you intend to use your own `CodecRegistry`),
319+create it and register it on your `Cluster` instance:
320+
321+```java
322+// only if you do not intend to use CodecRegistry.DEFAULT_INSTANCE
323+CodecRegistry codecRegistry = new CodecRegistry();
324+Cluster cluster = Cluster.builder()
325+ .addContactPoints(...)
326+ .withCodecRegistry(codecRegistry)
327+ .build();
328+```
329+
330+Now, retrieve the metadata for type `address`:
331+
332+```java
333+UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address");
334+TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType);
335+```
336+
337+And finally, register your `AddressCodec` with the `CodecRegistry`. Note that
338+your codec simply delegates the hard work to an inner codec that knows how to deal with
339+user type values:
340+
341+```java
342+AddressCodec addressCodec = new AddressCodec(addressTypeCodec, Address.class);
343+codecRegistry.register(addressCodec);
344+```
345+
346+And voilà! You can now retrieve `address` values as `Address` instances:
347+
348+```java
349+ResultSet rows = session.execute(...);
350+Row row = rows.one();
351+// let the driver convert it for you...
352+Address address = row.get("address", Address.class);
353+// ...or access the low-level UDTValue, if you need
354+UDTValue addressUdt = row.get("address", UDTValue.class); // row.getUDTValue("address") would have worked too
355+```
356+
357+Note that this solution creates an intermediary `UDTValue` object when
358+serializing and deserializing. It's possible to bypass this step with a
359+lower-level implementation that manipulates the binary stream directly.
360+That's also how the object mapper handles UDTs, and you can rely on the
361+mapper to generate UDT codecs for you; see
362+[this page](../object_mapper/custom_codecs/#implicit-udt-codecs) for more
363+information.
364+
365+### Support for generic (parameterized) types
366+
367+Java generic (parameterized) types are fully supported, through Guava's [TypeToken] API.
368+Be sure to only use `get()` and `set()` methods that take a `TypeToken` argument:
369+
370+```java
371+// this works
372+Foo<Bar> foo = row.get(0, new TypeToken<Foo<Bar>>(){})
373+// this does not work due to type erasure
374+Foo<Bar> foo = row.get(0, Foo.class);
375+```
376+
377+### Support for subtype polymorphism
378+
379+Suppose the following class hierarchy:
380+
381+```java
382+class Animal {}
383+class Cat extends Animal {}
384+```
385+
386+By default, a codec will accept to serialize any object that extends or
387+implements its declared Java type: a codec such as
388+`AnimalCodec extends TypeCodec<Animal>` will accept `Cat` instances as well.
389+
390+This allows a codec to handle interfaces and superclasses
391+in a generic way, regardless of the actual implementation being
392+used by client code; for example, the driver has a built-in codec
393+that handles `List` instances, and this codec is capable of
394+serializing any concrete `List` implementation.
395+
396+But this has one caveat: when setting or retrieving values
397+with `get()` and `set()`, *it is vital to pass the exact
398+Java type the codec handles*:
399+
400+```java
401+codecRegistry.register(new AnimalCodec());
402+BoundStatement bs = ...
403+bs.set(0, new Cat(), Animal.class); // works
404+bs.set(0, new Cat(), Cat.class); // throws CodecNotFoundException
405+```
406+
407+The same is valid when retrieving values:
408+
409+```java
410+codecRegistry.register(new AnimalCodec());
411+Row row = ...
412+Animal animal = row.get(0, Animal.class); // works
413+Cat cat = row.get(0, Cat.class); // throws CodecNotFoundException
414+```
415+
416+### Performance considerations
417+
418+A codec lookup operation may be costly; to mitigate this, the `CodecRegistry`
419+caches lookup results whenever possible.
420+
421+When the cache can be used and the registry looks up a codec, the following rules apply:
422+
423+1. if a result was previously cached for that mapping, it is returned;
424+2. otherwise, the registry checks the list of "basic" codecs: the default ones,
425+and the ones that were explicitly registered (in the order that they were registered).
426+It calls each codec's [accepts] methods to determine if it can handle the mapping,
427+and if so, adds it to the cache and returns it;
428+3. otherwise, the registry tries to generate a codec on the fly, according to the rules outlined above;
429+4. if the creation succeeds, the registry adds the created codec to the cache and returns it;
430+5. otherwise, the registry throws [CodecNotFoundException].
431+
432+The cache can be used as long as *at least the CQL type is known*. The following situations
433+are exceptions where it is *not* possible to cache lookup results:
434+
435+* With [SimpleStatement] instances;
436+* With [BuiltStatement] instances (created via the Query Builder).
437+
438+In these places, the driver has no way to determine the right CQL type to use, so it performs
439+a best-effort heuristic to guess which codec to use. The result of this heuristic is never cached.
440+
441+Beware that in these cases, the lookup performs in average 10x worse. If performance is a key factor for your application,
442+consider using prepared statements all the time.
443+
444+[JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
445+[TypeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html
446+[LocalDate]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/LocalDate.html
447+[ByteBuffer]: http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html
448+[serialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#serialize(T,%20com.datastax.driver.core.ProtocolVersion)
449+[deserialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#deserialize(java.nio.ByteBuffer,%20com.datastax.driver.core.ProtocolVersion)
450+[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#format(T)
451+[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#parse(java.lang.String)
452+[accepts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#accepts-com.datastax.driver.core.DataType-
453+[CodecRegistry]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/CodecRegistry.html
454+[CodecNotFoundException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/CodecNotFoundException.html
455+[Jackson]: http://wiki.fasterxml.com/JacksonHome
456+[AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
457+[UserType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UserType.html
458+[UDTValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UDTValue.html
459+[TupleType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleType.html
460+[TupleValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleValue.html
461+[CustomType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/DataType.CustomType.html
462+[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
463+[SimpleStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SimpleStatement.html
464+[BuiltStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/BuiltStatement.html
465+[setList]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setList(int,%20java.util.List)
466+[setSet]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setSet(int,%20java.util.Set)
467+[setMap]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setMap(int,%20java.util.Map)
468+[setObject]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setObject(int,%20V)
added manual/custom_payloads/README.md +248 −0
@@ -0,0 +1,248 @@
1+## Custom Payloads
2+
3+The [native protocol](../native_protocol/) version 4 introduces a new feature called [Custom Payloads][CASSANDRA-8553].
4+
5+According to the [protocol V4 specification][v4spec], custom payloads are generic key-value maps
6+where keys are strings and each value is an arbitrary sequence of bytes. Currently payloads
7+can be sent by clients along with all `QUERY`, `PREPARE`, `EXECUTE` and `BATCH` requests.
8+
9+Custom payloads can be used to convey user-specific information from clients to servers and vice versa.
10+_Please note that this is an advanced feature that requires specific server-side configuration (see below)._
11+
12+### Enabling custom payloads on C* nodes
13+
14+What the server is supposed to do with a payload depends on the [QueryHandler][qh] used server-side
15+to decode requests. Unsurprisingly, the default `QueryHandler` implementation used by Cassandra
16+simply ignores all payloads. However, users can replace it with their own implementation,
17+thus being able to to process user-specific payloads; the payload format as well as
18+the serialization and deserialization logic is entirely left for clients to implement.
19+Needless to say, the same encoding and decoding logic should be applied on both client
20+and server endpoints.
21+
22+This section is a small how-to to help driver users getting started with
23+custom payload processing server-side. For more detailed information,
24+please refer to the Cassandra documentation itself.
25+
26+To enable a custom `QueryHandler` for a Cassandra node, its JVM should be
27+started with the system property `cassandra.custom_query_handler_class` set
28+to a fully qualified name of a class implementing `org.apache.cassandra.cql3.QueryHandler`.
29+This class should be of course available on the node's classpath.
30+
31+This can be achieved with the following steps:
32+
33+1. Add your implementation jar to the `CLASSPATH` environment variable;
34+2. Add the following to `$CASSANDRA_CONF/cassandra-env.sh`:
35+
36+```
37+JVM_EXTRA_OPTS="-Dcassandra.custom_query_handler_class=fully.qualified.name.of.MyQueryHandler"
38+```
39+
40+Of course, all nodes in the cluster *must* be started with the same QueryHandler, otherwise
41+payloads sent by the driver could get lost.
42+
43+### Implementation Notes
44+
45+Payloads in the Java driver are represented as `Map<String,ByteBuffer>` instances.
46+It is safe to use any `Map` implementation, including unsynchronized implementations
47+such as `java.util.HashMap`; the driver will create defensive, thread-safe copies of
48+user-supplied maps. However, `ByteBuffer` instances are inherently mutable,
49+so callers should take care not to modify the `ByteBuffer` values in a payload map *after* submitting it
50+to the driver as it could lead to unexpected results.
51+
52+#### Null values
53+
54+Note that, for thread safety reasons, the Java driver does not permit `null` keys nor `null` values in a payload map;
55+including a `null` in your payload will result in a `NullPointerException` being immediately thrown.
56+
57+However, the protocol specification *does* allow `null` values. If you need to include
58+a `null` value in your payload map, this can be achieved with the Java driver
59+by using the special value `Statement.NULL_PAYLOAD_VALUE`.
60+
61+##### Payload length limitations
62+
63+1. Payload maps cannot have more than 65,535 entries.
64+2. Payload map values are limited to a maximum length of `Integer.MAX_VALUE` (2<sup><small>31</small></sup> − 1) bytes each.
65+
66+### Sending custom payloads
67+
68+A custom payload can be attached to any `Statement` via `Statement.setOutgoingPayload()`.
69+
70+Once the payload is set, you can either prepare the statement or execute it;
71+in both cases, the payload will be sent along with the `PREPARE` or `QUERY` request respectively:
72+
73+```java
74+Statement statement = new SimpleStatement("SELECT foo FROM bar WHERE qix = 1");
75+statement.setOutgoingPayload(myCustomPayload);
76+session.execute(statement); // myCustomPayload will be sent with QUERY request
77+session.prepare(statement); // myCustomPayload will be sent with PREPARE request
78+```
79+
80+Naturally, you can also set a payload when using the `QueryBuilder` API:
81+
82+```java
83+Statement statement = QueryBuilder.select("c2").from("t1").where(eq("c1", 1)).setOutgoingPayload(myCustomPayload);
84+session.execute(statement); // myCustomPayload will be sent with EXECUTE request
85+```
86+
87+When sending payloads with batches, please note that payloads must be attached to the
88+`BatchStatement` itself, *not* to internal statements:
89+
90+```java
91+Statement statement = new SimpleStatement("INSERT INTO t1 (c1, c2) values ('foo', 'bar')")
92+// correct
93+Statement batch = new BatchStatement().add(statement);
94+batch.setOutgoingPayload(myCustomPayload);
95+session.execute(batch); // myCustomPayload will be sent with BATCH request
96+// wrong
97+statement.setOutgoingPayload(myCustomPayload);
98+Statement batch = new BatchStatement().add(statement);
99+session.execute(batch); // myCustomPayload will NOT be sent with BATCH request
100+```
101+
102+One important note about paging requests: if your query needs to paginate,
103+any outgoing payload set on the executed statement *will be transparently
104+sent over and over for every new page request*.
105+
106+```java
107+Statement statement = new SimpleStatement("...");
108+statement.setOutgoingPayload(myCustomPayload);
109+ResultSet rows = session.execute(...); // myCustomPayload will be sent with first QUERY request
110+for (Row row : rows) {
111+ // if additional QUERY requests are sent, all of them will send the same payload
112+}
113+```
114+
115+And finally, note that custom payloads can only be used with protocol versions >= 4;
116+trying to set a payload under lower protocol versions will result in
117+an [UnsupportedFeatureException][ufe] (wrapped in a [NoHostAvailableException][nhae])
118+when the request is encoded.
119+
120+If you want to defensively protect your code against these errors, you can either:
121+
122+1) Force the protocol version when creating your `Cluster` instance:
123+
124+```java
125+Cluster cluster = Cluster.builder()
126+ .addContactPoint("...")
127+ .withProtocolVersion(ProtocolVersion.V4)
128+ .build();
129+```
130+
131+2) Inspect the current negotiated protocol version, and only send payloads if version is equal to or
132+greater than 4:
133+
134+```java
135+ProtocolVersion myCurrentVersion = cluster.getConfiguration()
136+ .getProtocolOptions()
137+ .getProtocolVersionEnum();
138+if (myCurrentVersion.compareTo(ProtocolVersion.V4) >= 0) {
139+ // only send custom payloads if current protocol version supports it
140+ statement.setOutgoingPayload(myCustomPayload);
141+}
142+```
143+
144+### Receiving custom payloads
145+
146+Custom payloads sent back by the server can be retrieved in the following ways:
147+
148+1) From a `ResultSet`: use the `ExecutionInfo` class to retrieve the payload sent by the server.
149+
150+```java
151+Statement statement = new SimpleStatement("...");
152+ResultSet rows = session.execute(...);
153+// last payload sent by the server
154+Map<String,ByteBuffer> serverPayload = rows.getExecutionInfo().getIncomingPayload();
155+```
156+
157+If your query required pagination (multiple `QUERY` requests),
158+the above method would only return the last payload sent by server
159+with its last `RESULT` response. If you need to retrieve all the
160+payloads for all `RESULT` responses, use the following method instead:
161+
162+```java
163+Statement statement = new SimpleStatement("...");
164+ResultSet rows = session.execute(...);
165+//all payloads sent by the server
166+for (ExecutionInfo info : rows.getAllExecutionInfo()) {
167+ Map<String,ByteBuffer> serverPayload = info.getIncomingPayload();
168+}
169+```
170+
171+2) From a `PreparedStatement`: to retrieve the payload that the server sent back
172+with its `PREPARED` response, use the following method:
173+
174+```java
175+PreparedStatement ps = session.prepare(...);
176+Map<String,ByteBuffer> serverPayload = ps.getIncomingPayload();
177+```
178+
179+### Custom Payloads and Prepared Statements
180+
181+If you use either `Session.prepare(RegularStatement)` or `Session.prepareAsync(RegularStatement)`
182+to prepare a statement, as with all other properties in the given statement, its outgoing
183+payload, if any, will become the default outgoing payload for the prepared statement.
184+
185+```java
186+Statement statement = new SimpleStatement("...");
187+statement.setOutgoingPayload(myCustomPayload)
188+PreparedStatement ps = session.prepare(...); // myCustomPayload will be sent with PREPARE request
189+ // AND become the default outgoing payload
190+```
191+
192+Naturally, you can also set a default outgoing payload on the `PreparedStatement` instance itself.
193+The code below is roughly equivalent to the one above - except that the payload is not sent
194+with the `PREPARE` request:
195+
196+```java
197+Statement statement = new SimpleStatement("...");
198+PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request
199+ps.setOutgoingPayload(myCustomPayload) // default outgoing payload is now myCustomPayload
200+```
201+
202+But `PreparedStatement` has also a `getIncomingPayload()` method, which, as we already know,
203+can be used to retrieve incoming payloads sent back by the server that prepared the request.
204+
205+When binding a statement - with either `PreparedStatement.bind()` or `PreparedStatement.bind(Object...)`) -
206+`BoundStatement` instances will also inherit payloads.
207+
208+To determine which payload is going to be used as outgoing payload for a bound statement,
209+the following rules apply:
210+
211+1. If the prepared statement has a non-null outgoing payload, all instances of `BoundStatement`
212+ created out of it will inherit that payload as their outgoing payload;
213+2. Otherwise, if the prepared statement has a non-null incoming payload, all instances of `BoundStatement`
214+ created out of it will inherit that payload as their outgoing payload;
215+3. Otherwise, all instances of `BoundStatement` created out of it
216+ won't have any outgoing payload set by default; users can however set an outgoing payload on
217+ individual `BoundStatement` instances by calling their `setOutgoingPayload()` method,
218+ like in the example below:
219+
220+```java
221+Statement statement = new SimpleStatement("...");
222+PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request
223+BoundStatement bs = ps.bind(1); // no outgoing payload by default
224+bs.setOutgoingPayload(myCustomPayload); // outgoing payload for this specific statement
225+session.execute(statement); // myCustomPayload will be sent with EXECUTE request for this bound statement only
226+```
227+
228+### Debugging custom payloads
229+
230+When debugging custom payloads, set the `com.datastax.driver.core.Message` logger to the `TRACE` level, e.g. with Log4J:
231+
232+```xml
233+<logger name="com.datastax.driver.core.Message">
234+ <level value="TRACE"/>
235+</logger>
236+```
237+
238+This will log a message for every request and every response that contains a non-null payload.
239+The log message contains a pretty-printed version of the payload itself, and its total length in bytes.
240+
241+[CASSANDRA-8553]: https://issues.apache.org/jira/browse/CASSANDRA-8553
242+[v4spec]: https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec
243+[qh]: https://issues.apache.org/jira/browse/CASSANDRA-6659
244+[nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
245+[chm]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html
246+[immutablemap]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html
247+[ufe]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/UnsupportedFeatureException.html
248+
added manual/logging/README.md +305 −0
@@ -0,0 +1,305 @@
1+## Logging
2+
3+### Setup
4+
5+DataStax Java driver uses the popular [SLF4J](http://www.slf4j.org) library to emit log messages;
6+SLF4J has the advantage of providing a logging API that is entirely decoupled from concrete
7+implementations, letting client applications free to seamlessly connect SLF4J to their preferred logging backend.
8+
9+The driver itself does not attempt to configure any concrete logging framework.
10+It is up to client applications using the driver to correctly set up their classpath and
11+runtime configuration to be able to capture log messages emitted by the driver.
12+Concretely, client applications need to provide, at runtime, a *binding* to any logging framework
13+of their choice that is [compatible with SLF4J](http://www.slf4j.org/manual.html#swapping).
14+
15+If your application is built with Maven, this usually involves adding one (runtime) dependency to your POM file.
16+For example, if you intend to use [Logback](http://logback.qos.ch), add the following dependency:
17+
18+```xml
19+<dependency>
20+ <groupId>ch.qos.logback</groupId>
21+ <artifactId>logback-classic</artifactId>
22+ <version>1.1.3</version>
23+</dependency>
24+```
25+
26+If you are using Log4J 1.2 instead, add the following dependency:
27+
28+```xml
29+<dependency>
30+ <groupId>org.slf4j</groupId>
31+ <artifactId>slf4j-log4j12</artifactId>
32+ <version>1.7.12</version>
33+</dependency>
34+```
35+
36+Check [SLF4J's documentation](http://www.slf4j.org/manual.html#projectDep) for examples for
37+other logging frameworks, and for troubleshooting dependency resolution problems.
38+
39+### Configuration
40+
41+Each logging framework has its own configuration rules, but all of them provide
42+different levels (DEBUG, INFO, WARN, ERROR...), different *loggers* or *categories*
43+(messages from different categories or loggers can be filtered out separately or printed out
44+differently), and different *appenders* (message receptacles such as the standard console,
45+the error console, a file on disk, a socket...).
46+
47+Check your logging framework documentation for more information about how to properly configure it.
48+You can also find some configuration examples below.
49+
50+### Useful loggers
51+
52+When debugging the Java driver, the following loggers could be particularly useful
53+and provide hints about what's going wrong.
54+
55+* `com.datastax.driver.core.Cluster`
56+ * ERROR
57+ * Authentication errors
58+ * Unexpected errors when handling events, reconnecting, refreshing schemas
59+ * Unexpected events
60+ * WARN
61+ * Cluster name mismatches
62+ * Unreachable contact points
63+ * Unsupported protocol versions
64+ * Schema disagreements
65+ * Ignored notifications due to high contention
66+ * INFO
67+ * Hosts added or removed
68+ * DEBUG
69+ * Cluster lifecycle (start, shutdown)
70+ * Event delivery notifications (schema changes, topology changes)
71+ * Topology change events: hosts Up / Down / Added / Removed
72+ * Hosts being ignored
73+ * Protocol version negotiation
74+ * Reconnection attempts
75+ * Schema metadata refreshes
76+ * TRACE
77+ * Connection pools lifecycle (create, renew, refresh)
78+* `com.datastax.driver.core.Session`
79+ * ERROR
80+ * Errors related to connection pools
81+ * WARN
82+ * Problems related to connection pools
83+ * DEBUG
84+ * Connection pools lifecycle (create, renew, refresh)
85+* `com.datastax.driver.core.RequestHandler`
86+ * ERROR
87+ * Unexpected errors preparing queries
88+ * Queries sent to a bootstrapping host
89+ * Unexpected server errors
90+ * WARN
91+ * Queries sent to an overloaded host
92+ * INFO
93+ * Unprepared queries
94+ * DEBUG
95+ * Retry attempts
96+ * TRACE
97+ * Host currently being queried
98+* `com.datastax.driver.core.Connection`
99+ * WARN
100+ * Problem setting keyspace
101+ * Errors closing Netty channel
102+ * DEBUG
103+ * Connection lifecycle (open, close, defunct)
104+ * Error connecting or writing requests
105+ * Heartbeats
106+ * TRACE
107+ * Authentication progress
108+ * Sending requests
109+ * Receiving responses
110+* `com.datastax.driver.core.Message`
111+ * TRACE
112+ * Custom payloads
113+
114+### Logging query latencies
115+
116+The `QueryLogger` provides clients with the ability to log queries
117+executed by the driver, and especially, it allows client to track slow
118+queries, i.e. queries that take longer to complete than a configured
119+threshold in milliseconds.
120+
121+To turn on this feature, you first need to instantiate and register a `QueryLogger` instance:
122+
123+```java
124+Cluster cluster = ...
125+QueryLogger queryLogger = QueryLogger.builder()
126+ .withConstantThreshold(...)
127+ .withMaxQueryStringLength(...)
128+.build();
129+cluster.register(queryLogger);
130+```
131+
132+Note that `QueryLogger` instances are thread-safe and can be shared cluster-wide.
133+Besides, you can adjust several parameters such as the maximum query string length to be printed,
134+the maximum number of parameters to print, etc. Refer to the
135+`QueryLogger` [API docs][query_logger] for more information.
136+
137+Secondly, you need to adjust your logging framework to accept log messages from the `QueryLogger`. The `QueryLogger`
138+uses 3 different loggers:
139+
140+* `com.datastax.driver.core.QueryLogger.NORMAL` : Used to log normal queries, i.e., queries that completed successfully within a configurable threshold in milliseconds.
141+* `com.datastax.driver.core.QueryLogger.SLOW` : Used to log slow queries, i.e., queries that completed successfully but that took longer than a configurable threshold in milliseconds to complete.
142+* `com.datastax.driver.core.QueryLogger.ERROR`: Used to log unsuccessful queries, i.e., queries that did not complete normally and threw an exception. Note this this logger will also print the full stack trace of the reported exception.
143+
144+You need to set the above loggers to DEBUG level to turn them on. E.g. to track queries
145+that take more than 300 ms to complete, configure your `QueryLogger` with that threshold (see above),
146+then set the `com.datastax.driver.core.QueryLogger.SLOW` logger to DEBUG, e.g. with Log4J:
147+
148+```xml
149+ <logger name="com.datastax.driver.core.QueryLogger.SLOW">
150+ <level value="DEBUG"/>
151+ </logger>
152+```
153+
154+The `QueryLogger` would then print messages such as this for every slow query:
155+
156+```
157+DEBUG [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=?;
158+```
159+
160+As you can see, actual query parameters are not logged; if you want them to be printed as well, set the `com.datastax.driver.core.QueryLogger.SLOW` logger
161+to TRACE instead, e.g. with Log4J:
162+
163+```xml
164+ <logger name="com.datastax.driver.core.QueryLogger.SLOW">
165+ <level value="TRACE"/>
166+ </logger>
167+```
168+
169+The `QueryLogger` would then print messages such as this for every slow query:
170+
171+```
172+TRACE [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=? [user_id=42];
173+```
174+
175+Be careful when logging large query strings (specially batches) and/or queries with considerable amounts of parameters.
176+See the `QueryLogger` [API docs][query_logger] for examples of how to truncate the printed message when necessary.
177+
178+#### Constant vs Dynamic thresholds
179+
180+Currently the `QueryLogger` can be configured to track slow queries using either
181+a constant threshold in milliseconds (which is the default behavior), or
182+a dynamic threshold based on per-host latency percentiles, as computed by `PerHostPercentileTracker`.
183+
184+**Dynamic thresholds are still a beta feature: they haven't been extensively
185+tested yet, and the API is still subject to change.**
186+
187+Refer to the `QueryLogger` [API docs][query_logger] for an example of usage.
188+
189+### Performance Tips
190+
191+* Use asynchronous appenders; both [Log4J](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html)
192+and [Logback](http://logback.qos.ch/manual/appenders.html#AsyncAppender) provide asynchronous appenders
193+that can significantly boost latencies when writing log messages.
194+* While the driver does not provide such capability, it is possible for client applications to hot-reload the log configuration
195+without stopping the application. This usually involves JMX and is available for [Logback](http://logback.qos.ch/manual/jmxConfig.html);
196+Log4J provides a `configureAndWatch()` method but it is not recommended to use it inside J2EE containers (see [FAQ](https://logging.apache.org/log4j/1.2/faq.html#a3.6)).
197+
198+### Logback Example
199+
200+Here is a typical example configuration for Logback. *Please adapt it to your specific needs before using it!*
201+
202+It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
203+By default, only messages with ERROR level or higher are logged.
204+
205+It also turns on slow query tracing as described above.
206+
207+```xml
208+<?xml version="1.0" encoding="UTF-8"?>
209+<configuration>
210+
211+ <!-- log INFO or higher messages to the console -->
212+ <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
213+ <encoder>
214+ <pattern>%-5p %msg%n</pattern>
215+ </encoder>
216+ </appender>
217+
218+ <!-- log everything to a rolling file -->
219+ <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
220+ <file>driver.log</file>
221+ <encoder>
222+ <pattern>%-5p [%d{ISO8601}] [%t] %F:%L - %msg%n</pattern>
223+ </encoder>
224+ <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
225+ <!-- daily rollover -->
226+ <fileNamePattern>driver.%d{yyyy-MM-dd}.log</fileNamePattern>
227+ <!-- keep 30 days' worth of history -->
228+ <maxHistory>30</maxHistory>
229+ </rollingPolicy>
230+ </appender>
231+
232+ <!-- use AsyncAppender for lower latencies -->
233+ <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
234+ <appender-ref ref="console" />
235+ <appender-ref ref="file" />
236+ </appender>
237+
238+ <!--
239+ Turn on slow query logging by setting this logger to DEBUG;
240+ set level to TRACE to also log query parameters
241+ -->
242+ <logger name="com.datastax.driver.core.QueryLogger.SLOW" level="DEBUG" />
243+
244+ <root level="ERROR">
245+ <appender-ref ref="async" />
246+ </root>
247+
248+</configuration>
249+```
250+
251+### Log4J Example
252+
253+Here is a typical example configuration for Log4J. *Please adapt it to your specific needs before using it!*
254+
255+It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
256+By default, only messages with ERROR level or higher are logged.
257+
258+It also turns on slow query tracing as described above.
259+
260+```xml
261+<log4j:configuration>
262+
263+ <!-- log INFO or higher messages to the console -->
264+ <appender name="console" class="org.apache.log4j.ConsoleAppender">
265+ <param name="threshold" value="INFO"/>
266+ <layout class="org.apache.log4j.PatternLayout">
267+ <param name="ConversionPattern" value="%-5p %m%n"/>
268+ </layout>
269+ </appender>
270+
271+ <!-- log everything to a rolling file -->
272+ <appender name="file" class="org.apache.log4j.RollingFileAppender">
273+ <param name="file" value="driver.log"/>
274+ <param name="append" value="false"/>
275+ <param name="maxFileSize" value="1GB"/>
276+ <param name="maxBackupIndex" value="10"/>
277+ <layout class="org.apache.log4j.PatternLayout">
278+ <param name="ConversionPattern" value="%-5p [%d{ISO8601}] [%t] %F:%L - %m%n"/>
279+ </layout>
280+ </appender>
281+
282+ <!-- use AsyncAppender for lower latencies -->
283+ <appender name="async" class="org.apache.log4j.AsyncAppender">
284+ <param name="BufferSize" value="500"/>
285+ <appender-ref ref="file"/>
286+ <appender-ref ref="console"/>
287+ </appender>
288+
289+ <!--
290+ Turn on slow query logging by setting this logger to DEBUG;
291+ set level to TRACE to also log query parameters
292+ -->
293+ <logger name="com.datastax.driver.core.QueryLogger.SLOW">
294+ <level value="DEBUG"/>
295+ </logger>
296+
297+ <root>
298+ <priority value="ERROR"/>
299+ <appender-ref ref="async"/>
300+ </root>
301+
302+</log4j:configuration>
303+```
304+
305+[query_logger]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryLogger.html
added manual/metadata/README.md +194 −0
@@ -0,0 +1,194 @@
1+## Metadata
2+
3+The driver maintains global information about the Cassandra cluster it
4+is connected to. It is available via
5+[Cluster#getMetadata()][getMetadata].
6+
7+[getMetadata]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.html#getMetadata()
8+
9+### Schema metadata
10+
11+Use [getKeyspace(String)][getKeyspace] or [getKeyspaces()][getKeyspaces]
12+to get keyspace-level metadata. From there you can access the keyspace's
13+objects (tables, and UDTs and UDFs if relevant).
14+
15+[getKeyspace]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getKeyspace(java.lang.String)
16+[getKeyspaces]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getKeyspaces()
17+
18+#### Refreshes
19+
20+Schema metadata gets refreshed in the following circumstances:
21+
22+* **schema changes via the driver**: after successfully executing a
23+ schema-altering query (ex: `CREATE TABLE`), the driver waits for
24+ schema agreement (see below), then refreshes the schema.
25+* **third-party schema changes**: if another client (cqlsh, other driver
26+ instance...) changes the schema, the driver gets notified by Cassandra
27+ via a push notification. It refreshes the schema directly (there is no
28+ need to wait for schema agreement since Cassandra has already done it).
29+
30+#### Subscribing to schema changes
31+
32+Users interested in being notified of schema changes can implement the
33+[SchemaChangeListener][SchemaChangeListener] interface.
34+
35+Every listener must [be registered][registerListener] against a `Cluster` instance:
36+
37+```java
38+Cluster cluster = ...
39+SchemaChangeListener myListener = ...
40+cluster.register(myListener);
41+```
42+
43+Once registered, the listener will be notified of all schema changes detected by the driver,
44+regardless of where they originate from.
45+
46+Note that it is preferable to register a listener only *after* the cluster is fully initialized,
47+otherwise the listener could be notified with a great deal of "Added" events as
48+the driver builds the schema metadata from scratch for the first time.
49+
50+[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SchemaChangeListener.html
51+[registerListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#register(com.datastax.driver.core.SchemaChangeListener)
52+
53+#### Schema agreement
54+
55+Schema changes need to be propagated to all nodes in the cluster. Once
56+they have settled on a common version, we say that they are in
57+agreement.
58+
59+As explained above, the driver waits for schema agreement after
60+executing a schema-altering query. This is to ensure that subsequent
61+requests (which might get routed to different nodes) see an up-to-date
62+version of the schema.
63+
64+```ditaa
65+ Application Driver Cassandra
66+------+--------------------+------------------+-----
67+ | | |
68+ | CREATE TABLE... | |
69+ |------------------->| |
70+ | | send request |
71+ | |----------------->|
72+ | | |
73+ | | success |
74+ | |<-----------------|
75+ | | |
76+ | /--------------------\ |
77+ | :Wait until all nodes+------>|
78+ | :agree (or timeout) : |
79+ | \--------------------/ |
80+ | | ^ |
81+ | | | |
82+ | | +---------|
83+ | | |
84+ | | refresh schema |
85+ | |----------------->|
86+ | |<-----------------|
87+ | complete query | |
88+ |<-------------------| |
89+ | | |
90+```
91+
92+The schema agreement wait is performed synchronously, so the `execute`
93+call -- or the completion of the `ResultSetFuture` if you use the async
94+API -- will only return after it has completed.
95+
96+The check is implemented by repeatedly querying system tables for the
97+schema version reported by each node, until they all converge to the
98+same value. If that doesn't happen within a given timeout, the driver
99+will give up waiting. The default timeout is 10 seconds, it can be
100+customized when building your cluster:
101+
102+```java
103+Cluster cluster = Cluster.builder()
104+ .addContactPoint("127.0.0.1")
105+ .withMaxSchemaAgreementWaitSeconds(20)
106+ .build();
107+```
108+
109+After executing a statement, you can check whether schema agreement was
110+successful or timed out:
111+
112+```java
113+ResultSet rs = session.execute("CREATE TABLE...");
114+if (rs.getExecutionInfo().isSchemaInAgreement()) {
115+ // schema is in agreement
116+} else {
117+ // schema agreement timed out
118+}
119+```
120+
121+You can also perform an on-demand check at any time:
122+
123+```java
124+if (cluster.getMetadata().checkSchemaAgreement()) {
125+ // schema is in agreement
126+} else {
127+ // schema is not in agreement
128+}
129+```
130+
131+The on-demand check does not retry, it only queries system tables once
132+(so `maxSchemaAgreementWaitSeconds` does not apply). If you need
133+retries, you'll have to schedule them yourself (for example with a
134+custom executor).
135+
136+Check out the API docs for the features in this section:
137+
138+* [withMaxSchemaAgreementWaitSeconds(int)](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.Builder.html#withMaxSchemaAgreementWaitSeconds(int))
139+* [isSchemaInAgreement()](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ExecutionInfo.html#isSchemaInAgreement())
140+* [checkSchemaAgreement()](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#checkSchemaAgreement())
141+
142+
143+### Token metadata
144+
145+This feature is probably of less interest to regular driver users, but
146+it will be useful if you're writing an analytics client on top of the
147+driver.
148+
149+[Metadata][metadata] exposes a number of methods to manipulate tokens
150+and ranges: [getTokenRanges()][getTokenRanges], [getTokenRanges(String
151+keyspace, Host host)][getTokenRanges2], [getReplicas(String keyspace,
152+TokenRange range)][getReplicas], [newToken(String)][newToken] and
153+[newTokenRange(Token start, Token end)][newTokenRange].
154+
155+[TokenRange][TokenRange] provides various operations on ranges
156+(splitting, merging, etc.).
157+
158+Each host exposes its primary tokens as [getTokens()][getTokens].
159+
160+Finally, you can inject tokens in CQL queries with
161+[BoundStatement#setToken][setToken], and retrieve them from results with
162+[Row#getToken][getToken] and [Row#getPartitionKeyToken][getPKToken].
163+
164+As an example, here is how you could compute the splits to partition a
165+job (pseudocode):
166+
167+```
168+metadata = cluster.getMetadata()
169+for range : metadata.getTokenRanges() {
170+ hosts = metadata.getReplicas(keyspace, range)
171+ int n = estimateNumberOfSplits() // more on that below
172+ for split : range.splitEvenly(n)
173+ // pick a host to process split
174+}
175+```
176+
177+For `estimateNumberOfSplits`, you need a way to estimate the total
178+number of partition keys (this is what analytics clients would
179+traditionally do with the Thrift operation `describe_splits_ex`).
180+Starting with Cassandra 2.1.5, this information is available in a system
181+table (see
182+[CASSANDRA-7688](https://issues.apache.org/jira/browse/CASSANDRA-7688)).
183+
184+[metadata]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html
185+[getTokenRanges]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getTokenRanges()
186+[getTokenRanges2]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getTokenRanges(java.lang.String,%20com.datastax.driver.core.Host)
187+[getReplicas]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#getReplicas(java.lang.String,%20com.datastax.driver.core.TokenRange)
188+[newToken]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#newToken(java.lang.String)
189+[newTokenRange]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metadata.html#newTokenRange(com.datastax.driver.core.Token,%20com.datastax.driver.core.Token)
190+[TokenRange]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TokenRange.html
191+[getTokens]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Host.html#getTokens()
192+[setToken]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BoundStatement.html#setToken(int,%20com.datastax.driver.core.Token)
193+[getToken]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Row.html#getToken(int)
194+[getPKToken]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Row.html#getPartitionKeyToken()
added manual/native_protocol/README.md +112 −0
@@ -0,0 +1,112 @@
1+## Native protocol
2+
3+The native protocol defines the format of the binary messages exchanged
4+between the driver and Cassandra over TCP. As a driver user, you don't
5+need to know the fine details (although the protocol spec is [in the
6+Cassandra codebase][native_spec] if you're curious); the most visible
7+aspect is that some features are only available with specific protocol
8+versions.
9+
10+[native_spec]: https://github.com/apache/cassandra/tree/trunk/doc
11+
12+### Compatibility matrix
13+
14+By default, the protocol version is negotiated between the driver and
15+Cassandra when the first connection is established. Both sides are
16+backward-compatible with older versions:
17+
18+<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
19+<tr><td>&nbsp;</td><td>Cassandra: 1.2.x<br/>(DSE 3.2)</td><td>2.0.x<br/>(DSE 4.0 to 4.6)</td><td>2.1.x<br/>(DSE 4.7)</td><td>2.2.x</td><td>3.0.x</td></tr>
20+<tr><td>Driver: 1.0.x</td> <td>v1</td> <td>v1</td> <td>v1</td> <td>v1</td> <td>Unsupported <i>(1)</i></td> </tr>
21+<tr><td>2.0.x to 2.1.1</td> <td>v1</td> <td>v2</td> <td>v2</td> <td>v2</td> <td>Unsupported <i>(1)</i></td> </tr>
22+<tr><td>2.1.2 to 2.1.x</td> <td>v1</td> <td>v2</td> <td>v3</td> <td>v3</td> <td>Unsupported <i>(2)</i></td> </tr>
23+<tr><td>3.x</td> <td>v1</td> <td>v2</td> <td>v3</td> <td>v4</td> <td>v4</td> </tr>
24+</table>
25+
26+*(1) Cassandra 3.0 does not support protocol versions v1 and v2*
27+
28+*(2) There is a matching protocol version (v3), but the driver 2.1.x can't read the new system table format of Cassandra 3.0*
29+
30+For example, if you use version 2.1.5 of the driver to connect to
31+Cassandra 2.0.9, the maximum version you can use (and the one you'll get
32+by default) is protocol v2 (third row, second column). If you use the
33+same version to connect to Cassandra 2.1.4, you can use protocol v3.
34+
35+### Controlling the protocol version
36+
37+To find out which version you're currently using, use
38+[ProtocolOptions#getProtocolVersion()][gpv]:
39+
40+```java
41+ProtocolVersion myCurrentVersion = cluster.getConfiguration()
42+ .getProtocolOptions()
43+ .getProtocolVersionEnum();
44+```
45+
46+The protocol version can not be changed at runtime. However, you can
47+force a given version at initialization:
48+
49+```java
50+Cluster cluster = Cluster.builder()
51+ .addContactPoint("127.0.0.1")
52+ .withProtocolVersion(ProtocolVersion.V2)
53+ .build();
54+```
55+
56+If you specify a version that is not compatible with your current
57+driver/Cassandra combination, you'll get an error:
58+
59+```
60+Exception in thread "main" com.datastax.driver.core.exceptions.NoHostAvailableException:
61+All host(s) tried for query failed
62+(tried: /127.0.0.1:9042 (com.datastax.driver.core.UnsupportedProtocolVersionException:
63+ [/127.0.0.1:9042] Host /127.0.0.1:9042 does not support protocol version V3 but V2))
64+```
65+
66+[gpv]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion()
67+
68+#### Protocol version with mixed clusters
69+
70+If you have a cluster with mixed versions (for example, while doing a
71+rolling upgrade of Cassandra), note that **the protocol version will be
72+negotiated with the first host the driver connects to**.
73+
74+This could lead to the following situation (assuming you use driver
75+2.1.2+):
76+
77+* the first contact point is a 2.1 host, so the driver negotiates
78+ protocol v3;
79+* while connecting to the rest of the cluster, the driver contacts a 2.0
80+ host using protocol v3, which fails; an error is logged and this host
81+ will be permanently ignored.
82+
83+To avoid this issue, you can use one the following workarounds:
84+
85+* always force a protocol version at startup. You keep it at v2 while
86+ the rolling upgrade is happening, and only switch to v3 when the whole
87+ cluster has switched to Cassandra 2.1;
88+* ensure that the list of initial contact points only contains hosts
89+ with the oldest version (2.0 in this example).
90+
91+
92+### New features by protocol version
93+
94+#### v1 to v2
95+
96+* bound variables in simple statements
97+ ([Session#execute(String, Object...)](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#execute(java.lang.String,%20java.lang.Object...)))
98+* [batch statements](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BatchStatement.html)
99+* [query paging](../paging/)
100+
101+#### v2 to v3
102+
103+* the number of stream ids per connection goes from 128 to 32768 (see
104+ [Connection pooling](../pooling/))
105+* [serial consistency on batch statements](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BatchStatement.html#setSerialConsistencyLevel(com.datastax.driver.core.ConsistencyLevel))
106+* [client-side timestamps](../query_timestamps/)
107+
108+#### v3 to v4
109+
110+* [query warnings](http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ExecutionInfo.html#getWarnings())
111+* allowed unset values in bound statements
112+* [Custom payloads](../custom_payloads/)
added manual/object_mapper/.nav +3 −0
@@ -0,0 +1,3 @@
1+creating
2+using
3+custom_codecs
No newline at the end of the file
added manual/object_mapper/README.md +18 −0
@@ -0,0 +1,18 @@
1+# Object Mapper
2+
3+Version 2.1 of the driver introduces a simple object mapper, which
4+avoids most of the boilerplate when converting your domain classes to
5+and from query results. It handles basic CRUD operations in Cassandra tables
6+containing UDTs, collections and all native CQL types.
7+
8+The mapper is published as a separate Maven artifact:
9+
10+```xml
11+<dependency>
12+ <groupId>com.datastax.cassandra</groupId>
13+ <artifactId>cassandra-driver-mapping</artifactId>
14+ <version>3.0.0-rc1</version>
15+</dependency>
16+```
17+
18+This documentation is organized in subsections describing mapper features.
added manual/object_mapper/creating/README.md +224 −0
@@ -0,0 +1,224 @@
1+## Definition of mapped classes
2+
3+The object mapper is configured by annotations on the mapped classes.
4+
5+### Creating a table entity
6+
7+A table entity is a class that will be mapped to a table in Cassandra.
8+It is annotated with [@Table][table]:
9+
10+```
11+CREATE TABLE user (user_id uuid PRIMARY KEY, name text);
12+```
13+
14+```java
15+@Table(keyspace = "ks", name = "users",
16+ readConsistency = "QUORUM",
17+ writeConsistency = "QUORUM",
18+ caseSensitiveKeyspace = false,
19+ caseSensitiveTable = false)
20+public static class User {
21+ @PartitionKey
22+ @Column(name = "user_id")
23+ private UUID userId;
24+ private String name;
25+ // ... constructors / getters / setters
26+}
27+```
28+
29+`@Table` takes the following options:
30+
31+- `keyspace`: the keyspace for the table.
32+- `name`: the name of the table in the database.
33+- `caseSensitiveKeyspace`: whether the keyspace name is [case-sensitive].
34+- `caseSensitiveTable`: whether the table name is [case-sensitive].
35+- `readConsistency`: the [consistency level] that will be used on each
36+ get operation in the mapper. (if unspecified, it defaults to the
37+ cluster-wide setting)
38+- `writeConsistency`: the [consistency level] that will be used on each
39+ save, or delete operation in the mapper. (if unspecified, it defaults
40+ to the cluster-wide setting)
41+
42+The class must provide a default constructor, and all fields (except the
43+ones annotated `@Transient`) must have corresponding setters and
44+getters.
45+
46+[table]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Table.html
47+[case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html
48+[consistency level]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ConsistencyLevel.html
49+
50+#### Column names
51+
52+By default, the mapper tries to map each Java property to a
53+case insensitive column of the same name. If you want to use a different
54+name, or [case-sensitive] names, use the [@Column][column] annotation on
55+the field.
56+
57+[column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html
58+
59+#### Primary key fields
60+
61+[@PartitionKey][pk] and [@ClusteringColumn][cc] are used to indicate the
62+[partition key][pks] and [clustering columns][pks]. In the case of a
63+composite partition key or multiple clustering columns, the integer
64+value indicates the position of the column in the key:
65+
66+```
67+CREATE TABLE sales(countryCode text, areaCode text, sales int,
68+ PRIMARY KEY((countryCode, area Code)));
69+```
70+
71+```java
72+@PartitionKey(0)
73+private String countryCode;
74+@PartitionKey(1)
75+private String areaCode;
76+```
77+
78+The order of the indices must match that of the columns in the table
79+declaration.
80+
81+[pk]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/PartitionKey.html
82+[cc]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/ClusteringColumn.html
83+[pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html
84+
85+#### Computed fields
86+
87+[@Computed][computed] can be used on fields that are the result of a
88+computation on the Cassandra side. Typically a function call. Native
89+functions in Cassandra like `writetime()` or [User Defined Functions] are
90+supported.
91+
92+```java
93+@Computed("ttl(name)")
94+Integer ttl;
95+```
96+
97+The CQL return type of function must match the type of the field,
98+otherwise an exception will be thrown.
99+
100+Computed fields are ignored when saving an entity.
101+
102+`@Computed` does not support case-sensitivity. If the expression
103+contains case-sensitive column or function names, you'll have to escape
104+them:
105+
106+```java
107+@Computed("\"myFunction\"(\"myColumn\")")
108+int f;
109+```
110+
111+Finally, computed fields are only supported with [basic read
112+operations](../using/#basic-crud-operations) at this time.
113+Support in [accessors](../using/#accessors) in planned for a future
114+version (see
115+[JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)).
116+
117+[User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/
118+[computed]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Computed.html
119+
120+#### Transient fields
121+
122+[@Transient][transient] can be used to prevent a field from being mapped.
123+
124+[transient]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Transient.html
125+
126+### Mapping User Types
127+
128+[User Defined Types] can also be mapped by using [@UDT][udt]:
129+
130+```
131+CREATE TYPE address (street text, zip_code int);
132+```
133+
134+```java
135+@UDT(keyspace = "ks", name = "address")
136+class Address {
137+ private String street;
138+ @Field(name = "zip_code")
139+ private int zipCode;
140+ // ... constructors / getters / setters
141+}
142+```
143+
144+`@UDT` takes the following options:
145+
146+- `keyspace`: the keyspace for the UDT.
147+- `name`: the name of the UDT in the database.
148+- `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive.
149+- `caseSensitiveType`: whether the UDT name is case-sensitive.
150+
151+The class must provide a default constructor, and all fields (except the
152+ones annotated `@Transient`) must have corresponding setters and
153+getters.
154+
155+As in table entities, fields are mapped to an UDT field of the same
156+name by default. To declare a different name or use case-sensitivity,
157+use the [@Field][field] annotation:
158+
159+```java
160+@Field(name = "zip_code")
161+private int zipCode;
162+```
163+
164+When a table has a UDT column, the mapper will automatically map it to
165+the corresponding class:
166+
167+```
168+CREATE TABLE company (company_id uuid PRIMARY KEY, name text, address address);
169+```
170+
171+```java
172+public static class Company {
173+ @PartitionKey
174+ @Column(name = "company_id")
175+ private UUID companyId;
176+ private String name;
177+ private Address address;
178+}
179+```
180+
181+(this also works with UDTs inside collections or other UDTs, with
182+arbitrary level of nesting)
183+
184+[User Defined Types]:http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/reference/userDefinedTypes.html
185+[udt]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/UDT.html
186+[field]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Field.html
187+
188+### Mapping collections
189+
190+Java collections will be automatically mapped into corresponding
191+Cassandra types. As in Cassandra, collections can contain all native
192+types and all [user types](#mapping-user-types) previously defined is
193+the database.
194+
195+Collection and UDT fields should be annotated to indicate whether they are
196+frozen. Currently this is only for informational purposes (the mapper
197+won't check that the declarations match the rules in Cassandra).
198+However it is a good idea to keep using these annotations and make sure
199+they match the schema, in anticipation for the schema generation features
200+that will be added in a future version.
201+The default annotation is [@Frozen][frozen], [@FrozenKey][frozenkey] and
202+[@FrozenValue][frozenvalue]` are also provided for convenience:
203+
204+```java
205+// Will be mapped as a 'list<text>'
206+private List<String> stringList;
207+
208+// Will be mapped as a 'frozen<list<text>>'
209+@Frozen
210+private List<String> frozenStringList;
211+
212+// Will be mapped as 'map<frozen<address>, frozen<list<text>>>'
213+@FrozenKey
214+@FrozenValue
215+private Map<Address, List<String>> frozenKeyValueMap;
216+
217+// Will be mapped as 'map<text, frozen<list<address>>>'
218+@FrozenValue
219+private Map<String, List<Address>> frozenValueMap;
220+```
221+
222+[frozen]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Frozen.html
223+[frozenkey]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenKey.html
224+[frozenvalue]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenValue.html
added manual/object_mapper/custom_codecs/README.md +147 −0
@@ -0,0 +1,147 @@
1+# Using custom codecs
2+
3+The mapper can take advantage of [custom codecs](../../custom_codecs/)
4+to apply custom conversions to mapped columns and fields.
5+
6+## Declaring codecs
7+
8+Let's assume you have a table containing a timestamp column:
9+
10+```
11+create table user(id int primary key, birth timestamp);
12+```
13+
14+You've created a custom class, and the codec to convert it:
15+
16+```java
17+public class MyCustomDate { ... }
18+
19+public class MyCustomDateCodec extends TypeCodec<MyCustomDate> {
20+ public MyCustomDate() {
21+ super(DataType.timestamp(), MyCustomDate.class);
22+ }
23+ ...
24+}
25+```
26+
27+### Pre-registered codecs
28+
29+If you register your codec with the mapper's underlying `Cluster`, it
30+will be automatically available to the mapper:
31+
32+```java
33+Cluster cluster = Cluster.builder()
34+ .addContactPoint("127.0.0.1")
35+ .withCodecRegistry(
36+ new CodecRegistry().register(new MyCustomDateCodec())
37+ ).build();
38+
39+MappingManager mappingManager = new MappingManager(cluster.connect());
40+```
41+
42+You can normally create your mapped classes using your custom type,
43+without any additional configuration:
44+
45+```java
46+@Table(name = "user")
47+public class User {
48+ @PartitionKey
49+ private int id;
50+ private MyCustomDate birth;
51+
52+ ... // getters and setters
53+}
54+```
55+
56+This also works in accessors:
57+
58+```java
59+@Accessor
60+interface UserAccessor {
61+ @Query("update user set birth = :b where id = :i)
62+ void updateBirth(@Param("i") int id,
63+ @Param("b") MyCustomDate birth);
64+}
65+```
66+
67+### One-time declaration
68+
69+Sometimes you might want to use your codec only for one particular
70+column/field. In that case you won't register it when initializing the
71+`Cluster`:
72+
73+```java
74+Cluster cluster = Cluster.builder()
75+ .addContactPoint("127.0.0.1")
76+ .build();
77+
78+MappingManager mappingManager = new MappingManager(cluster.connect());
79+```
80+
81+Instead, reference the codec's class in the [@Column][column]
82+annotation:
83+
84+```java
85+@Table(name = "user")
86+public class User {
87+ @PartitionKey
88+ private int id;
89+ @Column(codec = MyCustomDateCodec.class)
90+ private MyCustomDate birth;
91+
92+ ... // getters and setters
93+}
94+```
95+
96+The class must have a no-arg constructor. The mapper will create an
97+instance (one per column) and cache it for future use.
98+
99+This also works with [@Field][field] and [@Param][param] annotations.
100+
101+[column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html
102+[field]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Field.html
103+[param]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Param.html
104+
105+
106+## Implicit UDT codecs
107+
108+The mapper uses custom codecs internally to handle UDT conversions: when
109+you register an [entity](../using/#entity-mappers), the mapper inspects
110+the type of all fields to find classes annotated with
111+[@UDT](../creating/#mapping-user-types) (this works recursively with
112+nested UDTs and collections). For each class, the mapper creates a codec
113+and registers it with the underlying `Cluster`.
114+
115+```java
116+@UDT(name = "address")
117+public class Address { ... }
118+
119+@Entity(name = "user")
120+public class User {
121+ ...
122+ private Address address;
123+ ...
124+}
125+
126+Mapper<User> userMapper = mappingManager.mapper(User.class);
127+
128+// Codec is now registered for Address <-> CQL address
129+```
130+
131+A nice side-effect is that you can now use the `@UDT`-annotated class
132+with any driver method, not just mapper methods:
133+
134+```java
135+Row row = session.execute("select address from user where id = 1").one();
136+Address address = row.get("address", Address.class);
137+```
138+
139+If you don't use entity mappers but still want the convenience of the
140+UDT codec for core driver methods, the mapper provides a way to create
141+it independently:
142+
143+```java
144+mappingManager.udtCodec(Address.class);
145+
146+// Codec is now registered
147+```
added manual/object_mapper/using/README.md +295 −0
@@ -0,0 +1,295 @@
1+## Using the mapper
2+
3+First, create a [MappingManager]. It wraps an existing [Session]
4+instance:
5+
6+```java
7+MappingManager manager = new MappingManager(session);
8+```
9+
10+`MappingManager` is thread-safe and can be safely shared throughout your
11+application. You would typically create one instance at startup, right
12+after your `Session`.
13+
14+Note that `MappingManager` will initialize the `Session` if not
15+previously done (this was not the case in previous driver versions; if
16+this is a problem for you, see `MappingManager(session, protocolVersion)`).
17+
18+### Entity mappers
19+
20+Each entity class (annotated with `@Table`) is managed by a dedicated
21+[Mapper] object. You obtain this object from the `MappingManager`:
22+
23+```java
24+Mapper<User> mapper = manager.mapper(User.class);
25+```
26+
27+`Mapper` objects are thread-safe. The manager caches them internally, so
28+calling `manager#mapper` more than once for the same class will return
29+the previously generated mapper.
30+
31+[Mapper]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/Mapper.html
32+[MappingManager]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/MappingManager.html
33+[Session]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html
34+
35+#### Basic CRUD operations
36+
37+To save an object, use `Mapper#save`:
38+
39+```java
40+UUID userId = ...;
41+User u = new User(userId, "John Doe", new Address("street", 01000));
42+mapper.save(u);
43+```
44+
45+--------------
46+
47+To retrieve an object, use `Mapper#get`:
48+
49+```java
50+UUID userId = ...;
51+User u = mapper.get(userId);
52+```
53+
54+`get`'s arguments must match the partition key components (number of
55+arguments and their types).
56+
57+--------------
58+
59+To delete a row in a table, use `Mapper#delete`. This method support
60+deleting a row given either its primary keys, or the object to delete:
61+
62+```java
63+UUID userId = ...;
64+mapper.delete(userId);
65+mapper.delete(u);
66+```
67+
68+--------------
69+
70+All these CRUD operations are synchronous, but the `Mapper` provides
71+their asynchronous equivalents:
72+
73+```java
74+ListenableFuture<Void> saveFuture = mapper.saveAsync(u);
75+ListenableFuture<User> userFuture = mapper.getAsync(userId);
76+ListenableFuture<Void> deleteFuture = mapper.deleteAsync(userId);
77+```
78+
79+#### Mapper options
80+
81+The basic CRUD operations accept additional options to customize the
82+underlying query:
83+
84+- `ttl`: add a time-to-live value for the operation.
85+- `timestamp`: add a timestamp value for the operation.
86+- `consistencyLevel`: specify a consistency level.
87+- `tracing`: set tracing flag for the query.
88+- `saveNullFields`: if set to true, fields with value `null` in an
89+ instance that is to be persisted will be explicitly written as `null`
90+ in the query. If set to false, fields with null value won't be included
91+ in the write query (thus avoiding tombstones). If not specified, the
92+ default behavior is to persist `null` fields.
93+
94+To use options, add them to the mapper call after regular parameters:
95+
96+```java
97+import static com.datastax.driver.mapping.Mapper.Option.*;
98+
99+mapper.save(new User(userId, "helloworld"),
100+ timestamp(123456L), tracing(true), ttl(42));
101+```
102+
103+Some options don't apply to all operations:
104+
105+<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
106+ <tr> <td><b>Option</b></td> <td><b>save/saveQuery</b></td> <td><b>get/getQuery</b></td> <td><b>delete/deleteQuery</b></td></tr>
107+ <tr> <td>Ttl</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
108+ <tr> <td>Timestamp</td> <td>yes</td> <td>no</td> <td>yes</td> </tr>
109+ <tr> <td>ConsistencyLevel</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
110+ <tr> <td>Tracing</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr>
111+ <tr> <td>SaveNullFields</td> <td>yes</td> <td>no</td> <td>no</td> </tr>
112+</table>
113+
114+Note that `Option.consistencyLevel` is redundant with the consistency
115+level defined by [@Table](../creating/#creating-a-table-entity).
116+If both are defined, the option will take precedence over the
117+annotation.
118+
119+Default options can be defined for each type of operation:
120+
121+```java
122+mapper.setDefaultGetOption(tracing(true), consistencyLevel(QUORUM));
123+mapper.setDefaultSaveOption(saveNullFields(false));
124+mapper.setDefaultDeleteOption(consistencyLevel(ONE));
125+
126+// Given the defaults above, this will use tracing(true), consistencyLevel(ONE)
127+mapper.get(uuid, consistencyLevel(ONE));
128+```
129+
130+To reset default options, use the following methods:
131+
132+```java
133+mapper.resetDefaultGetOption();
134+mapper.resetDefaultSaveOption();
135+mapper.resetDefaultDeleteOption();
136+```
137+
138+#### Access to underlying `Statement`s
139+
140+Instead of performing an operation directly, it's possible to ask the
141+`Mapper` to just return the corresponding `Statement` object. This gives
142+the client a chance to customize the statement before executing it.
143+
144+- `Mapper.saveQuery(entity)`: returns a statement generated by the
145+ mapper to save `entity` into the database.
146+- `Mapper.getQuery(userId)`: returns a statement to select a row in the
147+ database, selected on the given `userId`, and matching the mapped
148+ object structure.
149+- `Mapper.deleteQuery(userID)`: returns a statement delete a row in the
150+ database given the `userId` provided. This method can also accept a
151+ mapped object instance.
152+
153+#### Manual mapping
154+
155+`Mapper#map` provides a way to converts the results of a regular query:
156+
157+```java
158+ResultSet results = session.execute("SELECT * FROM user");
159+Result<User> users = mapper.map(results);
160+for (User u : users) {
161+ System.out.println("User : " + u.getUserId());
162+}
163+```
164+
165+This method will ignore:
166+
167+* extra columns in the `ResultSet` that are not mapped for this entity.
168+* mapped fields that are not present in the `ResultSet` (setters won't
169+ be called so the value will be the one after invocation of the class's
170+ default constructor).
171+
172+[Result] is similar to `ResultSet` but for a given mapped class.
173+It provides methods `one()`, `all()`, `iterator()`, `getExecutionInfo()`
174+and `isExhausted()`. Note that iterating the `Result` will consume the
175+`ResultSet`, and vice-versa.
176+
177+[Result]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/Result.html
178+
179+### Accessors
180+
181+`Accessor`s provide a way to map custom queries not supported by the
182+default entity mappers.
183+
184+To create an accessor, define a Java interface and annotate each method
185+to provide the corresponding CQL query:
186+
187+```java
188+@Accessor
189+public interface UserAccessor {
190+ @Query("SELECT * FROM user")
191+ Result<User> getAll();
192+}
193+```
194+
195+The `MappingManager` can then process this class and generate an
196+implementation:
197+
198+```java
199+UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
200+User user = userAccessor.getOne(uuid);
201+```
202+
203+Like mappers, accessors are cached at the manager level and thus, are
204+thread-safe/sharable.
205+
206+#### Parameters
207+
208+A query can have bind markers, that will be set with the method's
209+arguments.
210+
211+With unnamed markers, the order of the arguments must match the order of
212+the markers:
213+
214+```java
215+@Query("insert into user (id, name) values (?, ?)")
216+ResultSet insert(UUID userId, String name);
217+```
218+
219+With named markers, use [@Param][param] to indicate which parameter
220+corresponds to which marker:
221+
222+```java
223+@Query("insert into user (userId, name) values (:u, :n)")
224+ResultSet insert(@Param("u") UUID userId, @Param("n") String name);
225+```
226+
227+[param]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Param.html
228+
229+If a method argument is a Java enumeration, it must be annotated with
230+`@Enumerated` to indicate how to convert it to a CQL type (the rules are
231+the same as in [mapping definition](../creating/#enumerations)):
232+
233+```java
234+@Query("insert into user (key, gender) values (?,?)")
235+ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value);
236+```
237+
238+#### Return type
239+
240+The declared return type of each method affects how the query will get
241+executed:
242+
243+<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
244+ <tr> <td><b>Return type</b></td> <td><b>Effect</b></td> </tr>
245+ <tr>
246+ <td><code>void</code></td>
247+ <td>Synchronous execution, discards the results of the query.</td>
248+ </tr>
249+ <tr>
250+ <td><code>ResultSet</code></td>
251+ <td>Synchronous execution, returns unmapped results.</td>
252+ </tr>
253+ <tr>
254+ <td><code>T</code></td>
255+ <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns the first row (or <code>null</code> if there are no results).</td>
256+ </tr>
257+ <tr>
258+ <td><code>Result&lt;T&gt;</code></td>
259+ <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns a list of mapped objects.</td>
260+ </tr>
261+ <tr>
262+ <td><code>ResultSetFuture</code></td>
263+ <td>Asynchronous execution, returns unmapped results.</td>
264+ </tr>
265+ <tr>
266+ <td><code>ListenableFuture&lt;T&gt;</code></td>
267+ <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns the first row (or <code>null</code> if there are no results).</td>
268+ </tr>
269+ <tr>
270+ <td><code>ListenableFuture&lt;Result&lt;T&gt;&gt;</code></td>
271+ <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns a list of mapped objects.</td>
272+ </tr>
273+</table>
274+
275+Example:
276+
277+```java
278+@Query("SELECT * FROM user")
279+public ListenableFuture<Result<User>> getAllAsync();
280+```
281+
282+
283+#### Customizing the statement
284+
285+It is possible to customize query parameters to include in a `Accessor`
286+query with the annotation [@QueryParameters]. Then, options like
287+*consistency level*, *fetchsize* or *tracing* are settable:
288+
289+```java
290+@Query("SELECT * FROM ks.users")
291+@QueryParameters(consistency="QUORUM")
292+public ListenableFuture<Result<User>> getAllAsync();
293+```
294+
295+[@QueryParameters]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/QueryParameters.html
added manual/paging/README.md +268 −0
@@ -0,0 +1,268 @@
1+## Paging
2+
3+When a query returns many rows, it would be inefficient to return them
4+as a single response message. Instead, the driver breaks the results
5+into *pages* which get returned as they are needed.
6+
7+### Setting the fetch size
8+
9+The *fetch size* specifies how many rows will be returned at once by
10+Cassandra (in other words, it's the size of each page).
11+
12+You can set a default fetch size globally for a `Cluster` instance:
13+
14+```java
15+// At initialization:
16+Cluster cluster = Cluster.builder()
17+ .addContactPoint("127.0.0.1")
18+ .withQueryOptions(new QueryOptions().setFetchSize(2000))
19+ .build();
20+
21+// Or at runtime:
22+cluster.getConfiguration().getQueryOptions().setFetchSize(2000);
23+```
24+
25+The fetch size can also be set on a statement:
26+
27+```java
28+Statement statement = new SimpleStatement("your query");
29+statement.setFetchSize(2000);
30+```
31+
32+If the fetch size is set on a statement, it will take precedence;
33+otherwise, the cluster-wide value (which defaults to 5000) will be used.
34+
35+Note that setting a fetch size doesn't mean that Cassandra will always
36+return the exact number of rows, it is possible that it returns slightly
37+more or less results.
38+
39+### Result set iteration
40+
41+The fetch size limits the number of results that are returned in one
42+page; if you iterate past that, the driver will run background queries
43+to fetch subsequent pages. Here's an example with a fetch size of 20:
44+
45+```ditaa
46+ client Session Cassandra
47+ --+--------------+---------------------------------+-----
48+ |execute(query)| |
49+ |------------->| |
50+ | | query rows 1 to 20 |
51+ | |-------------------------------->|
52+ | | |
53+ | |create |
54+ | |------>ResultSet |
55+ | | |
56++-----+--------+-----------------+-+ |
57+|For i in 1..20| | | |
58++--------------+ | | |
59+| | get next row | | |
60+| |------------------------->| | |
61+| | row i | | |
62+| |<-------------------------| | |
63+| | | | |
64++-----+--------------------------+-+ |
65+ | | |
66+ | | |
67+ | get next row | |
68+ |------------------------->| |
69+ | | query rows 21 to 40 |
70+ | |-------------------->|
71+ | row 21 | |
72+ |<------------------------ | |
73+```
74+
75+By default, the background fetch happens at the last moment, when there
76+are no more "local" rows available. If you need finer control, the
77+[ResultSet][result_set] interface provides the following methods:
78+
79+* `getAvailableWithoutFetching()` and `isFullyFetched()` to check the
80+ current state;
81+* `fetchMoreResults()` to force a page fetch.
82+
83+Here's how you could use these methods to pre-fetch the next page in
84+advance, in order to avoid the performance hit at the end of each page:
85+
86+```java
87+ResultSet rs = session.execute("your query");
88+for (Row row : rs) {
89+ if (rs.getAvailableWithoutFetching() == 100 && !rs.isFullyFetched())
90+ rs.fetchMoreResults(); // this is asynchronous
91+ // Process the row ...
92+ System.out.println(row);
93+}
94+```
95+
96+If you use paging with the async API, you'll also want to use those
97+methods to avoid triggering synchronous fetches unintentionally; see
98+[async paging](../async/#async-paging).
99+
100+
101+### Saving and reusing the paging state
102+
103+Sometimes it is convenient to save the paging state in order to restore
104+it later. For example, consider a stateless web service that displays a
105+list of results with a link to the next page. When the user clicks that
106+link, we want to run the exact same query, except that the iteration
107+should start where we stopped on the previous page.
108+
109+To do so, the driver exposes a [PagingState][paging_state] object that represents
110+where we were in the result set when the last page was fetched:
111+
112+```java
113+ResultSet resultSet = session.execute("your query");
114+// iterate the result set...
115+PagingState pagingState = resultSet.getExecutionInfo().getPagingState();
116+```
117+
118+This object can be serialized to a `String` or a byte array:
119+
120+```java
121+String string = pagingState.toString();
122+byte[] bytes = pagingState.toBytes();
123+```
124+
125+This serialized form can be saved in some form of persistent storage to
126+be reused later. In our web service example, we would probably save the
127+string version as a query parameter in the URL to the next page
128+(`http://myservice.com/results?page=<...>`). When that value is
129+retrieved later, we can deserialize it and reinject it in a statement:
130+
131+```java
132+PagingState pagingState = PagingState.fromString(string);
133+Statement st = new SimpleStatement("your query");
134+st.setPagingState(pagingState);
135+ResultSet rs = session.execute(st);
136+```
137+
138+Note that the paging state can only be reused with the exact same
139+statement (same query string, same parameters). Also, it is an opaque
140+value that is only meant to be collected, stored an re-used. If you try
141+to modify its contents or reuse it with a different statement, the
142+driver will raise an error.
143+
144+Putting it all together, here's a more comprehensive example
145+implementation for our web service:
146+
147+```java
148+final int RESULTS_PER_PAGE = 100;
149+
150+Statement st = new SimpleStatement("your query");
151+st.setFetchSize(RESULTS_PER_PAGE);
152+
153+String requestedPage = extractPagingStateStringFromURL();
154+// This will be absent for the first page
155+if (requestedPage != null) {
156+ st.setPagingState(
157+ PagingState.fromString(requestedPage));
158+}
159+
160+ResultSet rs = session.execute(st);
161+PagingState nextPage = rs.getExecutionInfo().getPagingState();
162+
163+// Note that we don't rely on RESULTS_PER_PAGE, since Cassandra might
164+// have not respected it, or we might be at the end of the result set
165+int remaining = rs.getAvailableWithoutFetching();
166+for (Row row : rs) {
167+ renderInResponse(row);
168+ if (--remaining == 0) {
169+ break;
170+ }
171+}
172+
173+// This will be null if there are no more pages
174+if (nextPage != null) {
175+ renderNextPageLink(nextPage.toString());
176+}
177+```
178+
179+[result_set]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSet.html
180+[paging_state]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PagingState.html
181+
182+
183+Due to internal implementation details, `PagingState` instances are not
184+portable across [native protocol](../native_protocol/) versions. This
185+could become a problem in the following scenario:
186+
187+* you're using the driver 2.0.x and Cassandra 2.0.x, and therefore
188+ native protocol v2;
189+* a user bookmarks a link to your web service that contains a serialized
190+ paging state;
191+* you upgrade your server stack to use the driver 2.1.x and Cassandra
192+ 2.1.x, so you're now using protocol v3;
193+* the user tries to reload their bookmark, but the paging state was
194+ serialized with protocol v2, so trying to reuse it will fail.
195+
196+If this is not acceptable for you, you might want to consider the unsafe
197+API described in the next section.
198+
199+#### Unsafe API
200+
201+As an alternative to the standard API, there are two methods that
202+manipulate a raw `byte[]` instead of a `PagingState` object:
203+
204+* [ExecutionInfo#getPagingStateUnsafe()][gpsu]
205+* [Statement#setPagingStateUnsafe(byte[])][spsu]
206+
207+These low-level methods perform no validation on their arguments;
208+therefore nothing protects you from reusing a paging state that was
209+generated from a different statement, or altered in any way. This could
210+result in sending a corrupt paging state to Cassandra, with
211+unpredictable consequences (ranging from wrong results to a query
212+failure).
213+
214+There are two situations where you might want to use the unsafe API:
215+
216+* you never expose the paging state to end users and you are confident
217+ that it won't get altered;
218+* you want portability across protocol versions and/or you prefer
219+ implementing your own validation logic (for example, signing the raw
220+ state with a private key).
221+
222+[gpsu]: http://www.datastax.com/drivers/java/3.0/com/datastax/driver/core/ExecutionInfo.html#getPagingStateUnsafe()
223+[spsu]: http://www.datastax.com/drivers/java/3.0/com/datastax/driver/core/Statement.html#setPagingStateUnsafe(byte[])
224+
225+### Offset queries
226+
227+Saving the paging state works well when you only let the user move from
228+one page to the next. But it doesn't allow random jumps (like "go
229+directly to page 10"), because you can't fetch a page unless you have
230+the paging state of the previous one. Such a feature would require
231+*offset queries*, but they are not natively supported by Cassandra (see
232+[CASSANDRA-6511](https://issues.apache.org/jira/browse/CASSANDRA-6511)).
233+The rationale is that offset queries are inherently inefficient (the
234+performance will always be linear in the number of rows skipped), so the
235+Cassandra team doesn't want to encourage their use.
236+
237+If you really want offset queries, you can emulate them client-side.
238+You'll still get linear performance, but maybe that's acceptable for
239+your use case. For example, if each page holds 10 rows and you show at
240+most 20 pages, this means you'll fetch at most 190 extra rows, which
241+doesn't sound like a big deal.
242+
243+For example, if the page size is 10, the fetch size is 50, and the user
244+asks for page 12 (rows 110 to 119):
245+
246+* execute the statement a first time (the result set contains rows 0 to
247+ 49, but you're not going to use them, only the paging state);
248+* execute the statement a second time with the paging state from the
249+ first query;
250+* execute the statement a third time with the paging state from the
251+ second query. The result set now contains rows 100 to 149;
252+* skip the first 10 rows of the iterator. Read the next 10 rows and
253+ discard the remaining ones.
254+
255+You'll want to experiment with the fetch size to find the best balance:
256+too small means many background queries; too big means bigger messages
257+and too many unneeded rows returned (we picked 50 above for the sake of
258+example, but it's probably too small -- the default is 5000).
259+
260+Again, offset queries are inefficient by nature. Emulating them
261+client-side is a compromise when you think you can get away with the
262+performance hit. We recommend that you:
263+
264+* test your code at scale with the expected query patterns, to make sure
265+ that your assumptions are correct;
266+* set a hard limit on the highest possible page number, to prevent
267+ malicious users from triggering queries that would skip a huge amount
268+ of rows.
added manual/pooling/README.md +290 −0
@@ -0,0 +1,290 @@
1+## Connection pooling
2+
3+### Basics
4+
5+The driver communicates with Cassandra over TCP, using the Cassandra
6+binary protocol. This protocol is asynchronous, which allows each TCP
7+connection to handle multiple simultaneous requests:
8+
9+* when a query gets executed, a *stream id* gets assigned to it. It is a
10+ unique identifier on the current connection;
11+* the driver writes a request containing the stream id and the query on
12+ the connection, and then proceeds without waiting for the response (if
13+ you're using the asynchronous API, this is when the driver will send you
14+ back a [ResultSetFuture][result_set_future]).
15+ Once the request has been written to the
16+ connection, we say that it is *in flight*;
17+* at some point, Cassandra will send back a response on the connection.
18+ This response also contains the stream id, which allows the driver to
19+ trigger a callback that will complete the corresponding query (this is
20+ the point where your `ResultSetFuture` will get completed).
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**.
25+
26+The number of connections per pool is configurable (this will be
27+described in the next section). The number of stream ids depends on the
28+[native protocol version](../native_protocol/):
29+
30+* protocol v2 or below: 128 stream ids per connection.
31+* protocol v3 or above: up to 32768 stream ids per connection.
32+
33+```ditaa
34++-------+1 n+-------+1 n+----+1 n+----------+1 128/32K+-------+
35+|Cluster+-----+Session+-----+Pool+-----+Connection+-----------+Request+
36++-------+ +-------+ +----+ +----------+ +-------+
37+```
38+
39+### Configuring the connection pool
40+
41+Connections pools are configured with a [PoolingOptions][pooling_options] object, which
42+is global to a `Cluster` instance. You can pass that object when
43+building the cluster:
44+
45+```java
46+PoolingOptions poolingOptions = new PoolingOptions();
47+// customize options...
48+
49+Cluster cluster = Cluster.builder()
50+ .withContactPoints("127.0.0.1")
51+ .withPoolingOptions(poolingOptions)
52+ .build();
53+```
54+
55+Most options can also be changed at runtime. If you don't have a
56+reference to the `PoolingOptions` instance, here's how you can get it:
57+
58+```java
59+PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
60+// customize options...
61+```
62+
63+#### Pool size
64+
65+Connection pools have a variable size, which gets adjusted automatically
66+depending on the current load. There will always be at least a *core*
67+number of connections, and at most a *max* number. These values can be
68+configured independently by host *distance* (the distance is determined
69+by your [LoadBalancingPolicy][lbp], and will generally indicate whether a
70+host is in the same datacenter or not).
71+
72+```java
73+poolingOptions
74+ .setCoreConnectionsPerHost(HostDistance.LOCAL, 4)
75+ .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
76+ .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
77+ .setMaxConnectionsPerHost( HostDistance.REMOTE, 4);
78+```
79+
80+For convenience, core and max can be set simultaneously:
81+
82+```java
83+poolingOptions
84+ .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
85+ .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
86+```
87+
88+The default settings are:
89+
90+* protocol v2:
91+ * `LOCAL` hosts: core = 2, max = 8
92+ * `REMOTE` hosts: core = 1, max = 2
93+* protocol v3:
94+ * `LOCAL` hosts: core = max = 1
95+ * `REMOTE` hosts: core = max = 1
96+
97+[PoolingOptions.setNewConnectionThreshold][nct] determines the threshold
98+that triggers the creation of a new connection when the pool is not at
99+its maximum capacity. In general, you shouldn't need to change its
100+default value.
101+
102+#### Dynamic resizing
103+
104+If core != max, the pool will resize automatically to adjust to the
105+current activity on the host.
106+
107+When activity goes up and there are *n* connections with n < max, the driver
108+will add a connection when the number of concurrent requests is more than
109+(n - 1) * 128 + [PoolingOptions.setNewConnectionThreshold][nct]
110+(in layman's terms, when all but the last connection are full and the last
111+connection is above the threshold).
112+
113+When activity goes down, the driver will "trash" connections if the maximum
114+number of requests in a 10 second time period can be satisfied by less than
115+the number of connections opened. Trashed connections are kept open but do
116+not accept new requests. After a given timeout (defined by
117+[PoolingOptions.setIdleTimeoutSeconds][sits]), trashed connections are closed
118+and removed. If during that idle period activity increases again, those
119+connections will be resurrected back into the active pool and reused. The
120+main intent of that is to not constantly recreate connections if activity
121+changes quickly over an interval.
122+
123+#### Simultaneous requests per connection
124+
125+[PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to
126+throttle the number of concurrent requests per connection.
127+
128+With protocol v2, there is no reason to throttle. It is set to 128 (the
129+max) and you should not change it.
130+
131+With protocol v3, it is set to 1024 for `LOCAL` hosts, and 256 for
132+`REMOTE` hosts. These low defaults were chosen so that the default
133+configuration for protocol v2 and v3 allow the same total number of
134+simultaneous requests (to avoid bad surprises when clients migrate from
135+v2 to v3). You can raise this threshold, or even set it to the max:
136+
137+```java
138+poolingOptions
139+ .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768)
140+ .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000);
141+```
142+
143+Just keep in mind that high values will give clients more bandwidth and
144+therefore put more pressure on your cluster. This might require some
145+tuning, especially if you have many clients.
146+
147+#### Heartbeat
148+
149+If connections stay idle for too long, they might be dropped by
150+intermediate network devices (routers, firewalls...). Normally, TCP
151+keepalive should take care of this; but tweaking low-level keepalive
152+settings might be impractical in some environments.
153+
154+The driver provides application-side keepalive in the form of a
155+connection heartbeat: when a connection has been idle for a given amount
156+of time, the driver will simulate activity by writing a dummy request to
157+it.
158+
159+This feature is enabled by default. The default heartbeat interval is 30
160+seconds, it can be customized with the following method:
161+
162+```java
163+poolingOptions.setHeartbeatIntervalSeconds(60);
164+```
165+
166+If it gets changed at runtime, only connections created after that will
167+use the new interval. Most users will want to do this at startup.
168+
169+The heartbeat interval should be set higher than
170+[SocketOptions.readTimeoutMillis][rtm]:
171+the read timeout is the maximum time that the driver waits for a regular
172+query to complete, therefore the connection should not be considered
173+idle before it has elapsed.
174+
175+To disable heartbeat, set the interval to 0.
176+
177+Implementation note: the dummy request sent by heartbeat is an
178+[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278)
179+message.
180+
181+
182+#### Acquisition timeout
183+
184+When the driver tries to send a request to a host, it will first try to
185+acquire a connection from this host's pool. If the pool is busy (i.e.
186+all connections are already handling their maximum number of in flight
187+requests), the client thread will block for a while, until a connection
188+becomes available (note that this will block even if you're using the
189+asynchronous API, like [Session.executeAsync][exec_async]).
190+
191+The time that the driver blocks is controlled by
192+[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection
193+available after this timeout, the driver will try the next host.
194+
195+For some applications, blocking is not acceptable, and it is preferable
196+to fail fast if the request cannot be fulfilled. If that's your case,
197+set the pool timeout to 0. If all hosts are busy, you will get a
198+[NoHostAvailableException][nhae] (if you look at the exception's details, you
199+will see a `java.util.concurrent.TimeoutException` for each host).
200+
201+
202+### Monitoring and tuning the pool
203+
204+The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's
205+a simple example that will print the number of open connections, active
206+requests, and maximum capacity for each host, every 5 seconds:
207+
208+```java
209+final LoadBalancingPolicy loadBalancingPolicy =
210+ cluster.getConfiguration().getPolicies().getLoadBalancingPolicy();
211+final PoolingOptions poolingOptions =
212+cluster.getConfiguration().getPoolingOptions();
213+
214+ScheduledExecutorService scheduled =
215+Executors.newScheduledThreadPool(1);
216+scheduled.scheduleAtFixedRate(new Runnable() {
217+ @Override
218+ public void run() {
219+ Session.State state = session.getState();
220+ for (Host host : state.getConnectedHosts()) {
221+ HostDistance distance = loadBalancingPolicy.distance(host);
222+ int connections = state.getOpenConnections(host);
223+ int inFlightQueries = state.getInFlightQueries(host);
224+ System.out.printf("%s connections=%d, current load=%d, max
225+load=%d%n",
226+ host, connections, inFlightQueries,
227+ connections *
228+poolingOptions.getMaxRequestsPerConnection(distance));
229+ }
230+ }
231+}, 5, 5, TimeUnit.SECONDS);
232+```
233+
234+In real life, you'll probably want something more sophisticated, like
235+exposing a JMX MBean or sending the data to your favorite monitoring
236+tool.
237+
238+If you find that the current load stays close or equal to the maximum
239+load at all time, it's a sign that your connection pools are saturated
240+and you should raise the max connections per host, or max requests per
241+connection (protocol v3).
242+
243+If you're using protocol v2 and the load is often less than core * 128,
244+your pools are underused and you could get away with less core
245+connections.
246+
247+#### Tuning protocol v3 for very high throughputs
248+
249+As mentioned above, the default pool size for protocol v3 is core = max
250+= 1. This means all requests to a given node will share a single
251+connection, and therefore a single Netty I/O thread.
252+
253+There is a corner case where this I/O thread can max out its CPU core
254+and become a bottleneck in the driver; in our benchmarks, this happened
255+with a single-node cluster and a high throughput (approximately 80K
256+requests / second).
257+
258+It's unlikely that you'll run into this issue: in most real-world
259+deployments, the driver connects to more than one node, so the load will
260+spread across more I/O threads. However if you suspect that you
261+experience the issue, here's what to look out for:
262+
263+* the driver throughput plateaus but the process does not appear to
264+ max out any system resource (in particular, overall CPU usage is well
265+ below 100%);
266+* one of the driver's I/O threads maxes out its CPU core. You can see
267+ that with a profiler, or OS-level tools like `pidstat -tu` on Linux.
268+ I/O threads are called `<cluster_name>-nio-worker-<n>`, unless you're
269+ injecting your own `EventLoopGroup` with `NettyOptions`.
270+
271+The solution is to add more connections per node. To ensure that
272+additional connections get created before you run into the bottleneck,
273+either:
274+
275+* set core = max;
276+* keep core = 1, but adjust [maxRequestsPerConnection][mrpc] and
277+ [newConnectionThreshold][nct] so that enough connections are added by
278+ the time you reach the bottleneck.
279+
280+[result_set_future]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html
281+[pooling_options]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html
282+[lbp]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
283+[nct]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
284+[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection(com.datastax.driver.core.HostDistance,%20int)
285+[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds(int)
286+[rtm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis()
287+[exec_async]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement)
288+[ptm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
289+[nhae]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
290+[get_state]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState()
added manual/query_timestamps/README.md +77 −0
@@ -0,0 +1,77 @@
1+## Query timestamps
2+
3+In Cassandra, each mutation has a microsecond-precision timestamp, which
4+is used to order operations relative to each other.
5+
6+There are various ways to assign it:
7+
8+### CQL `USING TIMESTAMP`
9+
10+You can explicitly provide the timestamp in your CQL query:
11+
12+```java
13+session.execute("INSERT INTO my_table(c1, c2) values (1, 1) " +
14+ "USING TIMESTAMP 1432815430948040");
15+```
16+
17+### Client-side generation
18+
19+This is enabled by default if you're using the driver 3.0 and a version
20+of Cassandra that supports [native protocol](../native_protocol) v3 or
21+above.
22+
23+A client timestamp will be sent by each query. It is generated by a
24+[TimestampGenerator][tsg]. The default implementation is
25+[AtomicMonotonicTimestampGenerator][amtsg].
26+
27+You can specify another generator at initialization:
28+
29+```java
30+Cluster.builder().addContactPoint("127.0.0.1")
31+ .withTimestampGenerator(new MyCustomTimestampGenerator())
32+ .build();
33+```
34+
35+In addition, you can also override the default timestamp on a
36+per-statement basis:
37+
38+```java
39+Statement statement = new SimpleStatement(
40+ "UPDATE users SET email = 'x@y.com' where id = 1");
41+statement.setDefaultTimestamp(1234567890);
42+session.execute(statement);
43+```
44+
45+[tsg]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TimestampGenerator.html
46+[amtsg]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.html
47+
48+
49+### Server-side generation
50+
51+This is the "legacy" behavior if you're connected to a Cassandra version
52+that only supports protocol v2 or below. The server will assign a
53+timestamp based on the time it receives the query.
54+
55+This can be a problem when the order of the writes matter: with unlucky
56+timing (different coordinators, network latency, etc.), two successive
57+requests from the same client might be processed in a different order
58+server-side, and end up with out-of-order timestamps. If protocol v3 is
59+not an option, the only workaround is to add `USING TIMESTAMP` in your
60+queries.
61+
62+
63+### Summary
64+
65+As shown in the previous sections, there are multiple ways to provide a
66+timestamp, some of which overlap. The order of precedence is the
67+following:
68+
69+1. if there is a `USING TIMESTAMP` clause in the CQL string, use that
70+ over anything else;
71+2. otherwise, if a default timestamp was set on the statement and is
72+ different from `Long.MIN_VALUE`, use it;
73+3. otherwise, if a generator is specified, invoke it and use its result
74+ if it is different from `Long.MIN_VALUE`;
75+4. otherwise, let the server assign the timestamp.
76+
77+Steps 2 and 3 only apply if native protocol v3 or above is in use.
added manual/shaded_jar/README.md +55 −0
@@ -0,0 +1,55 @@
1+## Using the shaded JAR
2+
3+The default driver JAR depends on [Netty](http://netty.io/), which is
4+used internally for networking.
5+
6+This explicit dependency can be a problem if your application already
7+uses another Netty version. To avoid conflicts, we provide a "shaded"
8+version of the JAR, which bundles the Netty classes under a different
9+package name:
10+
11+```xml
12+<dependency>
13+ <groupId>com.datastax.cassandra</groupId>
14+ <artifactId>cassandra-driver-core</artifactId>
15+ <version>3.0.0-rc1</version>
16+ <classifier>shaded</classifier>
17+ <!-- Because the shaded JAR uses the original POM, you still need
18+ to exclude this dependency explicitly: -->
19+ <exclusions>
20+ <exclusion>
21+ <groupId>io.netty</groupId>
22+ <artifactId>*</artifactId>
23+ </exclusion>
24+ </exclusions>
25+</dependency>
26+```
27+
28+If you also use the mapper, you need to remove its dependency to the
29+non-shaded JAR:
30+
31+```xml
32+<dependency>
33+ <groupId>com.datastax.cassandra</groupId>
34+ <artifactId>cassandra-driver-core</artifactId>
35+ <version>3.0.0-rc1</version>
36+ <classifier>shaded</classifier>
37+ <exclusions>
38+ <exclusion>
39+ <groupId>io.netty</groupId>
40+ <artifactId>*</artifactId>
41+ </exclusion>
42+ </exclusions>
43+</dependency>
44+<dependency>
45+ <groupId>com.datastax.cassandra</groupId>
46+ <artifactId>cassandra-driver-mapping</artifactId>
47+ <version>3.0.0-rc1</version>
48+ <exclusions>
49+ <exclusion>
50+ <groupId>com.datastax.cassandra</groupId>
51+ <artifactId>cassandra-driver-core</artifactId>
52+ </exclusion>
53+ </exclusions>
54+</dependency>
55+```
added manual/speculative_execution/README.md +343 −0
@@ -0,0 +1,343 @@
1+## Speculative query execution
2+
3+Sometimes a Cassandra node might be experiencing difficulties (ex: long
4+GC pause) and take longer than usual to reply. Queries sent to that node
5+will experience bad latency.
6+
7+One thing we can do to improve that is pre-emptively start a second
8+execution of the query against another node, before the first node has
9+replied or errored out. If that second node replies faster, we can send
10+the response back to the client (we also cancel the first query):
11+
12+```ditaa
13+client driver exec1 exec2
14+--+----------------+--------------+------+---
15+ | execute(query) |
16+ |--------------->|
17+ | | query host1
18+ | |------------->|
19+ | | |
20+ | | |
21+ | | query host2
22+ | |-------------------->|
23+ | | | |
24+ | | | |
25+ | | host2 replies |
26+ | |<--------------------|
27+ | complete | |
28+ |<---------------| |
29+ | | cancel |
30+ | |------------->|
31+```
32+
33+Or the first node could reply just after the second execution was
34+started. In this case, we cancel the second execution. In other words,
35+whichever node replies faster "wins" and completes the client query:
36+
37+```ditaa
38+client driver exec1 exec2
39+--+----------------+--------------+------+---
40+ | execute(query) |
41+ |--------------->|
42+ | | query host1
43+ | |------------->|
44+ | | |
45+ | | |
46+ | | query host2
47+ | |-------------------->|
48+ | | | |
49+ | | | |
50+ | | host1 replies| |
51+ | |<-------------| |
52+ | complete | |
53+ |<---------------| |
54+ | | cancel |
55+ | |-------------------->|
56+```
57+
58+Speculative executions are **disabled** by default. The following
59+sections cover the practical details and how to enable them.
60+
61+### Query idempotence
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
67+there is no way to guarantee that only one node will apply the mutation.
68+
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+### Enabling speculative executions
115+
116+Speculative executions are controlled by an instance of
117+[SpeculativeExecutionPolicy][sep] provided when initializing the
118+`Cluster`. This policy defines the threshold after which a new
119+speculative execution will be triggered.
120+
121+[sep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html
122+
123+Two implementations are provided with the driver:
124+
125+#### [ConstantSpeculativeExecutionPolicy][csep]
126+
127+This simple policy uses a constant threshold:
128+
129+```java
130+Cluster cluster = Cluster.builder()
131+ .addContactPoint("127.0.0.1")
132+ .withSpeculativeExecutionPolicy(
133+ new ConstantSpeculativeExecutionPolicy(
134+ 500, // delay before a new execution is launched
135+ 2 // maximum number of executions
136+ ))
137+ .build();
138+```
139+
140+Given the above configuration, an idempotent query would be handled this
141+way:
142+
143+* start the initial execution at t0;
144+* if no response has been received at t0 + 500 milliseconds, start a
145+ speculative execution on another node;
146+* if no response has been received at t0 + 1000 milliseconds, start
147+ another speculative execution on a third node.
148+
149+[csep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.html
150+
151+#### [PercentileSpeculativeExecutionPolicy][psep]
152+
153+This policy sets the threshold at a given latency percentile for the
154+current host, based on recent statistics.
155+
156+**As of 2.1.6, this class is provided as a beta preview: it hasn't been
157+extensively tested yet, and the API is still subject to change.**
158+
159+First and foremost, make sure that the [HdrHistogram][hdr] library (used
160+under the hood to collect latencies) is in your classpath. It's defined
161+as an optional dependency in the driver's POM, so you'll need to
162+explicitly depend on it:
163+
164+```xml
165+<dependency>
166+ <groupId>org.hdrhistogram</groupId>
167+ <artifactId>HdrHistogram</artifactId>
168+ <version>2.1.4</version>
169+</dependency>
170+```
171+
172+Then create an instance of [PerHostPercentileTracker][phpt] that will collect
173+latency statistics for your `Cluster`:
174+
175+```java
176+// There are more options than shown here, please refer to the API docs
177+// for more information
178+PerHostPercentileTracker tracker = PerHostPercentileTracker
179+ .builderWithHighestTrackableLatencyMillis(15000)
180+ .build();
181+```
182+
183+Create an instance of the policy with the tracker, and pass it to your
184+cluster:
185+
186+```java
187+PercentileSpeculativeExecutionPolicy policy =
188+ new PercentileSpeculativeExecutionPolicy(
189+ tracker,
190+ 99.0, // percentile
191+ 2); // maximum number of executions
192+
193+Cluster cluster = Cluster.builder()
194+ .addContactPoint("127.0.0.1")
195+ .withSpeculativeExecutionPolicy(policy)
196+ .build();
197+```
198+
199+Finally, don't forget to register your tracker with the cluster (the
200+policy does not do this itself):
201+
202+```java
203+cluster.register(tracker);
204+```
205+
206+Note that `PerHostPercentileTracker` may also be used with a slow query
207+logger (see the [Logging](../logging/) section). In that case, you would
208+create a single tracker object and share it with both components.
209+
210+[psep]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html
211+[hdr]: http://hdrhistogram.github.io/HdrHistogram/
212+[phpt]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PerHostPercentileTracker.html
213+
214+#### Using your own
215+
216+As with all policies, you are free to provide your own by implementing
217+`SpeculativeExecutionPolicy`.
218+
219+### How speculative executions affect retries
220+
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
230+parallel execution will trigger retries independently:
231+
232+```ditaa
233+client driver exec1 exec2
234+--+----------------+--------------+------+---
235+ | execute(query) |
236+ |--------------->|
237+ | | query host1
238+ | |------------->|
239+ | | |
240+ | | unavailable |
241+ | |<-------------|
242+ | |
243+ | |retry at lower CL
244+ | |------------->|
245+ | | |
246+ | | query host2
247+ | |-------------------->|
248+ | | | |
249+ | | server error |
250+ | |<--------------------|
251+ | | |
252+ | | retry on host3
253+ | |-------------------->|
254+ | | | |
255+ | | host1 replies| |
256+ | |<-------------| |
257+ | complete | |
258+ |<---------------| |
259+ | | cancel |
260+ | |-------------------->|
261+```
262+
263+The only impact is that all executions of the same query always share
264+the same query plan, so each host will be used by at most one execution.
265+
266+[retry_policy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html
267+
268+### Tuning and practical details
269+
270+The goal of speculative executions is to improve overall latency (the
271+time between `execute(query)` and `complete` in the diagrams above) at
272+high percentiles. On the flipside, they cause the driver to send more
273+individual requests, so throughput will not necessarily improve.
274+
275+You can monitor how many speculative executions were triggered with the
276+`speculative-executions` metric (exposed in the Java API as
277+[cluster.getMetrics().getErrors().getSpeculativeExecutions()][se_metric]).
278+It should only be a few percents of the total number of requests
279+([cluster.getMetrics().getRequestsTimer().getCount()][request_metric]).
280+
281+[se_metric]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions()
282+[request_metric]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metrics.html#getRequestsTimer()
283+
284+#### Stream id exhaustion
285+
286+One side-effect of speculative executions is that many requests are
287+cancelled, which can lead to a phenomenon called *stream id exhaustion*:
288+each TCP connection can handle multiple simultaneous requests,
289+identified by a unique number called *stream id*. When a request gets
290+cancelled, we can't reuse its stream id immediately because we might
291+still receive a response from the server later. If this happens often,
292+the number of available stream ids diminishes over time, and when it
293+goes below a given threshold we close the connection and create a new
294+one. If requests are often cancelled, so will see connections being
295+recycled at a high rate.
296+
297+One way to detect this is to monitor open connections per host
298+([Session.getState().getOpenConnections(host)][session_state]) against
299+TCP connections at the OS level. If open connections stay constant but
300+you see many TCP connections in closing states, you might be running
301+into this issue. Try raising the speculative execution threshold.
302+
303+This problem is more likely to happen with version 2 of the native
304+protocol, because each TCP connection only has 128 stream ids. With
305+version 3 (driver 2.1.2 or above with Cassandra 2.1 or above), there are
306+32K stream ids per connection, so higher cancellation rates can be
307+sustained. If you're unsure of which native protocol version you're
308+using, you can check with
309+[cluster.getConfiguration().getProtocolOptions().getProtocolVersion()][protocol_version].
310+
311+[session_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.State.html
312+[protocol_version]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion()
313+
314+#### Request ordering and client timestamps
315+
316+Another issue that might arise is that you get unintuitive results
317+because of request ordering. Suppose you run the following query with
318+speculative executions enabled:
319+
320+ insert into my_table (k, v) values (1, 1);
321+
322+The first execution is a bit too slow, so a second execution gets
323+triggered. Finally, the first execution completes, so the client code
324+gets back an acknowledgement, and the second execution is cancelled.
325+However, cancelling only means that the driver stops waiting for the
326+server's response, the request could still be "on the wire"; let's
327+assume that this is the case.
328+
329+Now you run the following query, which completes successfully:
330+
331+ delete from my_table where k = 1;
332+
333+But now the second execution of the first query finally reaches its
334+target node, which applies the mutation. The row that you've just
335+deleted is back!
336+
337+The workaround is to use a timestamp with your queries:
338+
339+ insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000;
340+
341+If you're using native protocol v3, you can also enable [client-side
342+timestamps](../query_timestamps/#client-side-generation) to have this done
343+automatically.
added manual/ssl/README.md +184 −0
@@ -0,0 +1,184 @@
1+## SSL
2+
3+You can secure traffic between the driver and Cassandra with SSL. There
4+are two aspects to that:
5+
6+* **client-to-node encryption**, where the traffic is encrypted, and the
7+ client verifies the identity of the Cassandra nodes it connects to;
8+* optionally, **client certificate authentication**, where Cassandra
9+ nodes also verify the identity of the client.
10+
11+This section describes the driver-side configuration; it assumes that
12+you've already configured SSL in Cassandra:
13+
14+* [the Cassandra documentation](http://docs.datastax.com/en/cassandra/2.0/cassandra/security/secureSSLClientToNode_t.html)
15+ covers a basic approach with self-signed certificates, which is fine
16+ for development and tests.
17+* [this blog post](http://thelastpickle.com/blog/2015/09/30/hardening-cassandra-step-by-step-part-1-server-to-server.html)
18+ details a more advanced solution based on a Certificate Authority
19+ (CA).
20+
21+### Preparing the certificates
22+
23+#### Client truststore
24+
25+This is required for client-to-node encryption.
26+
27+If you're using self-signed certificates, you need to export the public
28+part of each node's certificate from that node's keystore:
29+
30+```
31+keytool -export -alias cassandra -file cassandranode0.cer -keystore .keystore
32+```
33+
34+Then add all public certificates to the client truststore:
35+
36+```
37+keytool -import -v -trustcacerts -alias <cassandra_node0> -file cassandranode0.cer -keystore client.truststore
38+keytool -import -v -trustcacerts -alias <cassandra_node1> -file cassandranode1.cer -keystore client.truststore
39+...
40+```
41+
42+If you're using a Certificate Authority, the client truststore only
43+needs to contain the CA's certificate:
44+
45+```
46+keytool -import -v -trustcacerts -alias CARoot -file ca.cer -keystore client.truststore
47+```
48+
49+#### Client keystore
50+
51+If you also intend to use client certificate authentication, generate
52+the public and private key pair for the client:
53+
54+```
55+keytool -genkey -keyalg RSA -alias client -keystore client.keystore
56+```
57+
58+If you're using self-signed certificates, extract the public part of the
59+client certificate, and import it in the truststore of each Cassandra
60+node:
61+
62+```
63+keytool -export -alias client -file client.cer -keystore client.keystore
64+keytool -import -v -trustcacerts -alias client -file client.cer -keystore server.truststore
65+```
66+
67+If you're using a CA, sign the client certificate with it (see the blog
68+post linked at the top of this page). Then the nodes' truststores only
69+need to contain the CA's certificate (which should already be the case
70+if you've followed the steps for inter-node encryption).
71+
72+### Driver configuration
73+
74+The base class to configure SSL is [SSLOptions]. It's very generic, but
75+you don't necessarily need to deal with it directly: the default
76+instance, or the provided subclasses, might be enough for your needs.
77+
78+#### JSSE, Property-based
79+
80+`withSSL()` gives you a basic JSSE configuration:
81+
82+```java
83+Cluster cluster = Cluster.builder()
84+ .addContactPoint("127.0.0.1")
85+ .withSSL()
86+ .build();
87+```
88+
89+You can then use
90+[JSSE system properties](http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization)
91+for specific details, like keystore locations and passwords:
92+
93+```
94+-Djavax.net.ssl.trustStore=/path/to/client.truststore
95+-Djavax.net.ssl.trustStorePassword=password123
96+# If you're using client authentication:
97+-Djavax.net.ssl.keyStore=/path/to/client.keystore
98+-Djavax.net.ssl.keyStorePassword=password123
99+```
100+
101+#### JSSE, programmatic
102+
103+If you need more control than what system properties allow, you can
104+configure SSL programmatically with [JdkSSLOptions]:
105+
106+```java
107+SSLContext sslContext = ... // create and configure SSL context
108+
109+JdkSSLOptions sslOptions = JdkSSLOptions.builder()
110+ .withSSLContext(context)
111+ .build();
112+
113+Cluster cluster = Cluster.builder()
114+ .addContactPoint("127.0.0.1")
115+ .withSSL(sslOptions)
116+ .build();
117+```
118+
119+Note that you can also extend the class and override
120+[newSSLEngine(SocketChannel)][newSSLEngine] if you need specific
121+configuration on the `SSLEngine` (for example hostname verification).
122+
123+[newSSLEngine]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/JdkSSLOptions.html#newSSLEngine(io.netty.channel.socket.SocketChannel)
124+
125+#### Netty
126+
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.
130+
131+##### Converting your client certificates for OpenSSL
132+
133+OpenSSL doesn't use keystores, so if you use client authentication and
134+generated your certificates with keytool, you need to convert them.
135+
136+* use this command to extract the public certificate chain:
137+
138+ ```
139+ keytool -export -keystore client.keystore -alias client -rfc -file client.crt
140+ ```
141+* follow
142+ [this tutorial](http://www.herongyang.com/crypto/Migrating_Keys_keytool_to_OpenSSL_3.html)
143+ to extract your client's private key from `client.keystore` to a text
144+ file `client.key` in PEM format.
145+
146+##### Updating your dependencies
147+
148+Netty-tcnative provides the native integration with OpenSSL. Follow
149+[these instructions](http://netty.io/wiki/forked-tomcat-native.html) to
150+add it to your dependencies.
151+
152+Note that using netty-tcnative requires JDK 1.7 or above.
153+
154+##### Configuring the context
155+
156+Use the following Java code to configure OpenSSL with your certificates:
157+
158+```java
159+KeyStore ks = KeyStore.getInstance("JKS");
160+// make sure you close this stream properly (not shown here for brevity)
161+InputStream trustStore = new FileInputStream("client.truststore");
162+ks.load(trustStore, "password123".toCharArray());
163+TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
164+tmf.init(ks);
165+
166+SslContextBuilder builder = SslContextBuilder
167+ .forClient()
168+ .sslProvider(SslProvider.OPENSSL)
169+ .trustManager(tmf);
170+ // only if you use client authentication
171+ .keyManager(new File("client.crt"), new File("client.key"));
172+
173+SSLOptions sslOptions = new NettySSLOptions(builder.build());
174+
175+Cluster cluster = Cluster.builder()
176+ .addContactPoint("127.0.0.1")
177+ .withSSL(sslOptions)
178+ .build();
179+```
180+
181+[SSLOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SSLOptions.html
182+[JdkSSLOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/JdkSSLOptions.html
183+[NettySSLOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/NettySSLOptions.html
184+[NettyOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/NettyOptions.html
added manual/statements/README.md +54 −0
@@ -0,0 +1,54 @@
1+## Statements
2+
3+To execute a query, you create a [Statement] instance and pass it to
4+`Session#execute()`. The driver provides various implementations:
5+
6+* [SimpleStatement]: a simple implementation built directly from a
7+ character string. Typically used for queries that are executed only
8+ once or a few times.
9+* [BoundStatement]: obtained by binding values to a [prepared
10+ statement](prepared/). Typically used for queries that are executed
11+ often, with different values.
12+* [BuiltStatement]: a statement built with the [QueryBuilder] DSL. It
13+ can be executed directly like a simple statement, or prepared.
14+* [BatchStatement]: a statement that groups multiple statements to be
15+ executed as a batch.
16+
17+`Session` also has a shortcut to build and execute a simple statement in
18+a single call:
19+
20+```java
21+session.execute("select release_version from system.local");
22+
23+// Is equivalent to:
24+Statement s = new SimpleStatement("select release_version from system.local");
25+session.execute(s);
26+```
27+
28+### Customizing execution
29+
30+Before executing a statement, you might want to customize certain
31+aspects of its execution. `Statement` provides a number of methods for
32+this, for example:
33+
34+```java
35+Statement s = new SimpleStatement("select release_version from system.local");
36+s.enableTracing();
37+session.execute(s);
38+```
39+
40+If you use custom policies ([RetryPolicy], [LoadBalancingPolicy],
41+[SpeculativeExecutionPolicy]...), you might also want to have custom
42+properties that influence statement execution. To achieve this, you can
43+wrap your statements in a custom [StatementWrapper] implementation.
44+
45+[Statement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Statement.html
46+[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SimpleStatement.html
47+[BoundStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BoundStatement.html
48+[BatchStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html
49+[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/QueryBuilder.html
50+[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/BuiltStatement.html
51+[StatementWrapper]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/StatementWrapper.html
52+[RetryPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/RetryPolicy.html
53+[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html
54+[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html
added manual/statements/prepared/README.md +188 −0
@@ -0,0 +1,188 @@
1+## Prepared statements
2+
3+When Cassandra executes a query, the first thing it does is parse the
4+query string to an internal representation. If the same query is used
5+often, you can use a prepared statement, which allows Cassandra to cache
6+that representation, and save time and resources for subsequent
7+executions. Prepared statements are typically parameterized, using
8+different values for each execution:
9+
10+```java
11+PreparedStatement prepared = session.prepare(
12+ "insert into product (sku, description) values (?, ?)");
13+
14+BoundStatement bound;
15+
16+bound = prepared.bind("234827", "Mouse");
17+session.execute(bound);
18+
19+bound = prepared.bind("987274", "Keyboard");
20+session.execute(bound);
21+```
22+
23+Statements should be be prepared only once. If you call `prepare`
24+multiple times with the same query string, the driver will log a
25+warning. So your application should cache the `PreparedStatement` object
26+once it's been created (this can be as simple as storing it as a field
27+in a DAO).
28+
29+### Parameters and binding
30+
31+Parameters can be either anonymous or named (named parameters are only
32+available with [native protocol](../../native_protocol) v2 or above):
33+
34+```java
35+ps1 = session.prepare("insert into product (sku, description) values (?, ?)");
36+ps2 = session.prepare("insert into product (sku, description) values (:s, :d)");
37+```
38+
39+To turn the statement into its executable form, you need to *bind* it
40+and provide values for the parameters. As shown previously, there is a
41+shorthand form to do it all in one call:
42+
43+```java
44+BoundStatement bound = ps1.bind("324378", "LCD screen");
45+```
46+
47+You can also bind first, then use setters, which is slightly more
48+explicit:
49+
50+```java
51+// Positional setters:
52+BoundStatement bound = ps1.bind()
53+ .setString(0, "324378")
54+ .setString(1, "LCD screen");
55+
56+// Named setters:
57+BoundStatement bound = ps2.bind()
58+ .setString("s", "324378")
59+ .setString("d", "LCD screen");
60+```
61+
62+You can use named setters even if the query uses anonymous parameters;
63+Cassandra will name the parameters after the column they apply to:
64+
65+```java
66+BoundStatement bound = ps1.bind()
67+ .setString("sku", "324378")
68+ .setString("description", "LCD screen");
69+```
70+
71+This can be ambiguous if the query uses the same column multiple times,
72+for example: `select * from sales where sku = ? and date > ? and date <
73+?`. In these situations, use positional setters or named parameters.
74+
75+For native protocol V3 or below, all variables must be bound. With native
76+protocol V4 or above, variables can be left unset, in which case they
77+will be ignored server side (no tombstones will be generated). If you're
78+reusing a bound statement you can use the `unset` method to unset variables
79+that were previously set:
80+
81+```java
82+BoundStatement bound = ps1.bind()
83+ .setString("sku", "324378")
84+ .setString("description", "LCD screen")
85+
86+// Using the unset method to unset previously set value.
87+// Positional setter:
88+bound.unset("description");
89+
90+// Named setter:
91+bound.unset(1);
92+```
93+
94+A bound statement also has getters to retrieve the values. Note that
95+this has a small performance overhead since values are stored in their
96+serialized form.
97+
98+### How the driver handles prepared statements
99+
100+When the driver prepares a statement, it sends the query string to
101+Cassandra, which caches the statement and returns an identifier. Later,
102+when the driver needs to execute the statement, it just sends the
103+identifier and parameter values. Note that the identifier is
104+deterministic, so it will always be the same for all nodes (it's a
105+actually a hash of the query string).
106+
107+Prepared statements are not replicated across the cluster. It is the
108+driver's responsibility to ensure that each node's cache is up to
109+date. It uses a number of strategies to achieve this:
110+
111+1. When a statement is initially prepared, it is first sent to a single
112+ node in the cluster (this prevents from hitting all nodes in case
113+ the query string is wrong). Once that node replies successfully, the
114+ driver re-prepares on all remaining nodes:
115+
116+ ```ditaa
117+ client driver node1 node2 node3
118+ --+------------------------+----------------+--------------+------+---
119+ | | | | |
120+ | session.prepare(query) | | | |
121+ |----------------------->| | | |
122+ | | PREPARE(query) | | |
123+ | |--------------->| | |
124+ | | | | |
125+ | | PREPARED(id) | | |
126+ | |<---------------| | |
127+ | | | | |
128+ | | | | |
129+ | | PREPARE(query) | |
130+ | |------------------------------>| |
131+ | | | | |
132+ | | PREPARE(query) | |
133+ | |------------------------------------->|
134+ | | | | |
135+ |<-----------------------| | | |
136+ ```
137+
138+2. if a node crashes, it loses all of its prepared statements. So the
139+ driver keeps a client-side cache; anytime a node is marked back up,
140+ the driver re-prepares all statements on it;
141+
142+3. finally, if the driver tries to execute a statement and finds out
143+ that the coordinator doesn't know about it, it will re-prepare the
144+ statement on the fly (this is transparent for the client, but will cost
145+ two extra roundtrips):
146+
147+ ```ditaa
148+ client driver node1
149+ --+-------------------------------+------------------------------+--
150+ | | |
151+ |session.execute(boundStatement)| |
152+ +------------------------------>| |
153+ | | EXECUTE(id, values) |
154+ | |----------------------------->|
155+ | | |
156+ | | UNPREPARED |
157+ | |<-----------------------------|
158+ | | |
159+ | | |
160+ | | PREPARE(query) |
161+ | |----------------------------->|
162+ | | |
163+ | | PREPARED(id) |
164+ | |<-----------------------------|
165+ | | |
166+ | | |
167+ | | EXECUTE(id, values) |
168+ | |----------------------------->|
169+ | | |
170+ | | ROWS |
171+ | |<-----------------------------|
172+ | | |
173+ |<------------------------------| |
174+ ```
175+
176+You can customize these strategies through `QueryOptions`:
177+
178+* [setPrepareOnAllHosts] controls whether statements are initially
179+ re-prepared on other hosts (step 1 above);
180+* [setReprepareOnUp] controls whether statements are re-prepared on a
181+ node that comes back up (step 2 above).
182+
183+Changing the driver's defaults should be done with care and only in
184+specific situations; read each method's Javadoc for detailed
185+explanations.
186+
187+[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts(boolean)
188+[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp(boolean)
modified upgrade_guide/README.md +7 −7
@@ -12,7 +12,7 @@
1212 We've also seized the opportunity to remove code that was deprecated in 2.1.
1313
1414 1. The default consistency level in `QueryOptions` is now `LOCAL_ONE`.
15-2. [Custom codecs](../features/custom_codecs/)
15+2. [Custom codecs](../manual/custom_codecs/)
1616 ([JAVA-721](https://datastax-oss.atlassian.net/browse/JAVA-721))
1717 introduce several breaking changes and also modify a few runtime behaviors.
1818
@@ -72,7 +72,7 @@
7272 corresponding method `MappingManager#udtMapper`.
7373
7474 The mapper now uses custom codecs to convert UDTs. See more
75- explanations [here](../features/object_mapper/custom_codecs/#implicit-udt-codecs).
75+ explanations [here](../manual/object_mapper/custom_codecs/#implicit-udt-codecs).
7676
7777 5. All methods that took the protocol version as an `int` or assumed a
7878 default version have been removed (they were already deprecated in
@@ -131,9 +131,9 @@
131131 callback methods (`onUp`, `onDown`, etc.) have been duplicated. This
132132 is unlikely to affect clients.
133133
134-12. [Client-side timestamp generation](../features/query_timestamps/) is
134+12. [Client-side timestamp generation](../manual/query_timestamps/) is
135135 now the default (provided that [native
136- protocol](../features/native_protocol) v3 or higher is in use). The
136+ protocol](../manual/native_protocol) v3 or higher is in use). The
137137 generator used is `AtomicMonotonicTimestampGenerator`.
138138
139139 13. If a DNS name resolves to multiple A-records,
@@ -142,7 +142,7 @@
142142 maintaining contact points in DNS configuration, and having a single,
143143 static contact point in your Java code.
144144
145-14. The following methods were added for [Custom payloads](../features/custom_payloads):
145+14. The following methods were added for [Custom payloads](../manual/custom_payloads):
146146 * in `PreparedStatement`: `getIncomingPayload()`,
147147 `getOutgoingPayload()` and
148148 `setOutgoingPayload(Map<String,ByteBuffer>)`
@@ -276,7 +276,7 @@
276276 ones.
277277
278278 Also, note that the connection pool for protocol v3 can now be configured to
279- use multiple connections. See [this page](../features/pooling) for more
279+ use multiple connections. See [this page](../manual/pooling) for more
280280 information.
281281
282282 3. `MappingManager(Session)` will now force the initialization of the `Session`
@@ -445,7 +445,7 @@
445445 default like in previous versions.
446446
447447 3. Netty is not shaded anymore in the default Maven artifact. However we publish a
448- [shaded artifact](../features/shaded_jar/) under a different classifier.
448+ [shaded artifact](../manual/shaded_jar/) under a different classifier.
449449
450450 4. The internal initialization sequence of the Cluster object has been slightly changed:
451451 some fields that were previously initialized in the constructor are now set when