Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 3.0
Changesetec7bd869f099277fa600201fd768050b52bf8397c11e77f11ec31567cdcb8304
Authorolim7t <omichallat+github@gmail.com> · 2016-01-15 18:03 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-01-15 18:37 +01:00
Parents34059ba4d66a, 7e6c21d3caab

Browse the files at this changeset

17 files changed

modified manual/README.md +295 −10
@@ -1,17 +1,302 @@
11 ## Manual
22
3-This part of the documentation is organized into sub-sections covering
4-specific topics.
3+### Quick start
4+
5+Here's a short program that connects to Cassandra and executes a query:
6+
7+```java
8+Cluster cluster = null;
9+try {
10+ cluster = Cluster.builder() // (1)
11+ .addContactPoint("127.0.0.1")
12+ .build();
13+ Session session = cluster.connect(); // (2)
14+
15+ ResultSet rs = session.execute("select release_version from system.local"); // (3)
16+ Row row = rs.one();
17+ System.out.println(row.getString("release_version")); // (4)
18+} finally {
19+ if (cluster != null) cluster.close(); // (5)
20+}
21+```
22+
23+1. the [Cluster] object is the main entry point of the driver. It holds the known state of the actual Cassandra cluster
24+ (notably the [Metadata](metadata/)). This class is thread-safe, you should create a single instance (per target
25+ Cassandra cluster), and share it throughout your application;
26+2. the [Session] is what you use to execute queries. Likewise, it is thread-safe and should be reused;
27+3. we use `execute` to send a query to Cassandra. This returns a [ResultSet], which is essentially a collection of [Row]
28+ objects. On the next line, we extract the first row (which is the only one in this case);
29+4. we extract the value of the first (and only) column from the row;
30+5. finally, we close the cluster after we're done with it. This will also close any session that was created from this
31+ cluster. This step is important because it frees underlying resources (TCP connections, thread pools...). In a real
32+ application, you would typically do this at shutdown (for example, when undeploying your webapp).
33+
34+Note: this example uses the synchronous API. Most methods have [asynchronous](async/) equivalents.
35+
36+
37+### Setting up the driver
38+
39+#### [Cluster]
40+
41+##### Creating an instance
42+
43+The simplest approach is to do it programmatically with [Cluster.Builder], which provides a fluent API:
44+
45+```java
46+Cluster cluster = Cluster.builder()
47+ .withClusterName("myCluster")
48+ .addContactPoint("127.0.0.1")
49+ .build();
50+```
51+
52+Alternatively, you might want to retrieve the settings from an external source (like a properties file or a web
53+service). You'll need to provide an implementation of [Initializer] that loads these settings:
54+
55+```java
56+Initializer myInitializer = ... // your implementation
57+Cluster cluster = Cluster.buildFrom(myInitializer);
58+```
59+
60+##### Creation options
61+
62+The only required option is the list of contact points, i.e. the hosts that the driver will initially contact to
63+discover the cluster topology. You can provide a single contact point, but it is usually a good idea to provide more, so
64+that the driver can fallback if the first one is down.
65+
66+The other aspects that you can configure on the `Cluster` are:
67+
68+* [address translation](address_resolution/);
69+* [authentication](auth/);
70+* [compression](compression/);
71+* [load balancing](load_balancing/);
72+* [metrics](metrics/);
73+* low-level [Netty configuration][NettyOptions];
74+* [query options][QueryOptions];
75+* [reconnections](reconnection/);
76+* [retries](retries/);
77+* [socket options][SocketOptions];
78+* [SSL](ssl/);
79+* [speculative executions](speculative_execution/);
80+* [query timestamps](query_timestamps/).
81+
82+In addition, you can register various types of listeners to be notified of cluster events; see [Host.StateListener],
83+[LatencyTracker], and [SchemaChangeListener].
84+
85+##### Cluster initialization
86+
87+A freshly-built `Cluster` instance does not initialize automatically; that will be triggered by one of the following
88+actions:
89+
90+* an explicit call to `cluster.init()`;
91+* a call to `cluster.getMetadata()`;
92+* creating a session with `cluster.connect()` or one of its variants;
93+* calling `session.init()` on a session that was created with `cluster.newSession()`.
94+
95+The initialization sequence is the following:
96+
97+* initialize internal state (thread pools, utility components, etc.);
98+* try to connect to each of the contact points in sequence. The order is not deterministic (in fact, the driver shuffles
99+ the list to avoid hotspots if a large number of clients share the same contact points). If no contact point replies,
100+ a [NoHostAvailableException] is thrown and the process stops here;
101+* otherwise, the successful contact point is elected as the [control host](control_connection/). The driver negotiates
102+ the [native protocol version](native_protocol/) with it, and queries its system tables to discover the addresses of
103+ the other hosts.
104+
105+Note that, at this stage, only the control connection has been established. Connections to other hosts will only be
106+opened when a session gets created.
107+
108+#### [Session]
109+
110+By default, a session isn't tied to any specific keyspace. You'll need to prefix table names in your queries:
111+
112+```java
113+Session session = cluster.connect();
114+session.execute("select * from myKeyspace.myTable where id = 1");
115+```
116+
117+You can also specify a keyspace name at construction time, it will be used as the default when table names are not
118+qualified:
119+
120+```java
121+Session session = cluster.connect("myKeyspace");
122+session.execute("select * from myTable where id = 1");
123+session.execute("select * from otherKeyspace.otherTable where id = 1");
124+```
125+
126+You might be tempted to open a separate session for each keyspace used in your application; however, note that
127+[connection pools](pooling/) are created at the session level, so each new session will consume additional system
128+resources:
129+
130+```java
131+// Warning: creating two sessions doubles the number of TCP connections opened by the driver
132+Session session1 = cluster.connect("ks1");
133+Session session2 = cluster.connect("ks2");
134+```
135+
136+Also, there is currently a [known limitation](async/#known-limitations) with named sessions, that causes the driver to
137+unexpectedly block the calling thread in certain circumstances; if you use a fully asynchronous model, you should use a
138+session with no keyspace.
139+
140+Finally, if you issue a `USE` statement, it will change the default keyspace on that session:
141+
142+```java
143+Session session = cluster.connect();
144+// No default keyspace set, need to prefix:
145+session.execute("select * from myKeyspace.myTable where id = 1");
146+
147+session.execute("USE myKeyspace");
148+// Now the keyspace is set, unqualified query works:
149+session.execute("select * from myTable where id = 1");
150+```
151+
152+Be very careful though: if the session is shared by multiple threads, switching the keyspace at runtime could easily
153+cause unexpected query failures.
154+
155+Generally, the recommended approach is to use a single session with no keyspace, and prefix all your queries.
156+
157+
158+### Running queries
159+
160+You run queries with the session's `execute` method:
161+
162+```java
163+ResultSet rs = session.execute("select release_version from system.local");
164+```
165+
166+As shown here, the simplest form is to pass a query string directly. You can also pass an instance of
167+[Statement](statements/).
168+
169+#### Processing rows
170+
171+Executing a query produces a [ResultSet], which is an iterable of [Row]. The basic way to process all rows is to use
172+Java's for-each loop:
173+
174+```java
175+for (Row row : rs) {
176+ // process the row
177+}
178+```
179+
180+Note that this will return **all results** without limit (even though the driver might use multiple queries in the
181+background). To handle large result sets, you might want to use a `LIMIT` clause in your CQL query, or use one of the
182+techniques described in the [paging](paging/) documentation.
183+
184+When you know that there is only one row (or are only interested in the first one), the driver provides a convenience
185+method:
186+
187+```java
188+Row row = rs.one();
189+```
190+
191+#### Reading columns
192+
193+[Row] provides getters to extract column values; they can be either positional or named:
194+
195+```java
196+Row row = session.execute("select first_name, last_name from users where id = 1").one();
197+
198+// The two are equivalent:
199+String firstName = row.getString(0);
200+String firstName = row.getString("first_name");
201+```
202+
203+##### CQL to Java type mapping
204+
205+<table border="1" style="text-align:center; width:100%;margin-bottom:1em;">
206+ <tr> <td><b>CQL3 data type</b></td> <td><b>Getter name</b></td> <td><b>Java type</b></td> </tr>
207+ <tr> <td>ascii</td> <td>getString</td> <td>java.lang.String</td> </tr>
208+ <tr> <td>bigint</td> <td>getLong</td> <td>long</td> </tr>
209+ <tr> <td>blob</td> <td>getBytes</td> <td>java.nio.ByteBuffer</td> </tr>
210+ <tr> <td>boolean</td> <td>getBool</td> <td>boolean</td> </tr>
211+ <tr> <td>counter</td> <td>getLong</td> <td>long</td> </tr>
212+ <tr> <td>date</td> <td>getDate</td> <td><a href="http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/LocalDate.html">LocalDate</a></td> </tr>
213+ <tr> <td>decimal</td> <td>getDecimal</td> <td>java.math.BigDecimal</td> </tr>
214+ <tr> <td>double</td> <td>getDouble</td> <td>double</td> </tr>
215+ <tr> <td>float</td> <td>getFloat</td> <td>float</td> </tr>
216+ <tr> <td>inet</td> <td>getInet</td> <td>java.net.InetAddress</td> </tr>
217+ <tr> <td>int</td> <td>getInt</td> <td>int</td> </tr>
218+ <tr> <td>list</td> <td>getList</td> <td>java.util.List<T></td> </tr>
219+ <tr> <td>map</td> <td>getMap</td> <td>java.util.Map<K, V></td> </tr>
220+ <tr> <td>set</td> <td>getSet</td> <td>java.util.Set<T></td> </tr>
221+ <tr> <td>smallint</td> <td>getShort</td> <td>short</td> </tr>
222+ <tr> <td>text</td> <td>getString</td> <td>java.lang.String</td> </tr>
223+ <tr> <td>time</td> <td>getTime</td> <td>long</td> </tr>
224+ <tr> <td>timestamp</td> <td>getTimestamp</td> <td>java.util.Date</td> </tr>
225+ <tr> <td>timeuuid</td> <td>getUUID</td> <td>java.util.UUID</td> </tr>
226+ <tr> <td>tinyint</td> <td>getByte</td> <td>byte</td> </tr>
227+ <tr> <td>tuple</td> <td>getTupleValue</td> <td><a href="tuples/">TupleValue</a></td> </tr>
228+ <tr> <td>user-defined types</td> <td>getUDTValue</td> <td><a href="udts/">UDTValue</a></td> </tr>
229+ <tr> <td>uuid</td> <td>getUUID</td> <td>java.util.UUID</td> </tr>
230+ <tr> <td>varchar</td> <td>getString</td> <td>java.lang.String</td> </tr>
231+ <tr> <td>varint</td> <td>getVarint</td> <td>java.math.BigInteger</td> </tr>
232+</table>
233+
234+In addition to these default mappings, you can register your own types with [custom codecs](custom_codecs/).
235+
236+##### Primitive types
237+
238+For performance reasons, the driver uses primitive Java types wherever possible (`boolean`, `int`...); the CQL value
239+`NULL` is encoded as the type's default value (`false`, `0`...), which can be ambiguous. To distinguish `NULL` from
240+actual values, use `isNull`:
241+
242+```java
243+Integer age = row.isNull("age") ? null : row.getInt("age");
244+```
245+
246+##### Collection types
247+
248+To ensure type safety, collection getters are generic. You need to provide type parameters matching your CQL type when
249+calling the methods:
250+
251+```java
252+// Assuming given_names is a list<text>:
253+List<String> givenNames = row.getList("given_names", String.class);
254+```
255+
256+For nested collections, element types are generic and cannot be expressed as Java `Class` instances. We use Guava's
257+[TypeToken](https://github.com/google/guava/wiki/ReflectionExplained) instead:
258+
259+```java
260+// Assuming teams is a set<list<text>>:
261+TypeToken<List<String>> listOfStrings = new TypeToken<List<String>>() {};
262+Set<List<String>> teams = row.getSet("teams", listOfStrings);
263+```
264+
265+Since type tokens are anonymous inner classes, it's recommended to store them as constants in a utility class instead of
266+re-creating them each time.
267+
268+##### Row metadata
269+
270+`Row` exposes an API to explore the column metadata at runtime:
271+
272+```java
273+for (ColumnDefinitions.Definition definition : row.getColumnDefinitions()) {
274+ System.out.printf("Column %s has type %s%n",
275+ definition.getName(),
276+ definition.getType());
277+}
278+```
279+
280+
281+### More information
5282
6283 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
284+github.io](http://datastax.github.io/java-driver/), use the "Contents"
285+menu on the left hand side to navigate sub-sections. If you're [browsing the source files on
9286 github.com](https://github.com/datastax/java-driver/tree/3.0/manual),
10287 simply navigate to each sub-directory.
11288
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.
289+[Cluster]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.html
290+[Cluster.Builder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.Builder.html
291+[Initializer]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.Initializer.html
292+[Session]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html
293+[ResultSet]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSet.html
294+[Row]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Row.html
295+[NettyOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/NettyOptions.html
296+[QueryOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html
297+[SocketOptions]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html
298+[Host.StateListener]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Host.StateListener.html
299+[LatencyTracker]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/LatencyTracker.html
300+[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SchemaChangeListener.html
301+[NoHostAvailableException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
302+[LocalDate]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/LocalDate.html
No newline at the end of the file
modified manual/async/README.md +3 −3
@@ -145,6 +145,6 @@
145145 hasn't been fetched already.
146146
147147 [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
148+[init]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.html#init()
149+[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
150+[query trace]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryTrace.html
added manual/auth/README.md +5 −0
@@ -0,0 +1,5 @@
1+## Authentication
2+
3+*Coming soon... In the meantime, see the javadoc for [AuthProvider].*
4+
5+[AuthProvider]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/AuthProvider.html
No newline at the end of the file
added manual/control_connection/README.md +10 −0
@@ -0,0 +1,10 @@
1+## Control connection
2+
3+*Coming soon...*
4+
5+<!--
6+TODO cover:
7+- what the control connection is (link to init sequence in ../README.md)
8+- server-sent events (gossip + schema changes)
9+- maybe event debouncing (although it sometimes applies to other types of events)
10+-->
No newline at the end of the file
added manual/load_balancing/README.md +331 −0
@@ -0,0 +1,331 @@
1+## Load balancing
2+
3+A Cassandra cluster is typically composed of multiple hosts; the [LoadBalancingPolicy] \(sometimes abbreviated LBP) is a
4+central component that determines:
5+
6+* which hosts the driver will communicate with;
7+* for each new query, which coordinator to pick, and which hosts to use as failover.
8+
9+The policy is configured when initializing the cluster:
10+
11+```java
12+Cluster cluster = Cluster.builder()
13+ .addContactPoint("127.0.0.1")
14+ .withLoadBalancingPolicy(new RoundRobinPolicy())
15+ .build();
16+```
17+
18+Once the cluster has been built, you can't change the policy, but you may inspect it at runtime:
19+
20+```java
21+LoadBalancingPolicy lbp = cluster.getConfiguration().getPolicies().getLoadBalancingPolicy();
22+```
23+
24+If you don't explicitly configure the policy, you get the default, which is a
25+[datacenter-aware](#dc-aware-round-robin-policy), [token-aware](#token-aware-policy) policy:
26+
27+```java
28+new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build());
29+```
30+
31+### Common concepts
32+
33+Before we review the available implementations, we need to introduce two concepts:
34+
35+#### Host distance
36+
37+For each host, the policy computes a **[distance][HostDistance]** that determines how the driver will establish connections
38+to it:
39+
40+* `LOCAL` and `REMOTE` are "active" distances, meaning that the driver will keep open connections to the host. They
41+ differ in the number of connections opened, depending on your [pooling options](../pooling/). Also, the
42+ [control connection](../control_connection/) will favor local nodes if possible.
43+* `IGNORED`, as the name suggests, means that the driver will not attempt to connect.
44+
45+Typically, the distance will reflect network topology (e.g. local vs. remote datacenter), although that is entirely up
46+to your policy. The distance can be dynamic: the driver re-checks it whenever connection pools are created (e.g. at
47+startup or if a node was down and just came back up); you can also trigger it with [refreshConnectedHosts]:
48+
49+```java
50+// Re-evaluate all host distances:
51+cluster.getConfiguration().getPoolingOptions().refreshConnectedHosts();
52+
53+// Re-evaluate the distance for a given host:
54+cluster.getConfiguration().getPoolingOptions().refreshConnectedHost(host);
55+```
56+
57+#### Query plan
58+
59+Each time the driver executes a query, it asks the policy to compute a **query plan**, which is a list of hosts. The
60+driver will then try each host in sequence, according to the [retry policy](../retries/) and
61+[speculative execution policy](../speculative_execution).
62+
63+The contents and order of query plans are entirely up to your policy, but implementations typically return plans that:
64+
65+* are different for each query, in order to balance the load across the cluster;
66+* only contain hosts that are known to be able to process queries, i.e. neither ignored nor down;
67+* favor local hosts over remote ones.
68+
69+The next sections describe the implementations that are provided with the driver.
70+
71+
72+### [RoundRobinPolicy]
73+
74+```java
75+Cluster cluster = Cluster.builder()
76+ .addContactPoint("127.0.0.1")
77+ .withLoadBalancingPolicy(new RoundRobinPolicy())
78+ .build();
79+```
80+
81+This is the most straightforward implementation. It returns query plans that include all hosts, and shift for each
82+query in a round-robin fashion. For example:
83+
84+* query 1: host1, host2, host3
85+* query 2: host2, host3, host1
86+* query 3: host3, host1, host2
87+* query 4: host1, host2, host3
88+* etc.
89+
90+All hosts are at distance `LOCAL`.
91+
92+This works well for simple deployments. If you have multiple datacenters, it will be inefficient and you probably want
93+to switch to a DC-aware policy.
94+
95+
96+### [DCAwareRoundRobinPolicy]
97+
98+```java
99+Cluster cluster = Cluster.builder()
100+ .addContactPoint("127.0.0.1")
101+ .withLoadBalancingPolicy(
102+ DCAwareRoundRobinPolicy.builder()
103+ .withLocalDc("myLocalDC")
104+ .withUsedHostsPerRemoteDc(2)
105+ .allowRemoteDCsForLocalConsistencyLevel()
106+ .build()
107+ ).build();
108+```
109+
110+This policy queries nodes of the local data-center in a round-robin fashion; optionally, it can also try a configurable
111+number of hosts in remote data centers if all local hosts failed.
112+
113+Call `withLocalDc` to specify the name of your local datacenter. You can also leave it out, and the driver will use the
114+datacenter of the first contact point that was reached [at initialization](../#cluster-initialization). However,
115+remember that the driver shuffles the initial list of contact points, so this assumes that all contact points are in the
116+local datacenter. In general, providing the datacenter name explicitly is a safer option.
117+
118+Hosts belonging to the local datacenter are at distance `LOCAL`, and appear first in query plans (in a round-robin
119+fashion).
120+
121+If you call `withUsedHostsPerRemoteDc`, the policy will pick that number of hosts for each remote DC, and add them at
122+the end of query plans. To illustrate this, let's assume that the value is 2, there are 3 datacenters and 3 hosts in the
123+local datacenter. Query plans would look like this:
124+
125+* query 1: localHost1, localHost2, localHost3, host1InRemoteDc1, host2InRemoteDc1, host1InRemoteDc2, host2InRemoteDc2
126+* query 2: localHost2, localHost3, localHost1, host1InRemoteDc1, host2InRemoteDc1, host1InRemoteDc2, host2InRemoteDc2
127+* query 3: localHost3, localHost1, localHost2, host1InRemoteDc1, host2InRemoteDc1, host1InRemoteDc2, host2InRemoteDc2
128+
129+Hosts selected by this option are at distance `REMOTE`. Note that they always appear in the same order.
130+
131+Finally, `allowRemoteDCsForLocalConsistencyLevel` controls whether remote hosts included by the previous option are
132+included when the consistency level of the query is `LOCAL_ONE` or `LOCAL_QUORUM`. By default, it is off (remote hosts
133+are not included for local CLs).
134+
135+
136+### [TokenAwarePolicy]
137+
138+```java
139+Cluster cluster = Cluster.builder()
140+ .addContactPoint("127.0.0.1")
141+ .withLoadBalancingPolicy(new TokenAwarePolicy(anotherPolicy))
142+ .build();
143+```
144+
145+This policy adds **token awareness** on top of another policy: requests will be routed in priority to the local replicas
146+that own the data that is being queried.
147+
148+#### Requirements
149+
150+In order for token awareness to work, you should first ensure that metadata is enabled in the driver. That is the case
151+by default, unless it's been explicitly disabled by [QueryOptions#setMetadataEnabled][setMetadataEnabled].
152+
153+Then you need to consider whether routing information (provided by [Statement#getKeyspace] and
154+[Statement#getRoutingKey]) can be computed automatically for your statements; if not, you may provide it yourself (if a
155+statement has no routing information, the query will still be executed, but token awareness will not work, so the driver
156+might not pick the best coordinator).
157+
158+The examples assume the following CQL schema:
159+
160+```
161+CREATE TABLE testKs.sensor_data(id int, year int, ts timestamp, data double,
162+ PRIMARY KEY ((id, year), ts));
163+```
164+
165+For [simple statements](../statements/simple/), routing information can never be computed automatically:
166+
167+```java
168+SimpleStatement statement = new SimpleStatement(
169+ "SELECT * FROM testKs.sensor_data WHERE id = 1 and year = 2016");
170+
171+// No routing info available:
172+assert statement.getKeyspace() == null;
173+assert statement.getRoutingKey() == null;
174+
175+// Set the keyspace manually:
176+statement.setKeyspace("testKs");
177+
178+// Set the routing key manually: serialize each partition key component to its target CQL type
179+ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
180+statement.setRoutingKey(
181+ DataType.cint().serialize(1, protocolVersion),
182+ DataType.cint().serialize(2016, protocolVersion));
183+
184+session.execute(statement);
185+```
186+
187+For [built statements](../statements/built/), the keyspace is available if it was provided while building the query; the
188+routing key is available only if the statement was built using the table metadata, and all components of the partition
189+key appear in the query:
190+
191+```java
192+TableMetadata tableMetadata = cluster.getMetadata()
193+ .getKeyspace("testKs")
194+ .getTable("sensor_data");
195+
196+// Built from metadata: all info available
197+BuiltStatement statement1 = select().from(tableMetadata)
198+ .where(eq("id", 1))
199+ .and(eq("year", 2016));
200+
201+assert statement1.getKeyspace() != null;
202+assert statement1.getRoutingKey() != null;
203+
204+// Built from keyspace and table name: only keyspace available
205+BuiltStatement statement2 = select().from("testKs", "sensor")
206+ .where(eq("id", 1))
207+ .and(eq("year", 2016));
208+
209+assert statement2.getKeyspace() != null;
210+assert statement2.getRoutingKey() == null;
211+```
212+
213+For [bound statements](../statements/prepared/), the keyspace is always available; the routing key is only available if
214+all components of the partition key are bound as variables:
215+
216+```java
217+// All components bound: all info available
218+PreparedStatement pst1 = session.prepare("SELECT * FROM testKs.sensor_data WHERE id = :id and year = :year");
219+BoundStatement statement1 = pst1.bind(1, 2016);
220+
221+assert statement1.getKeyspace() != null;
222+assert statement1.getRoutingKey() != null;
223+
224+// 'id' hard-coded, only 'year' is bound: only keyspace available
225+PreparedStatement pst2 = session.prepare("SELECT * FROM testKs.sensor_data WHERE id = 1 and year = :year");
226+BoundStatement statement2 = pst2.bind(2016);
227+
228+assert statement2.getKeyspace() != null;
229+assert statement2.getRoutingKey() == null;
230+```
231+
232+For [batch statements](../statements/batch/), the routing information of each child statement is inspected; the first
233+non-null keyspace is used as the keyspace of the batch, and the first non-null routing key as its routing key (the idea
234+is that all childs should have the same routing information, since batches are supposed to operate on a single
235+partition). All children might have null information, in which case you need to provide the information manually as
236+shown previously.
237+
238+#### Behavior
239+
240+For any host, the distance returned by `TokenAwarePolicy` is always the same as its child policy.
241+
242+When the policy computes a query plan, it will first inspect the statement's routing information. If there is none, the
243+policy simply acts as a pass-through, and returns the query plan computed by its child policy.
244+
245+If the statement has routing information, the policy uses it to determine the replicas that hold the corresponding data.
246+Then it returns a query plan containing:
247+
248+1. the replicas for which the child policy returns distance `LOCAL`, shuffled in a random order;
249+2. followed by the query plan of the child policy, skipping any host that were already returned by the previous step.
250+
251+Finally, the `shuffleReplicas` constructor parameter allows you to control whether the policy shuffles the replicas in
252+step 1:
253+
254+```java
255+new TokenAwarePolicy(anotherPolicy, false); // no shuffling
256+```
257+
258+Shuffling will distribute writes better, and can alleviate hotspots caused by "fat" partitions. On the other hand,
259+setting it to `false` might increase the effectiveness of caching, since data will always be retrieved from the
260+"primary" replica. Shuffling is enabled by default.
261+
262+### [LatencyAwarePolicy]
263+
264+```java
265+Cluster cluster = Cluster.builder()
266+ .addContactPoint("127.0.0.1")
267+ .withLoadBalancingPolicy(
268+ LatencyAwarePolicy.builder(anotherPolicy)
269+ .withExclusionThreshold(2.0)
270+ .withScale(100, TimeUnit.MILLISECONDS)
271+ .withRetryPeriod(10, TimeUnit.SECONDS)
272+ .withUpdateRate(100, TimeUnit.MILLISECONDS)
273+ .withMininumMeasurements(50)
274+ .build()
275+ ).build();
276+```
277+
278+This policy adds **latency awareness** on top of another policy: it collects the latencies of queries to each host, and
279+will exclude the worst-performing hosts from query plans.
280+
281+The builder allow you to customize various aspects of the policy:
282+
283+* the [exclusion threshold][withExclusionThreshold] controls how much worse a host must perform (compared to the fastest
284+ host) in order to be excluded. For example, 2 means that hosts that are twice slower will be excluded;
285+* since a host's performance can vary over time, its score is computed with a time-weighted average; the
286+ [scale][withScale] controls how fast the weight given to older latencies decreases over time;
287+* the [retry period][withRetryPeriod] is the duration for which a slow host will be penalized;
288+* the [update rate][withUpdateRate] defines how often the minimum average latency (i.e. the fastest host) is recomputed;
289+* the [minimum measurements][withMininumMeasurements] threshold guarantees that we have enough measurements before we
290+ start excluding a host. This prevents skewing the measurements during a node restart, where JVM warm-up will influence
291+ latencies.
292+
293+For any host, the distance returned by the policy is always the same as its child policy.
294+
295+Query plans are based on the child policy's, except that hosts that are currently excluded for being too slow are moved
296+to the end of the plan.
297+
298+[withExclusionThreshold]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withExclusionThreshold-double-
299+[withMininumMeasurements]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withMininumMeasurements-int-
300+[withRetryPeriod]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withRetryPeriod-long-java.util.concurrent.TimeUnit-
301+[withScale]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withScale-long-java.util.concurrent.TimeUnit-
302+[withUpdateRate]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withUpdateRate-long-java.util.concurrent.TimeUnit-
303+
304+### Filtering policies
305+
306+[WhiteListPolicy] wraps another policy with a white list, to ensure that the driver will only ever connect to a
307+pre-defined subset of the cluster. The distance will be that of the child policy for hosts that are in the white list,
308+and `IGNORED` otherwise. Query plans are guaranteed to only contain white-listed hosts.
309+
310+[HostFilterPolicy] is a generalization of that concept, where you provide the predicate that will determine if a host is
311+included or not.
312+
313+### Implementing your own
314+
315+If none of the provided policies fit your use case, you can write your own. This is an advanced topic, so we recommend
316+studying the existing implementations first: `RoundRobinPolicy` is a good place to start, then you can look at more
317+complex ones like `DCAwareRoundRobinPolicy`.
318+
319+
320+[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
321+[RoundRobinPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RoundRobinPolicy.html
322+[DCAwareRoundRobinPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.html
323+[TokenAwarePolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/TokenAwarePolicy.html
324+[LatencyAwarePolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LatencyAwarePolicy.html
325+[HostFilterPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/HostFilterPolicy.html
326+[WhiteListPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/WhiteListPolicy.html
327+[HostDistance]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/HostDistance.html
328+[refreshConnectedHosts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#refreshConnectedHosts--
329+[setMetadataEnabled]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setMetadataEnabled-boolean-
330+[Statement#getKeyspace]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Statement.html#getKeyspace--
331+[Statement#getRoutingKey]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Statement.html#getRoutingKey--
modified manual/metadata/README.md +2 −2
@@ -47,8 +47,8 @@
4747 otherwise the listener could be notified with a great deal of "Added" events as
4848 the driver builds the schema metadata from scratch for the first time.
4949
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)
50+[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SchemaChangeListener.html
51+[registerListener]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.html#register(com.datastax.driver.core.SchemaChangeListener)
5252
5353 #### Schema agreement
5454
added manual/metrics/README.md +12 −0
@@ -0,0 +1,12 @@
1+## Metrics
2+
3+*Coming soon... In the meantime, see the javadoc for [Metrics].*
4+
5+<!--
6+TODO cover:
7+- methods on Cluster.builder()
8+- using your own MetricsRegistry (see JAVA-494)
9+- getMetrics() returns null until Cluster initialized
10+-->
11+
12+[Metrics]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Metrics.html
No newline at the end of the file
modified manual/object_mapper/creating/README.md +1 −1
@@ -181,7 +181,7 @@
181181 (this also works with UDTs inside collections or other UDTs, with
182182 arbitrary level of nesting)
183183
184-[User Defined Types]:http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/reference/userDefinedTypes.html
184+[User Defined Types]: ../../udts/
185185 [udt]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/UDT.html
186186 [field]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Field.html
187187
added manual/reconnection/README.md +11 −0
@@ -0,0 +1,11 @@
1+## Reconnection
2+
3+*Coming soon... In the meantime, see the javadoc for [ReconnectionPolicy].*
4+
5+<!--
6+TODO cover:
7+- reconnection policy
8+- scheduled reconnections vs. gossip events
9+-->
10+
11+[ReconnectionPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/ReconnectionPolicy.html
No newline at the end of the file
added manual/retries/README.md +6 −0
@@ -0,0 +1,6 @@
1+## Retries
2+
3+*Coming soon... In the meantime, see the javadoc for [RetryPolicy].*
4+
5+
6+[RetryPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html
No newline at the end of the file
modified manual/statements/README.md +11 −15
@@ -3,15 +3,15 @@
33 To execute a query, you create a [Statement] instance and pass it to
44 `Session#execute()`. The driver provides various implementations:
55
6-* [SimpleStatement]: a simple implementation built directly from a
6+* [SimpleStatement](simple/): a simple implementation built directly from a
77 character string. Typically used for queries that are executed only
88 once or a few times.
9-* [BoundStatement]: obtained by binding values to a [prepared
10- statement](prepared/). Typically used for queries that are executed
9+* [BoundStatement](prepared/): obtained by binding values to a prepared
10+ statement. Typically used for queries that are executed
1111 often, with different values.
12-* [BuiltStatement]: a statement built with the [QueryBuilder] DSL. It
12+* [BuiltStatement](built/): a statement built with the [QueryBuilder] DSL. It
1313 can be executed directly like a simple statement, or prepared.
14-* [BatchStatement]: a statement that groups multiple statements to be
14+* [BatchStatement](batch/): a statement that groups multiple statements to be
1515 executed as a batch.
1616
1717 `Session` also has a shortcut to build and execute a simple statement in
@@ -42,13 +42,9 @@
4242 properties that influence statement execution. To achieve this, you can
4343 wrap your statements in a custom [StatementWrapper] implementation.
4444
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
45+[Statement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Statement.html
46+[QueryBuilder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/QueryBuilder.html
47+[StatementWrapper]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/StatementWrapper.html
48+[RetryPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/RetryPolicy.html
49+[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
50+[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html
added manual/statements/batch/README.md +5 −0
@@ -0,0 +1,5 @@
1+## Batch statements
2+
3+*Coming soon... In the meantime, see the javadoc for [BatchStatement].*
4+
5+[BatchStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BatchStatement.html
added manual/statements/built/README.md +5 −0
@@ -0,0 +1,5 @@
1+## Built statements
2+
3+*Coming soon... In the meantime, see the javadoc for [QueryBuilder].*
4+
5+[QueryBuilder]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/QueryBuilder.html
No newline at the end of the file
modified manual/statements/prepared/README.md +2 −2
@@ -184,5 +184,5 @@
184184 specific situations; read each method's Javadoc for detailed
185185 explanations.
186186
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)
187+[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts(boolean)
188+[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp(boolean)
added manual/statements/simple/README.md +5 −0
@@ -0,0 +1,5 @@
1+## Simple statements
2+
3+*Coming soon... In the meantime, see the javadoc for [SimpleStatement].*
4+
5+[SimpleStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SimpleStatement.html
added manual/tuples/README.md +5 −0
@@ -0,0 +1,5 @@
1+## Tuples
2+
3+*Coming soon... In the meantime, see the javadoc for [TupleType].*
4+
5+[TupleType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleType.html
No newline at the end of the file
added manual/udts/README.md +5 −0
@@ -0,0 +1,5 @@
1+## User-defined types
2+
3+*Coming soon... In the meantime, see the javadoc for [UserType].*
4+
5+[UserType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UserType.html
No newline at the end of the file