Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changeset6d6a6c256bb859155249a1cbcfe6a68227969ae8c8701ed76c6ae6540b95b50d
Authorolim7t <omichallat+github@gmail.com> · 2015-02-19 18:40 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-02-19 19:04 +01:00
Parents8c8fb5365c18, 37bbc95ff88d

Browse the files at this changeset

27 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -9,6 +9,7 @@
99 - [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518)
1010 - [improvement] Add connection heartbeat (JAVA-533)
1111 - [improvement] Reduce level of logs on missing rpc_address (JAVA-568)
12+- [improvement] Expose node token and range information (JAVA-312)
1213 - [bug] Prevent race between cancellation and query completion (JAVA-614)
1314 - [bug] Prevent cancel and timeout from cancelling unrelated ResponseHandler if
1415 streamId was already released and reused (JAVA-632).
modified driver-core/src/main/java/com/datastax/driver/core/AbstractData.java +15 −0
@@ -271,6 +271,21 @@
271271 return wrapped;
272272 }
273273
274+ // setToken is package-private because we only want to expose it in BoundStatement
275+ T setToken(int i, Token v) {
276+ if (v == null)
277+ throw new NullPointerException(String.format("Cannot set a null token for column %s", getName(i)));
278+ checkType(i, v.getType().getName());
279+ return setValue(i, v.getType().codec(protocolVersion).serialize(v.getValue()));
280+ }
281+
282+ T setToken(String name, Token v) {
283+ int[] indexes = getAllIndexesOf(name);
284+ for (int i = 0; i < indexes.length; i++)
285+ setToken(indexes[i], v);
286+ return wrapped;
287+ }
288+
274289 public <E> T setList(int i, List<E> v) {
275290 DataType type = getType(i);
276291 if (type.getName() != DataType.Name.LIST)
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +17 −11
@@ -40,14 +40,15 @@
4040 private static final Queue<List<ByteBuffer>> EMPTY_QUEUE = new ArrayDeque<List<ByteBuffer>>(0);
4141
4242 protected final ColumnDefinitions metadata;
43-
43+ protected final Token.Factory tokenFactory;
4444 private final boolean wasApplied;
4545
4646 protected final ProtocolVersion protocolVersion;
4747
48- private ArrayBackedResultSet(ColumnDefinitions metadata, List<ByteBuffer> firstRow, ProtocolVersion protocolVersion) {
48+ private ArrayBackedResultSet(ColumnDefinitions metadata, Token.Factory tokenFactory, List<ByteBuffer> firstRow, ProtocolVersion protocolVersion) {
4949 this.metadata = metadata;
5050 this.protocolVersion = protocolVersion;
51+ this.tokenFactory = tokenFactory;
5152 this.wasApplied = checkWasApplied(firstRow, metadata);
5253 }
5354
@@ -69,12 +70,15 @@
6970 columnDefs = r.metadata.columns;
7071 }
7172
73+ Token.Factory tokenFactory = (session == null) ? null
74+ : session.getCluster().getMetadata().tokenFactory();
75+
7276 // info can be null only for internal calls, but we don't page those. We assert
7377 // this explicitly because MultiPage implementation don't support info == null.
7478 assert r.metadata.pagingState == null || info != null;
7579 return r.metadata.pagingState == null
76- ? new SinglePage(columnDefs, protocolVersion, r.data, info)
77- : new MultiPage(columnDefs, protocolVersion, r.data, info, r.metadata.pagingState, session, statement);
80+ ? new SinglePage(columnDefs, tokenFactory, protocolVersion, r.data, info)
81+ : new MultiPage(columnDefs, tokenFactory, protocolVersion, r.data, info, r.metadata.pagingState, session, statement);
7882
7983 case SET_KEYSPACE:
8084 case SCHEMA_CHANGE:
@@ -93,8 +97,8 @@
9397 }
9498
9599 private static ArrayBackedResultSet empty(ExecutionInfo info) {
96- // We could pass the protocol version but we know we won't need it so passing a bogus value (-1)
97- return new SinglePage(ColumnDefinitions.EMPTY, null, EMPTY_QUEUE, info);
100+ // We could pass the protocol version but we know we won't need it so passing a bogus value (null)
101+ return new SinglePage(ColumnDefinitions.EMPTY, null, null, EMPTY_QUEUE, info);
98102 }
99103
100104 public ColumnDefinitions getColumnDefinitions() {
@@ -153,10 +157,11 @@
153157 private final ExecutionInfo info;
154158
155159 private SinglePage(ColumnDefinitions metadata,
160+ Token.Factory tokenFactory,
156161 ProtocolVersion protocolVersion,
157162 Queue<List<ByteBuffer>> rows,
158163 ExecutionInfo info) {
159- super(metadata, rows.peek(), protocolVersion);
164+ super(metadata, tokenFactory, rows.peek(), protocolVersion);
160165 this.info = info;
161166 this.rows = rows;
162167 }
@@ -166,7 +171,7 @@
166171 }
167172
168173 public Row one() {
169- return ArrayBackedRow.fromData(metadata, protocolVersion, rows.poll());
174+ return ArrayBackedRow.fromData(metadata, tokenFactory, protocolVersion, rows.poll());
170175 }
171176
172177 public int getAvailableWithoutFetching() {
@@ -216,6 +221,7 @@
216221 private final Statement statement;
217222
218223 private MultiPage(ColumnDefinitions metadata,
224+ Token.Factory tokenFactory,
219225 ProtocolVersion protocolVersion,
220226 Queue<List<ByteBuffer>> rows,
221227 ExecutionInfo info,
@@ -226,7 +232,7 @@
226232 // Note: as of Cassandra 2.1.0, it turns out that the result of a CAS update is never paged, so
227233 // we could hard-code the result of wasApplied in this class to "true". However, we can not be sure
228234 // that this will never change, so apply the generic check by peeking at the first row.
229- super(metadata, rows.peek(), protocolVersion);
235+ super(metadata, tokenFactory, rows.peek(), protocolVersion);
230236 this.currentPage = rows;
231237 this.infos.offer(info);
232238
@@ -242,7 +248,7 @@
242248
243249 public Row one() {
244250 prepareNextRow();
245- return ArrayBackedRow.fromData(metadata, protocolVersion, currentPage.poll());
251+ return ArrayBackedRow.fromData(metadata, tokenFactory, protocolVersion, currentPage.poll());
246252 }
247253
248254 public int getAvailableWithoutFetching() {
@@ -425,4 +431,4 @@
425431
426432 return TypeCodec.BooleanCodec.instance.deserializeNoBoxing(value);
427433 }
428-}
434+}
No newline at the end of the file
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java +36 −8
@@ -15,13 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.math.BigDecimal;
19-import java.math.BigInteger;
20-import java.net.InetAddress;
2118 import java.nio.ByteBuffer;
2219 import java.util.*;
2320
24-import com.datastax.driver.core.exceptions.InvalidTypeException;
21+import com.datastax.driver.core.exceptions.DriverInternalError;
2522
2623 /**
2724 * Implementation of a Row backed by an ArrayList.
@@ -29,19 +26,21 @@
2926 class ArrayBackedRow extends AbstractGettableData implements Row {
3027
3128 private final ColumnDefinitions metadata;
29+ private final Token.Factory tokenFactory;
3230 private final List<ByteBuffer> data;
3331
34- private ArrayBackedRow(ColumnDefinitions metadata, ProtocolVersion protocolVersion, List<ByteBuffer> data) {
32+ private ArrayBackedRow(ColumnDefinitions metadata, Token.Factory tokenFactory, ProtocolVersion protocolVersion, List<ByteBuffer> data) {
3533 super(protocolVersion);
3634 this.metadata = metadata;
35+ this.tokenFactory = tokenFactory;
3736 this.data = data;
3837 }
3938
40- static Row fromData(ColumnDefinitions metadata, ProtocolVersion protocolVersion, List<ByteBuffer> data) {
39+ static Row fromData(ColumnDefinitions metadata, Token.Factory tokenFactory, ProtocolVersion protocolVersion, List<ByteBuffer> data) {
4140 if (data == null)
4241 return null;
4342
44- return new ArrayBackedRow(metadata, protocolVersion, data);
43+ return new ArrayBackedRow(metadata, tokenFactory, protocolVersion, data);
4544 }
4645
4746 @Override
@@ -69,6 +68,35 @@
6968 return metadata.getFirstIdx(name);
7069 }
7170
71+ @Override
72+ public Token getToken(int i) {
73+ if (tokenFactory == null)
74+ throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
75+
76+ metadata.checkType(i, tokenFactory.getTokenType().getName());
77+
78+ ByteBuffer value = data.get(i);
79+ if (value == null || value.remaining() == 0)
80+ return null;
81+
82+ return tokenFactory.deserialize(value, protocolVersion);
83+ }
84+
85+ @Override
86+ public Token getToken(String name) {
87+ // first, try with `token(name)`, preserving case sensitivity
88+ String tokenName = (name.length() >= 2 && name.charAt(0) == '"' && name.charAt(name.length() - 1) == '"')
89+ ? "\"token(" + name.substring(1, name.length() - 1) + ")\""
90+ : "token(" + name + ")";
91+ int[] indexes = metadata.findAllIdx(tokenName);
92+ if (indexes != null) {
93+ return getToken(indexes[0]);
94+ }
95+
96+ // Otherwise, use normal name
97+ return getToken(metadata.getFirstIdx(name));
98+ }
99+
72100 @Override
73101 public String toString() {
74102 StringBuilder sb = new StringBuilder();
@@ -85,4 +113,4 @@
85113 sb.append(']');
86114 return sb.toString();
87115 }
88-}
116+}
No newline at the end of the file
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +35 −0
@@ -195,6 +195,9 @@
195195 }
196196 break;
197197 default:
198+ if (toSet instanceof Token)
199+ toSet = ((Token)toSet).getValue();
200+
198201 Class<?> providedClass = toSet.getClass();
199202 Class<?> expectedClass = columnType.getName().javaType;
200203 if (!expectedClass.isAssignableFrom(providedClass))
@@ -721,6 +724,38 @@
721724 return wrapper.setInet(name, v);
722725 }
723726
727+ /**
728+ * Sets the {@code i}th value to the provided {@link Token}.
729+ *
730+ * @param i the index of the variable to set.
731+ * @param v the value to set.
732+ * @return this BoundStatement.
733+ *
734+ * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
735+ * @throws InvalidTypeException if column {@code i} is not of the type of the token's value.
736+ */
737+ public BoundStatement setToken(int i, Token v) {
738+ return wrapper.setToken(i, v);
739+ }
740+
741+ /**
742+ * Sets the value for (all occurrences of) variable {@code name} to the
743+ * provided token.
744+ *
745+ * @param name the name of the variable to set; if multiple variables
746+ * {@code name} are prepared, all of them are set.
747+ * @param v the value to set.
748+ * @return this BoundStatement.
749+ *
750+ * @throws IllegalArgumentException if {@code name} is not a prepared
751+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
752+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
753+ * not of the type of the token's value.
754+ */
755+ public BoundStatement setToken(String name, Token v) {
756+ return wrapper.setToken(name, v);
757+ }
758+
724759 /**
725760 * Sets the {@code i}th value to the provided list.
726761 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +16 −0
@@ -17,6 +17,7 @@
1717
1818 import java.net.InetAddress;
1919 import java.net.InetSocketAddress;
20+import java.util.Set;
2021 import java.util.concurrent.atomic.AtomicReference;
2122 import java.util.concurrent.locks.ReentrantLock;
2223
@@ -66,6 +67,8 @@
6667 // (partly because the 'System.local' doesn't have it for some weird reason for instance).
6768 volatile InetAddress listenAddress;
6869
70+ private volatile Set<Token> tokens;
71+
6972 // ClusterMetadata keeps one Host object per inet address and we rely on this (more precisely,
7073 // we rely on the fact that we can use Object equality as a valid equality), so don't use
7174 // that constructor but ClusterMetadata.getHost instead.
@@ -158,6 +161,19 @@
158161 return cassandraVersion;
159162 }
160163
164+ /**
165+ * Returns the tokens that this host owns.
166+ *
167+ * @return the (immutable) set of tokens.
168+ */
169+ public Set<Token> getTokens() {
170+ return tokens;
171+ }
172+
173+ void setTokens(Set<Token> tokens) {
174+ this.tokens = tokens;
175+ }
176+
161177 /**
162178 * Returns whether the host is considered up by the driver.
163179 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +143 −15
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
1918 import java.net.InetSocketAddress;
2019 import java.nio.ByteBuffer;
2120 import java.util.*;
@@ -24,6 +23,7 @@
2423 import java.util.regex.Pattern;
2524
2625 import com.google.common.collect.ImmutableSet;
26+import com.google.common.collect.Maps;
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
2929
@@ -264,19 +264,61 @@
264264 return '"' + id + '"';
265265 }
266266
267+ /**
268+ * Returns the token ranges that define data distribution in the ring.
269+ * <p>
270+ * Note that this information is refreshed asynchronously by the control
271+ * connection, when schema or ring topology changes. It might occasionally
272+ * be stale.
273+ *
274+ * @return the token ranges.
275+ */
276+ public Set<TokenRange> getTokenRanges() {
277+ TokenMap current = tokenMap;
278+ return (current == null) ? Collections.<TokenRange>emptySet() : current.tokenRanges;
279+ }
280+
281+ /**
282+ * Returns the token ranges that are replicated on the given host, for the given
283+ * keyspace.
284+ * <p>
285+ * Note that this information is refreshed asynchronously by the control
286+ * connection, when schema or ring topology changes. It might occasionally
287+ * be stale (or even empty).
288+ *
289+ * @param keyspace the name of the keyspace to get token ranges for.
290+ * @param host the host.
291+ * @return the (immutable) set of token ranges for {@code host} as known
292+ * by the driver.
293+ */
294+ public Set<TokenRange> getTokenRanges(String keyspace, Host host) {
295+ keyspace = handleId(keyspace);
296+ TokenMap current = tokenMap;
297+ if (current == null) {
298+ return Collections.emptySet();
299+ } else {
300+ Map<Host, Set<TokenRange>> dcRanges = current.hostsToRanges.get(keyspace);
301+ if (dcRanges == null) {
302+ return Collections.emptySet();
303+ } else {
304+ Set<TokenRange> ranges = dcRanges.get(host);
305+ return (ranges == null) ? Collections.<TokenRange>emptySet() : ranges;
306+ }
307+ }
308+ }
309+
267310 /**
268311 * Returns the set of hosts that are replica for a given partition key.
269312 * <p>
270- * Note that this method is a best effort method. Consumers should not rely
271- * too heavily on the result of this method not being stale (or even empty).
313+ * Note that this information is refreshed asynchronously by the control
314+ * connection, when schema or ring topology changes. It might occasionally
315+ * be stale (or even empty).
272316 *
273317 * @param keyspace the name of the keyspace to get replicas for.
274318 * @param partitionKey the partition key for which to find the set of
275319 * replica.
276- * @return the (immutable) set of replicas for {@code partitionKey} as know
277- * by the driver. No strong guarantee is provided on the stalelessness of
278- * this information. It is also not guarantee that the returned set won't
279- * be empty (which is then some form of staleness).
320+ * @return the (immutable) set of replicas for {@code partitionKey} as known
321+ * by the driver.
280322 */
281323 public Set<Host> getReplicas(String keyspace, ByteBuffer partitionKey) {
282324 keyspace = handleId(keyspace);
@@ -289,6 +331,28 @@
289331 }
290332 }
291333
334+ /**
335+ * Returns the set of hosts that are replica for a given token range.
336+ * <p>
337+ * Note that this information is refreshed asynchronously by the control
338+ * connection, when schema or ring topology changes. It might occasionally
339+ * be stale (or even empty).
340+ *
341+ * @param keyspace the name of the keyspace to get replicas for.
342+ * @param range the token range.
343+ * @return the (immutable) set of replicas for {@code range} as known by the driver.
344+ */
345+ public Set<Host> getReplicas(String keyspace, TokenRange range) {
346+ keyspace = handleId(keyspace);
347+ TokenMap current = tokenMap;
348+ if (current == null) {
349+ return Collections.emptySet();
350+ } else {
351+ Set<Host> hosts = current.getReplicas(keyspace, range.getEnd());
352+ return hosts == null ? Collections.<Host>emptySet() : hosts;
353+ }
354+ }
355+
292356 /**
293357 * The Cassandra name for the cluster connect to.
294358 *
@@ -365,24 +429,42 @@
365429 return sb.toString();
366430 }
367431
432+ Token.Factory tokenFactory() {
433+ TokenMap current = tokenMap;
434+ return (current == null) ? null : current.factory;
435+ }
436+
368437 static class TokenMap {
369438
370439 private final Token.Factory factory;
371440 private final Map<String, Map<Token, Set<Host>>> tokenToHosts;
441+ private final Map<String, Map<Host, Set<TokenRange>>> hostsToRanges;
372442 private final List<Token> ring;
443+ private final Set<TokenRange> tokenRanges;
373444 final Set<Host> hosts;
374445
375- private TokenMap(Token.Factory factory, Map<String, Map<Token, Set<Host>>> tokenToHosts, List<Token> ring, Set<Host> hosts) {
446+ private TokenMap(Token.Factory factory,
447+ Map<Host, Set<Token>> primaryToTokens,
448+ Map<String, Map<Token, Set<Host>>> tokenToHosts,
449+ Map<String, Map<Host, Set<TokenRange>>> hostsToRanges,
450+ List<Token> ring, Set<TokenRange> tokenRanges, Set<Host> hosts) {
376451 this.factory = factory;
377452 this.tokenToHosts = tokenToHosts;
453+ this.hostsToRanges = hostsToRanges;
378454 this.ring = ring;
455+ this.tokenRanges = tokenRanges;
379456 this.hosts = hosts;
457+ for (Map.Entry<Host, Set<Token>> entry : primaryToTokens.entrySet()) {
458+ Host host = entry.getKey();
459+ host.setTokens(ImmutableSet.copyOf(entry.getValue()));
460+ }
380461 }
381462
382463 public static TokenMap build(Token.Factory factory, Map<Host, Collection<String>> allTokens, Collection<KeyspaceMetadata> keyspaces) {
383464
384465 Set<Host> hosts = allTokens.keySet();
385466 Map<Token, Host> tokenToPrimary = new HashMap<Token, Host>();
467+ Map<Host, Set<Token>> primaryToTokens = new HashMap<Host, Set<Token>>();
386468 Set<Token> allSorted = new TreeSet<Token>();
387469
388470 for (Map.Entry<Host, Collection<String>> entry : allTokens.entrySet()) {
@@ -392,6 +474,12 @@
392474 Token t = factory.fromString(tokenStr);
393475 allSorted.add(t);
394476 tokenToPrimary.put(t, host);
477+ Set<Token> hostTokens = primaryToTokens.get(host);
478+ if (hostTokens == null) {
479+ hostTokens = new HashSet<Token>();
480+ primaryToTokens.put(host, hostTokens);
481+ }
482+ hostTokens.add(t);
395483 } catch (IllegalArgumentException e) {
396484 // If we failed parsing that token, skip it
397485 }
@@ -399,18 +487,23 @@
399487 }
400488
401489 List<Token> ring = new ArrayList<Token>(allSorted);
490+ Set<TokenRange> tokenRanges = makeTokenRanges(ring, factory);
402491
403492 Map<String, Map<Token, Set<Host>>> tokenToHosts = new HashMap<String, Map<Token, Set<Host>>>();
493+ Map<String, Map<Host, Set<TokenRange>>> hostsToRanges = new HashMap<String, Map<Host, Set<TokenRange>>>();
404494 for (KeyspaceMetadata keyspace : keyspaces)
405495 {
406496 ReplicationStrategy strategy = keyspace.replicationStrategy();
407- if (strategy == null) {
408- tokenToHosts.put(keyspace.getName(), makeNonReplicatedMap(tokenToPrimary));
409- } else {
410- tokenToHosts.put(keyspace.getName(), strategy.computeTokenToReplicaMap(tokenToPrimary, ring));
411- }
497+ Map<Token, Set<Host>> ksTokens = (strategy == null)
498+ ? makeNonReplicatedMap(tokenToPrimary)
499+ : strategy.computeTokenToReplicaMap(tokenToPrimary, ring);
500+
501+ tokenToHosts.put(keyspace.getName(), ksTokens);
502+
503+ Map<Host, Set<TokenRange>> ksRanges = computeHostsToRangesMap(tokenRanges, ksTokens, hosts.size());
504+ hostsToRanges.put(keyspace.getName(), ksRanges);
412505 }
413- return new TokenMap(factory, tokenToHosts, ring, hosts);
506+ return new TokenMap(factory, primaryToTokens, tokenToHosts, hostsToRanges, ring, tokenRanges, hosts);
414507 }
415508
416509 private Set<Host> getReplicas(String keyspace, Token token) {
@@ -419,7 +512,12 @@
419512 if (keyspaceHosts == null)
420513 return Collections.emptySet();
421514
422- // Find the primary replica
515+ // If the token happens to be one of the "primary" tokens, get result directly
516+ Set<Host> hosts = keyspaceHosts.get(token);
517+ if (hosts != null)
518+ return hosts;
519+
520+ // Otherwise, find closest "primary" token on the ring
423521 int i = Collections.binarySearch(ring, token);
424522 if (i < 0) {
425523 i = -i - 1;
@@ -436,5 +534,35 @@
436534 output.put(entry.getKey(), ImmutableSet.of(entry.getValue()));
437535 return output;
438536 }
537+
538+ private static Set<TokenRange> makeTokenRanges(List<Token> ring, Token.Factory factory) {
539+ ImmutableSet.Builder<TokenRange> builder = ImmutableSet.builder();
540+ for (int i = 0; i < ring.size(); i++) {
541+ Token start = ring.get(i);
542+ Token end = ring.get((i + 1) % ring.size());
543+ builder.add(new TokenRange(start, end, factory));
544+ }
545+ return builder.build();
546+ }
547+
548+ private static Map<Host, Set<TokenRange>> computeHostsToRangesMap(Set<TokenRange> tokenRanges, Map<Token, Set<Host>> ksTokens, int hostCount) {
549+ Map<Host, ImmutableSet.Builder<TokenRange>> builders = Maps.newHashMapWithExpectedSize(hostCount);
550+ for (TokenRange range : tokenRanges) {
551+ Set<Host> replicas = ksTokens.get(range.getEnd());
552+ for (Host host : replicas) {
553+ ImmutableSet.Builder<TokenRange> hostRanges = builders.get(host);
554+ if (hostRanges == null) {
555+ hostRanges = ImmutableSet.builder();
556+ builders.put(host, hostRanges);
557+ }
558+ hostRanges.add(range);
559+ }
560+ }
561+ Map<Host, Set<TokenRange>> ksRanges = Maps.newHashMapWithExpectedSize(hostCount);
562+ for (Map.Entry<Host, ImmutableSet.Builder<TokenRange>> entry : builders.entrySet()) {
563+ ksRanges.put(entry.getKey(), entry.getValue().build());
564+ }
565+ return ksRanges;
566+ }
439567 }
440568 }
modified driver-core/src/main/java/com/datastax/driver/core/Row.java +44 −0
@@ -433,6 +433,50 @@
433433 @Override
434434 public InetAddress getInet(String name);
435435
436+ /**
437+ * Returns the {@code i}th value of this row as a {@link Token}.
438+ *
439+ * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
440+ * @return the value of the {@code i}th column in this row as an Token.
441+ * If the value is NULL, {@code null} is returned.
442+ *
443+ * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
444+ * @throws InvalidTypeException if column {@code i} is not of the type of token values
445+ * for this cluster (this depends on the configured partitioner).
446+ */
447+ public Token getToken(int i);
448+
449+ /**
450+ * Returns the value of column {@code name} as a {@link Token}.
451+ * <p>
452+ * This method will first try with {@code token(name)}, because in most cases the column
453+ * is named that way since it results from the application of a CQL function:
454+ * <pre>
455+ * {@code
456+ * ResultSet rs = session.execute("SELECT token(k) FROM my_table WHERE k = 1");
457+ * Token token = rs.one().getToken("k"); // retrieves token(k)
458+ * }
459+ * </pre>
460+ * If that fails, it will try will {@code name}. This handles the case where the column
461+ * was aliased:
462+ * <pre>
463+ * {@code
464+ * ResultSet rs = session.execute("SELECT token(k) AS t FROM my_table WHERE k = 1");
465+ * Token token = rs.one().getToken("t");
466+ * }
467+ * </pre>
468+ *
469+ * @param name the name of the column to retrieve.
470+ * @return the value of column {@code name} as a Token.
471+ * If the value is NULL, {@code null} is returned.
472+ *
473+ * @throws IllegalArgumentException if {@code name} is not part of the
474+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
475+ * @throws InvalidTypeException if column {@code name} is not of the type of token values
476+ * for this cluster (this depends on the configured partitioner).
477+ */
478+ public Token getToken(String name);
479+
436480 /**
437481 * Returns the {@code i}th value of this row as a list.
438482 *
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +6 −3
@@ -92,11 +92,14 @@
9292 private static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion) {
9393 ByteBuffer[] serializedValues = new ByteBuffer[values.length];
9494 for (int i = 0; i < values.length; i++) {
95+ Object value = values[i];
9596 try {
96- serializedValues[i] = DataType.serializeValue(values[i], protocolVersion);
97+ if (value instanceof Token)
98+ value = ((Token)value).getValue();
99+ serializedValues[i] = DataType.serializeValue(value, protocolVersion);
97100 } catch (IllegalArgumentException e) {
98101 // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
99- throw new IllegalArgumentException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, values[i].getClass()));
102+ throw new IllegalArgumentException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, value.getClass()));
100103 }
101104 }
102105 return serializedValues;
@@ -248,4 +251,4 @@
248251 bb.put((byte) ((length >> 8) & 0xFF));
249252 bb.put((byte) (length & 0xFF));
250253 }
251-}
254+}
No newline at the end of the file
modified driver-core/src/main/java/com/datastax/driver/core/Token.java +339 −19
@@ -19,15 +19,35 @@
1919 import java.nio.ByteBuffer;
2020 import java.security.MessageDigest;
2121 import java.security.NoSuchAlgorithmException;
22+import java.util.Arrays;
23+import java.util.List;
2224
23-/*
24- * It's not an interface because we don't want to expose it
25- * Note: we may want to expose this later if people use custom partitioner and want to be able to extend that.
26- * This is way premature however.
27- */
28-abstract class Token implements Comparable<Token> {
25+import com.google.common.annotations.VisibleForTesting;
26+import com.google.common.collect.Lists;
27+import com.google.common.primitives.UnsignedBytes;
28+
29+import com.datastax.driver.core.utils.Bytes;
2930
30- public static Token.Factory getFactory(String partitionerName) {
31+/**
32+ * A token on the Cassandra ring.
33+ */
34+public abstract class Token implements Comparable<Token> {
35+
36+ /**
37+ * Returns the data type of this token's value.
38+ *
39+ * @return the datatype.
40+ */
41+ public abstract DataType getType();
42+
43+ /**
44+ * Returns the raw value of this token.
45+ *
46+ * @return the value.
47+ */
48+ public abstract Object getValue();
49+
50+ static Token.Factory getFactory(String partitionerName) {
3151 if (partitionerName.endsWith("Murmur3Partitioner"))
3252 return M3PToken.FACTORY;
3353 else if (partitionerName.endsWith("RandomPartitioner"))
@@ -38,16 +58,50 @@
3858 return null;
3959 }
4060
41- public interface Factory {
42- public Token fromString(String tokenStr);
43- public Token hash(ByteBuffer partitionKey);
61+ static abstract class Factory {
62+ abstract Token fromString(String tokenStr);
63+ abstract DataType getTokenType();
64+ abstract Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion);
65+ /** The minimum token is a special value that no key ever hashes to, it's used both as lower and upper bound. */
66+ abstract Token minToken();
67+ abstract Token hash(ByteBuffer partitionKey);
68+ abstract List<Token> split(Token startToken, Token endToken, int numberOfSplits);
69+
70+ // Base implementation for split
71+ protected List<BigInteger> split(BigInteger start, BigInteger range,
72+ BigInteger ringEnd, BigInteger ringLength,
73+ int numberOfSplits) {
74+ BigInteger[] tmp = range.divideAndRemainder(BigInteger.valueOf(numberOfSplits));
75+ BigInteger divider = tmp[0];
76+ int remainder = tmp[1].intValue();
77+
78+ List<BigInteger> results = Lists.newArrayListWithExpectedSize(numberOfSplits - 1);
79+ BigInteger current = start;
80+ BigInteger dividerPlusOne = (remainder == 0) ? null // won't be used
81+ : divider.add(BigInteger.ONE);
82+
83+ for (int i = 1; i < numberOfSplits; i++) {
84+ current = current.add(remainder-- > 0 ? dividerPlusOne : divider);
85+ if (ringEnd != null && current.compareTo(ringEnd) > 0)
86+ current = current.subtract(ringLength);
87+ results.add(current);
88+ }
89+ return results;
90+ }
4491 }
4592
4693 // Murmur3Partitioner tokens
4794 static class M3PToken extends Token {
4895 private final long value;
4996
50- public static final Factory FACTORY = new Factory() {
97+ public static final Factory FACTORY = new M3PTokenFactory();
98+
99+ private static class M3PTokenFactory extends Factory {
100+
101+ private static final BigInteger RING_END = BigInteger.valueOf(Long.MAX_VALUE);
102+ private static final BigInteger RING_LENGTH = RING_END.subtract(BigInteger.valueOf(Long.MIN_VALUE));
103+ public static final M3PToken MIN_TOKEN = new M3PToken(Long.MIN_VALUE);
104+ public static final M3PToken MAX_TOKEN = new M3PToken(Long.MAX_VALUE);
51105
52106 private long getblock(ByteBuffer key, int offset, int index) {
53107 int i_8 = index << 3;
@@ -152,17 +206,64 @@
152206 return new M3PToken(Long.parseLong(tokenStr));
153207 }
154208
209+ @Override
210+ DataType getTokenType() {
211+ return DataType.bigint();
212+ }
213+
214+ @Override
215+ Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion) {
216+ return new M3PToken((Long) getTokenType().deserialize(buffer, protocolVersion));
217+ }
218+
219+ @Override
220+ Token minToken() {
221+ return MIN_TOKEN;
222+ }
223+
155224 @Override
156225 public M3PToken hash(ByteBuffer partitionKey) {
157226 long v = murmur(partitionKey);
158227 return new M3PToken(v == Long.MIN_VALUE ? Long.MAX_VALUE : v);
159228 }
160- };
229+
230+ @Override
231+ List<Token> split(Token startToken, Token endToken, int numberOfSplits) {
232+ // edge case: ]min, min] means the whole ring
233+ if (startToken.equals(endToken) && startToken.equals(MIN_TOKEN))
234+ endToken = MAX_TOKEN;
235+
236+ BigInteger start = BigInteger.valueOf(((M3PToken)startToken).value);
237+ BigInteger end = BigInteger.valueOf(((M3PToken)endToken).value);
238+
239+ BigInteger range = end.subtract(start);
240+ if (range.compareTo(BigInteger.ZERO) < 0)
241+ range = range.add(RING_LENGTH);
242+
243+ List<BigInteger> values = super.split(start, range,
244+ RING_END, RING_LENGTH,
245+ numberOfSplits);
246+ List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size());
247+ for (BigInteger value : values)
248+ tokens.add(new M3PToken(value.longValue()));
249+ return tokens;
250+ }
251+ }
161252
162253 private M3PToken(long value) {
163254 this.value = value;
164255 }
165256
257+ @Override
258+ public DataType getType() {
259+ return FACTORY.getTokenType();
260+ }
261+
262+ @Override
263+ public Object getValue() {
264+ return value;
265+ }
266+
166267 @Override
167268 public int compareTo(Token other) {
168269 assert other instanceof M3PToken;
@@ -184,32 +285,186 @@
184285 public int hashCode() {
185286 return (int)(value^(value>>>32));
186287 }
288+
289+ @Override
290+ public String toString() {
291+ return Long.toString(value);
292+ }
187293 }
188294
189295 // OPPartitioner tokens
190296 static class OPPToken extends Token {
297+
191298 private final ByteBuffer value;
192299
193- public static final Factory FACTORY = new Factory() {
300+ public static final Factory FACTORY = new OPPTokenFactory();
301+
302+ private static class OPPTokenFactory extends Factory {
303+ private static final BigInteger TWO = BigInteger.valueOf(2);
304+ private static final Token MIN_TOKEN = new OPPToken(ByteBuffer.allocate(0));
305+
194306 @Override
195307 public OPPToken fromString(String tokenStr) {
196- return new OPPToken(TypeCodec.StringCodec.utf8Instance.serialize(tokenStr));
308+ String prefix = (tokenStr.length() % 2 == 0) ? "0x" : "0x0";
309+ ByteBuffer value = Bytes.fromHexString(prefix + tokenStr);
310+ return new OPPToken(value);
311+ }
312+
313+ @Override
314+ DataType getTokenType() {
315+ return DataType.blob();
316+ }
317+
318+ @Override
319+ Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion) {
320+ return new OPPToken(buffer);
321+ }
322+
323+ @Override
324+ Token minToken() {
325+ return MIN_TOKEN;
197326 }
198327
199328 @Override
200329 public OPPToken hash(ByteBuffer partitionKey) {
201330 return new OPPToken(partitionKey);
202331 }
203- };
204332
205- private OPPToken(ByteBuffer value) {
206- this.value = value;
333+ @Override
334+ public List<Token> split(Token startToken, Token endToken, int numberOfSplits) {
335+ int tokenOrder = startToken.compareTo(endToken);
336+
337+ // ]min,min] means the whole ring. However, since there is no "max token" with this partitioner, we can't come up
338+ // with a magic end value that would cover the whole ring
339+ if (tokenOrder == 0 && startToken.equals(MIN_TOKEN))
340+ throw new IllegalArgumentException("Cannot split whole ring with ordered partitioner");
341+
342+ OPPToken oppStartToken = (OPPToken)startToken;
343+ OPPToken oppEndToken = (OPPToken)endToken;
344+
345+ int significantBytes;
346+ BigInteger start, end, range, ringEnd, ringLength;
347+ BigInteger bigNumberOfSplits = BigInteger.valueOf(numberOfSplits);
348+ if (tokenOrder < 0) {
349+ // Since tokens are compared lexicographically, convert to integers using the largest length
350+ // (ex: given 0x0A and 0x0BCD, switch to 0x0A00 and 0x0BCD)
351+ significantBytes = Math.max(oppStartToken.value.capacity(), oppEndToken.value.capacity());
352+
353+ // If the number of splits does not fit in the difference between the two integers, use more bytes
354+ // (ex: cannot fit 4 splits between 0x01 and 0x03, so switch to 0x0100 and 0x0300)
355+ // At most 4 additional bytes will be needed, since numberOfSplits is an integer.
356+ int addedBytes = 0;
357+ while (true) {
358+ start = toBigInteger(oppStartToken.value, significantBytes);
359+ end = toBigInteger(oppEndToken.value, significantBytes);
360+ range = end.subtract(start);
361+ if (addedBytes == 4 || range.compareTo(bigNumberOfSplits) >= 0)
362+ break;
363+ significantBytes += 1;
364+ addedBytes += 1;
365+ }
366+ ringEnd = ringLength = null; // won't be used
367+ } else {
368+ // Same logic except that we wrap around the ring
369+ significantBytes = Math.max(oppStartToken.value.capacity(), oppEndToken.value.capacity());
370+ int addedBytes = 0;
371+ while (true) {
372+ start = toBigInteger(oppStartToken.value, significantBytes);
373+ end = toBigInteger(oppEndToken.value, significantBytes);
374+ ringLength = TWO.pow(significantBytes * 8);
375+ ringEnd = ringLength.subtract(BigInteger.ONE);
376+ range = end.subtract(start).add(ringLength);
377+ if (addedBytes == 4 || range.compareTo(bigNumberOfSplits) >= 0)
378+ break;
379+ significantBytes += 1;
380+ addedBytes += 1;
381+ }
382+ }
383+
384+ List<BigInteger> values = super.split(start, range,
385+ ringEnd, ringLength,
386+ numberOfSplits);
387+ List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size());
388+ for (BigInteger value : values)
389+ tokens.add(new OPPToken(toBytes(value, significantBytes)));
390+ return tokens;
391+ }
392+
393+ // Convert a token's byte array to a number in order to perform computations.
394+ // This depends on the number of "significant bytes" that we use to normalize all tokens to the same size.
395+ // For example if the token is 0x01 but significantBytes is 2, the result is 8 (0x0100).
396+ private BigInteger toBigInteger(ByteBuffer bb, int significantBytes) {
397+ byte[] bytes = Bytes.getArray(bb);
398+ byte[] target;
399+ if (significantBytes != bytes.length) {
400+ target = new byte[significantBytes];
401+ System.arraycopy(bytes, 0, target, 0, bytes.length);
402+ } else
403+ target = bytes;
404+ return new BigInteger(1, target);
405+ }
406+
407+ // Convert a numeric representation back to a byte array.
408+ // Again, the number of significant bytes matters: if the input value is 1 but significantBytes is 2, the
409+ // expected result is 0x0001 (a simple conversion would produce 0x01).
410+ protected ByteBuffer toBytes(BigInteger value, int significantBytes) {
411+ byte[] rawBytes = value.toByteArray();
412+ byte[] result;
413+ if (rawBytes.length == significantBytes)
414+ result = rawBytes;
415+ else {
416+ result = new byte[significantBytes];
417+ int start, length;
418+ if (rawBytes[0] == 0) { // that's a sign byte, ignore (it can cause rawBytes.length == significantBytes + 1)
419+ start = 1;
420+ length = rawBytes.length - 1;
421+ } else {
422+ start = 0;
423+ length = rawBytes.length;
424+ }
425+ System.arraycopy(rawBytes, start, result, significantBytes - length, length);
426+ }
427+ return ByteBuffer.wrap(result);
428+ }
429+ }
430+
431+ @VisibleForTesting
432+ OPPToken(ByteBuffer value) {
433+ this.value = stripTrailingZeroBytes(value);
434+ }
435+
436+ /**
437+ * @return A new ByteBuffer from the input Buffer with any trailing 0-bytes stripped off.
438+ */
439+ private static ByteBuffer stripTrailingZeroBytes(ByteBuffer b) {
440+ byte result[] = Bytes.getArray(b);
441+ int zeroIndex = result.length;
442+ for(int i = result.length-1; i > 0; i--) {
443+ if(result[i] == 0) {
444+ zeroIndex = i;
445+ } else {
446+ break;
447+ }
448+ }
449+ return ByteBuffer.wrap(result, 0, zeroIndex);
450+ }
451+
452+ @Override
453+ public DataType getType() {
454+ return FACTORY.getTokenType();
455+ }
456+
457+ @Override
458+ public Object getValue() {
459+ return value;
207460 }
208461
209462 @Override
210463 public int compareTo(Token other) {
211464 assert other instanceof OPPToken;
212- return value.compareTo(((OPPToken)other).value);
465+ return UnsignedBytes.lexicographicalComparator().compare(
466+ Bytes.getArray(value),
467+ Bytes.getArray(((OPPToken)other).value));
213468 }
214469
215470 @Override
@@ -226,6 +481,11 @@
226481 public int hashCode() {
227482 return value.hashCode();
228483 }
484+
485+ @Override
486+ public String toString() {
487+ return Bytes.toHexString(value);
488+ }
229489 }
230490
231491 // RandomPartitioner tokens
@@ -233,7 +493,15 @@
233493
234494 private final BigInteger value;
235495
236- public static final Factory FACTORY = new Factory() {
496+ public static final Factory FACTORY = new RPTokenFactory();
497+
498+ private static class RPTokenFactory extends Factory {
499+
500+ private static final BigInteger MIN_VALUE = BigInteger.ONE.negate();
501+ private static final BigInteger MAX_VALUE = BigInteger.valueOf(2).pow(127);
502+ private static final BigInteger RING_LENGTH = MAX_VALUE.add(BigInteger.ONE);
503+ private static final Token MIN_TOKEN = new RPToken(MIN_VALUE);
504+ private static final Token MAX_TOKEN = new RPToken(MAX_VALUE);
237505
238506 private BigInteger md5(ByteBuffer data) {
239507 try {
@@ -250,16 +518,63 @@
250518 return new RPToken(new BigInteger(tokenStr));
251519 }
252520
521+ @Override
522+ DataType getTokenType() {
523+ return DataType.varint();
524+ }
525+
526+ @Override
527+ Token deserialize(ByteBuffer buffer, ProtocolVersion protocolVersion) {
528+ return new RPToken((BigInteger)getTokenType().deserialize(buffer, protocolVersion));
529+ }
530+
531+ @Override
532+ Token minToken() {
533+ return MIN_TOKEN;
534+ }
535+
253536 @Override
254537 public RPToken hash(ByteBuffer partitionKey) {
255538 return new RPToken(md5(partitionKey));
256539 }
540+
541+ @Override
542+ List<Token> split(Token startToken, Token endToken, int numberOfSplits) {
543+ // edge case: ]min, min] means the whole ring
544+ if (startToken.equals(endToken) && startToken.equals(MIN_TOKEN))
545+ endToken = MAX_TOKEN;
546+
547+ BigInteger start = ((RPToken)startToken).value;
548+ BigInteger end = ((RPToken)endToken).value;
549+
550+ BigInteger range = end.subtract(start);
551+ if (range.compareTo(BigInteger.ZERO) < 0)
552+ range = range.add(RING_LENGTH);
553+
554+ List<BigInteger> values = super.split(start, range,
555+ MAX_VALUE, RING_LENGTH,
556+ numberOfSplits);
557+ List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size());
558+ for (BigInteger value : values)
559+ tokens.add(new RPToken(value));
560+ return tokens;
561+ }
257562 };
258563
259564 private RPToken(BigInteger value) {
260565 this.value = value;
261566 }
262567
568+ @Override
569+ public DataType getType() {
570+ return FACTORY.getTokenType();
571+ }
572+
573+ @Override
574+ public Object getValue() {
575+ return value;
576+ }
577+
263578 @Override
264579 public int compareTo(Token other) {
265580 assert other instanceof RPToken;
@@ -280,5 +595,10 @@
280595 public int hashCode() {
281596 return value.hashCode();
282597 }
598+
599+ @Override
600+ public String toString() {
601+ return value.toString();
602+ }
283603 }
284604 }
added driver-core/src/main/java/com/datastax/driver/core/TokenRange.java +265 −0
@@ -0,0 +1,265 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.ArrayList;
19+import java.util.List;
20+
21+import com.google.common.base.Objects;
22+import com.google.common.collect.ImmutableList;
23+
24+/**
25+ * A range of tokens on the Cassandra ring.
26+ * <p>
27+ * A range is start-exclusive and end-inclusive. It is empty when start and end are the same token, except if that is the minimum
28+ * token, in which case the range covers the whole ring (this is consistent with the behavior of CQL range queries).
29+ * <p>
30+ * Note that CQL does not handle wrapping. To query all partitions in a range, see {@link #unwrap()}.
31+ */
32+public final class TokenRange implements Comparable<TokenRange> {
33+ private final Token start;
34+ private final Token end;
35+ private final Token.Factory factory;
36+
37+ TokenRange(Token start, Token end, Token.Factory factory) {
38+ this.start = start;
39+ this.end = end;
40+ this.factory = factory;
41+ }
42+
43+ /**
44+ * Return the start of the range.
45+ *
46+ * @return the start of the range (exclusive).
47+ */
48+ public Token getStart() {
49+ return start;
50+ }
51+
52+ /**
53+ * Return the end of the range.
54+ *
55+ * @return the end of the range (inclusive).
56+ */
57+ public Token getEnd() {
58+ return end;
59+ }
60+
61+ /**
62+ * Splits this range into a number of smaller ranges of equal "size" (referring to the number of tokens, not the actual amount of data).
63+ * <p>
64+ * Splitting an empty range is not permitted. But note that, in edge cases, splitting a range might produce one or more empty ranges.
65+ *
66+ * @param numberOfSplits the number of splits to create.
67+ * @return the splits.
68+ *
69+ * @throws IllegalArgumentException if the range is empty or if numberOfSplits < 1.
70+ */
71+ public List<TokenRange> splitEvenly(int numberOfSplits) {
72+ if (numberOfSplits < 1)
73+ throw new IllegalArgumentException(String.format("numberOfSplits (%d) must be greater than 0.", numberOfSplits));
74+ if (isEmpty())
75+ throw new IllegalArgumentException("Can't split empty range " + this);
76+
77+ List<TokenRange> tokenRanges = new ArrayList<TokenRange>();
78+ List<Token> splitPoints = factory.split(start, end, numberOfSplits);
79+ Token splitStart = start;
80+ for (Token splitEnd : splitPoints) {
81+ tokenRanges.add(new TokenRange(splitStart, splitEnd, factory));
82+ splitStart = splitEnd;
83+ }
84+ tokenRanges.add(new TokenRange(splitStart, end, factory));
85+ return tokenRanges;
86+ }
87+
88+ /**
89+ * Returns whether this range is empty.
90+ * <p>
91+ * A range is empty when start and end are the same token, except if that is the minimum token,
92+ * in which case the range covers the whole ring (this is consistent with the behavior of CQL
93+ * range queries).
94+ *
95+ * @return whether the range is empty.
96+ */
97+ public boolean isEmpty() {
98+ return start.equals(end) && !start.equals(factory.minToken());
99+ }
100+
101+ /**
102+ * Returns whether this range wraps around the end of the ring.
103+ *
104+ * @return whether this range wraps around.
105+ */
106+ public boolean isWrappedAround() {
107+ return start.compareTo(end) > 0 && !end.equals(factory.minToken());
108+ }
109+
110+ /**
111+ * Splits this range into a list of two non-wrapping ranges. This will return the range itself if it is
112+ * non-wrapping, or two ranges otherwise.
113+ * <p>
114+ * For example:
115+ * <ul>
116+ * <li>{@code ]1,10]} unwraps to itself;</li>
117+ * <li>{@code ]10,1]} unwraps to {@code ]10,min_token]} and {@code ]min_token,1]}.</li>
118+ * </ul>
119+ * <p>
120+ * This is useful for CQL range queries, which do not handle wrapping:
121+ * <pre>
122+ * {@code
123+ * List<Row> rows = new ArrayList<Row>();
124+ * for (TokenRange subRange : range.unwrap()) {
125+ * ResultSet rs = session.execute("SELECT * FROM mytable WHERE token(pk) > ? and token(pk) <= ?",
126+ * subRange.getStart(), subRange.getEnd());
127+ * rows.addAll(rs.all());
128+ * }
129+ * }</pre>
130+ *
131+ * @return the list of non-wrapping ranges.
132+ */
133+ public List<TokenRange> unwrap() {
134+ if (isWrappedAround()) {
135+ return ImmutableList.of(
136+ new TokenRange(start, factory.minToken(), factory),
137+ new TokenRange(factory.minToken(), end, factory));
138+ } else {
139+ return ImmutableList.of(this);
140+ }
141+ }
142+
143+ /**
144+ * Returns whether this range intersects another one.
145+ * <p>
146+ * For example:
147+ * <ul>
148+ * <li>{@code ]3,5]} intersects {@code ]1,4]}, {@code ]4,5]}...</li>
149+ * <li>{@code ]3,5]} does not intersect {@code ]1,2]}, {@code ]2,3]}, {@code ]5,7]}...</li>
150+ * </ul>
151+ *
152+ * @param that the other range.
153+ * @return whether they intersect.
154+ */
155+ public boolean intersects(TokenRange that) {
156+ // Empty ranges never intersect any other range
157+ if (this.isEmpty() || that.isEmpty())
158+ return false;
159+
160+ return this.contains(that.start, true)
161+ || this.contains(that.end, false)
162+ || that.contains(this.start, true)
163+ || that.contains(this.end, false);
164+ }
165+
166+ // isStart handles the case where the token is the start of another range, for example:
167+ // * ]1,2] contains 2, but it does not contain the start of ]2,3]
168+ // * ]1,2] does not contain 1, but it contains the start of ]1,3]
169+ private boolean contains(Token token, boolean isStart) {
170+ boolean isAfterStart = isStart ? token.compareTo(start) >= 0 : token.compareTo(start) > 0;
171+ boolean isBeforeEnd = end.equals(factory.minToken()) ||
172+ (isStart ? token.compareTo(end) < 0 : token.compareTo(end) <= 0);
173+ return isWrappedAround()
174+ ? isAfterStart || isBeforeEnd
175+ : isAfterStart && isBeforeEnd;
176+ }
177+
178+ /**
179+ * Merges this range with another one.
180+ * <p>
181+ * The two ranges should either intersect or be adjacent; in other words, the merged range
182+ * should not include tokens that are in neither of the original ranges.
183+ * <p>
184+ * For example:
185+ * <ul>
186+ * <li>merging {@code ]3,5]} with {@code ]4,7]} produces {@code ]3,7]};</li>
187+ * <li>merging {@code ]3,5]} with {@code ]4,5]} produces {@code ]3,5]};</li>
188+ * <li>merging {@code ]3,5]} with {@code ]5,8]} produces {@code ]3,8]};</li>
189+ * <li>merging {@code ]3,5]} with {@code ]6,8]} fails.</li>
190+ * </ul>
191+ *
192+ * @param that the other range.
193+ * @return the resulting range.
194+ *
195+ * @throws IllegalArgumentException if the ranges neither intersect nor are adjacent.
196+ */
197+ public TokenRange mergeWith(TokenRange that) {
198+ if (this.equals(that))
199+ return this;
200+
201+ if (!(this.intersects(that) || this.end.equals(that.start) || that.end.equals(this.start)))
202+ throw new IllegalArgumentException(String.format(
203+ "Can't merge %s with %s because they neither intersect nor are adjacent",
204+ this, that));
205+
206+ if (this.isEmpty())
207+ return that;
208+
209+ if (that.isEmpty())
210+ return this;
211+
212+ // That's actually "starts in or is adjacent to the end of"
213+ boolean thisStartsInThat = that.contains(this.start, true) || this.start.equals(that.end);
214+ boolean thatStartsInThis = this.contains(that.start, true) || that.start.equals(this.end);
215+
216+ // This takes care of all the cases that return the full ring, so that we don't have to worry about them below
217+ if (thisStartsInThat && thatStartsInThis)
218+ return fullRing();
219+
220+ // Starting at this.start, see how far we can go while staying in at least one of the ranges.
221+ Token mergedEnd = (thatStartsInThis && !this.contains(that.end, false))
222+ ? that.end
223+ : this.end;
224+
225+ // Repeat in the other direction.
226+ Token mergedStart = thisStartsInThat ? that.start : this.start;
227+
228+ return new TokenRange(mergedStart, mergedEnd, factory);
229+ }
230+
231+ private TokenRange fullRing() {
232+ return new TokenRange(factory.minToken(), factory.minToken(), factory);
233+ }
234+
235+ @Override
236+ public boolean equals(Object other) {
237+ if (other == this)
238+ return true;
239+ if (other instanceof TokenRange) {
240+ TokenRange that = (TokenRange)other;
241+ return Objects.equal(this.start, that.start) &&
242+ Objects.equal(this.end, that.end);
243+ }
244+ return false;
245+ }
246+
247+ @Override
248+ public int hashCode() {
249+ return Objects.hashCode(start, end);
250+ }
251+
252+ @Override
253+ public String toString() {
254+ return String.format("]%s, %s]", start, end);
255+ }
256+
257+ @Override public int compareTo(TokenRange other) {
258+ if(this.equals(other)) {
259+ return 0;
260+ } else {
261+ int compareStart = this.start.compareTo(other.start);
262+ return compareStart != 0 ? compareStart : this.end.compareTo(other.end);
263+ }
264+ }
265+}
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +4 −0
@@ -11,4 +11,8 @@
1111 public static SessionAssert assertThat(Session session) {
1212 return new SessionAssert(session);
1313 }
14+
15+ public static TokenRangeAssert assertThat(TokenRange range) {
16+ return new TokenRangeAssert(range);
17+ }
1418 }
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +8 −2
@@ -20,6 +20,7 @@
2020 import com.datastax.driver.core.exceptions.DriverException;
2121 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2222
23+import com.google.common.base.Joiner;
2324 import com.google.common.io.Files;
2425 import org.slf4j.Logger;
2526 import org.slf4j.LoggerFactory;
@@ -88,11 +89,11 @@
8889 return bridge;
8990 }
9091
91- public static CCMBridge create(String name, int nbNodes) {
92+ public static CCMBridge create(String name, int nbNodes, String... options) {
9293 checkArgument(!"current".equals(name.toLowerCase()),
9394 "cluster can't be called \"current\"");
9495 CCMBridge bridge = new CCMBridge();
95- bridge.execute("ccm create %s -n %d -s -i %s -b %s", name, nbNodes, IP_PREFIX, CASSANDRA_VERSION);
96+ bridge.execute("ccm create %s -n %d -s -i %s -b %s " + Joiner.on(" ").join(options), name, nbNodes, IP_PREFIX, CASSANDRA_VERSION);
9697 return bridge;
9798 }
9899
@@ -149,6 +150,11 @@
149150 execute("ccm remove");
150151 }
151152
153+ public void remove(int n) {
154+ logger.info("Removing: " + IP_PREFIX + n);
155+ execute("ccm node%d remove", n);
156+ }
157+
152158 public void ring() {
153159 ring(1);
154160 }
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +61 −0
@@ -1,6 +1,12 @@
11 package com.datastax.driver.core;
22
3+import java.util.Iterator;
4+import java.util.Set;
5+import java.util.TreeSet;
6+
37 import static org.assertj.core.api.Assertions.assertThat;
8+
9+import com.google.common.collect.Iterators;
410 import org.assertj.core.api.AbstractAssert;
511
612 public class ClusterAssert extends AbstractAssert<ClusterAssert, Cluster> {
@@ -22,4 +28,59 @@
2228
2329 return new HostAssert(host, actual);
2430 }
31+
32+ /**
33+ * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s with the given keyspace.
34+ *
35+ * Ensures that no ranges intersect and that they cover the entire ring.
36+ * @param keyspace Keyspace to grab {@link TokenRange}s from.
37+ */
38+ public ClusterAssert hasValidTokenRanges(String keyspace) {
39+ // Sort the token ranges so they are in order (needed for vnodes).
40+ Set<TokenRange> ranges = new TreeSet<TokenRange>();
41+ for(Host host : actual.getMetadata().getAllHosts()) {
42+ ranges.addAll(actual.getMetadata().getTokenRanges(keyspace, host));
43+ }
44+ return hasValidTokenRanges(ranges);
45+ }
46+
47+ /**
48+ * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s.
49+ *
50+ * Ensures that no ranges intersect and that they cover the entire ring.
51+ */
52+ public ClusterAssert hasValidTokenRanges() {
53+ // Sort the token ranges so they are in order (needed for vnodes).
54+ Set<TokenRange> ranges = new TreeSet<TokenRange>(actual.getMetadata().getTokenRanges());
55+ return hasValidTokenRanges(ranges);
56+ }
57+
58+ /**
59+ * Asserts that given Set of {@link TokenRange}s are valid.
60+ *
61+ * Ensures that no ranges intersect and that they cover the entire ring.
62+ */
63+ private ClusterAssert hasValidTokenRanges(Set<TokenRange> ranges) {
64+ // Ensure no ranges intersect.
65+ Iterator<TokenRange> it = ranges.iterator();
66+ while(it.hasNext()) {
67+ TokenRange range = it.next();
68+ Assertions.assertThat(range).doesNotIntersect(Iterators.toArray(it, TokenRange.class));
69+ }
70+
71+ // Ensure the defined ranges cover the entire ring.
72+ it = ranges.iterator();
73+ TokenRange mergedRange = it.next();
74+ while(it.hasNext()) {
75+ TokenRange next = it.next();
76+ mergedRange = mergedRange.mergeWith(next);
77+ }
78+ boolean isFullRing = mergedRange.getStart().equals(mergedRange.getEnd())
79+ && !mergedRange.isEmpty();
80+ assertThat(isFullRing)
81+ .as("Ring is not fully defined for Cluster.")
82+ .isTrue();
83+
84+ return this;
85+ }
2586 }
added driver-core/src/test/java/com/datastax/driver/core/M3PTokenFactoryTest.java +79 −0
@@ -0,0 +1,79 @@
1+package com.datastax.driver.core;
2+
3+import java.util.List;
4+
5+import org.testng.annotations.Test;
6+
7+import static org.assertj.core.api.Assertions.assertThat;
8+import static org.testng.Assert.fail;
9+
10+public class M3PTokenFactoryTest {
11+ Token.Factory factory = Token.M3PToken.FACTORY;
12+
13+ @Test(groups = "unit")
14+ public void should_split_range() {
15+ List<Token> splits = factory.split(factory.fromString("-9223372036854775808"), factory.fromString("4611686018427387904"), 3);
16+ assertThat(splits).containsExactly(
17+ factory.fromString("-4611686018427387904"),
18+ factory.fromString("0")
19+ );
20+ }
21+
22+ @Test(groups = "unit")
23+ public void should_split_range_that_wraps_around_the_ring() {
24+ List<Token> splits = factory.split(factory.fromString("4611686018427387904"), factory.fromString("0"), 3);
25+ assertThat(splits).containsExactly(
26+ factory.fromString("-9223372036854775807"),
27+ factory.fromString("-4611686018427387903")
28+ );
29+ }
30+
31+ @Test(groups = "unit")
32+ public void should_split_range_when_division_not_integral() {
33+ List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("11"), 3);
34+ assertThat(splits).containsExactly(
35+ factory.fromString("4"),
36+ factory.fromString("8")
37+ );
38+ }
39+
40+ @Test(groups = "unit")
41+ public void should_split_range_producing_empty_splits() {
42+ List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("2"), 5);
43+ assertThat(splits).containsExactly(
44+ factory.fromString("1"),
45+ factory.fromString("2"),
46+ factory.fromString("2"),
47+ factory.fromString("2")
48+ );
49+ }
50+
51+ @Test(groups = "unit")
52+ public void should_split_range_producing_empty_splits_near_ring_end() {
53+ Token minToken = factory.fromString("-9223372036854775808");
54+ Token maxToken = factory.fromString("9223372036854775807");
55+
56+ // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring)
57+ List<Token> splits = factory.split(maxToken, minToken, 3);
58+ assertThat(splits).containsExactly(
59+ maxToken,
60+ maxToken
61+ );
62+
63+ splits = factory.split(minToken, factory.fromString("-9223372036854775807"), 3);
64+ assertThat(splits).containsExactly(
65+ factory.fromString("-9223372036854775807"),
66+ factory.fromString("-9223372036854775807")
67+ );
68+ }
69+
70+ @Test(groups = "unit")
71+ public void should_split_whole_ring() {
72+ List<Token> splits = factory.split(factory.fromString("-9223372036854775808"), factory.fromString("-9223372036854775808"), 3);
73+ assertThat(splits).containsExactly(
74+ factory.fromString("-3074457345618258603"),
75+ factory.fromString("3074457345618258602")
76+ );
77+ }
78+
79+}
No newline at the end of the file
added driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java +13 −0
@@ -0,0 +1,13 @@
1+package com.datastax.driver.core;
2+
3+import com.datastax.driver.core.Token.M3PToken;
4+
5+public class M3PTokenIntegrationTest extends TokenIntegrationTest {
6+ public M3PTokenIntegrationTest() {
7+ super("", DataType.bigint());
8+ }
9+
10+ @Override protected Token.Factory tokenFactory() {
11+ return M3PToken.FACTORY;
12+ }
13+}
added driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java +11 −0
@@ -0,0 +1,11 @@
1+package com.datastax.driver.core;
2+
3+public class M3PTokenVnodeIntegrationTest extends TokenIntegrationTest {
4+ public M3PTokenVnodeIntegrationTest() {
5+ super("", DataType.bigint(), true);
6+ }
7+
8+ @Override protected Token.Factory tokenFactory() {
9+ return Token.M3PToken.FACTORY;
10+ }
11+}
added driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +113 −0
@@ -0,0 +1,113 @@
1+package com.datastax.driver.core;
2+
3+import java.util.Map;
4+
5+import com.google.common.collect.Maps;
6+import org.testng.annotations.Test;
7+
8+import static com.datastax.driver.core.Assertions.assertThat;
9+import static com.datastax.driver.core.TestUtils.waitFor;
10+
11+public class MetadataTest {
12+
13+ /**
14+ * <p>
15+ * Validates that when the topology of the cluster changes that Cluster Metadata is properly updated.
16+ * </p>
17+ *
18+ * <p>
19+ * This test does the following:
20+ *
21+ * <ol>
22+ * <li>Creates a 3 node cluster and capture token range data from the {@link Cluster}'s {@link Metadata}</li>
23+ * <li>Decommission node 3.</li>
24+ * <li>Validates that the token range data was updated to reflect node 3 leaving and the other nodes
25+ * taking on its token range.</li>
26+ * <li>Adds a new node, node 4.</li>
27+ * <li>Validates that the token range data was updated to reflect node 4 joining the {@link Cluster} and
28+ * the token ranges reflecting this.</li>
29+ * </ol>
30+ *
31+ * @test_category metadata:token
32+ * @expected_result cluster metadata is properly updated in response to node remove and add events.
33+ * @jira_ticket JAVA-312
34+ * @since 2.0.10, 2.1.5
35+ */
36+ @Test(groups="long")
37+ public void should_update_metadata_on_topology_change() {
38+ CCMBridge ccm = null;
39+ Cluster cluster = null;
40+
41+ try {
42+ ccm = CCMBridge.create("test", 3);
43+
44+ cluster = Cluster.builder()
45+ .addContactPoint(CCMBridge.ipOfNode(1))
46+ .build();
47+ Session session = cluster.connect();
48+
49+ String keyspace = "test";
50+ session.execute("CREATE KEYSPACE IF NOT EXISTS " + keyspace + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
51+ Metadata metadata = cluster.getMetadata();
52+
53+ // Capture all Token data.
54+ assertThat(metadata.getTokenRanges()).hasSize(3);
55+ Map<Host, Token> tokensForHost = getTokenForHosts(metadata);
56+
57+ // Capture host3s token and range before we take it down.
58+ Host host3 = TestUtils.findHost(cluster, 3);
59+ Token host3Token = tokensForHost.get(host3);
60+
61+ ccm.decommissionNode(3);
62+ ccm.remove(3);
63+
64+ // Ensure that the token ranges were updated, there should only be 2 ranges now.
65+ assertThat(metadata.getTokenRanges()).hasSize(2);
66+
67+ // The token should not be present for any Host.
68+ assertThat(getTokenForHosts(metadata)).doesNotContainValue(host3Token);
69+
70+ // The ring should be fully accounted for.
71+ assertThat(cluster).hasValidTokenRanges("test");
72+ assertThat(cluster).hasValidTokenRanges();
73+
74+ // Add an additional node.
75+ ccm.bootstrapNode(4);
76+ waitFor(CCMBridge.IP_PREFIX + '4', cluster);
77+
78+ // Ensure that the token ranges were updated, there should only be 3 ranges now.
79+ assertThat(metadata.getTokenRanges()).hasSize(3);
80+
81+ Host host4 = TestUtils.findHost(cluster, 4);
82+ TokenRange host4Range = metadata.getTokenRanges(keyspace, host4).iterator().next();
83+
84+ // Ensure no host token range intersects with node 4.
85+ for(Host host : metadata.getAllHosts()) {
86+ if(!host.equals(host4)) {
87+ TokenRange hostRange = metadata.getTokenRanges(keyspace, host).iterator().next();
88+ assertThat(host4Range).doesNotIntersect(hostRange);
89+ }
90+ }
91+
92+ // The ring should be fully accounted for.
93+ assertThat(cluster).hasValidTokenRanges("test");
94+ assertThat(cluster).hasValidTokenRanges();
95+ } finally {
96+ if (cluster != null)
97+ cluster.close();
98+ if (ccm != null)
99+ ccm.remove();
100+ }
101+ }
102+
103+ /**
104+ * @return A mapping of Host -> Token for each Host in the given {@link Metadata}
105+ */
106+ private Map<Host, Token> getTokenForHosts(Metadata metadata) {
107+ Map<Host, Token> tokensByHost = Maps.newHashMap();
108+ for(Host host : metadata.getAllHosts()) {
109+ tokensByHost.put(host, host.getTokens().iterator().next());
110+ }
111+ return tokensByHost;
112+ }
113+}
added driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java +88 −0
@@ -0,0 +1,88 @@
1+package com.datastax.driver.core;
2+
3+import java.math.BigInteger;
4+import java.nio.ByteBuffer;
5+import java.util.List;
6+
7+import org.testng.annotations.Test;
8+
9+import static org.assertj.core.api.Assertions.assertThat;
10+import static org.testng.Assert.fail;
11+
12+public class OPPTokenFactoryTest {
13+ private static final Token.Factory factory = Token.OPPToken.FACTORY;
14+
15+ private static final Token minToken = token(ByteBuffer.allocate(0));
16+
17+ @Test(groups = "unit")
18+ public void should_split_range() {
19+ List<Token> splits = factory.split(token('a'), token('d'), 3);
20+ assertThat(splits).containsExactly(
21+ token('b'),
22+ token('c')
23+ );
24+ }
25+
26+ @Test(groups = "unit")
27+ public void should_split_range_producing_empty_splits_near_ring_end() {
28+ // the first token following min
29+ ByteBuffer buffer = ByteBuffer.wrap(new byte[]{ 0 });
30+ Token zero = token(buffer);
31+
32+ // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring)
33+ List<Token> splits = factory.split(minToken, zero, 3);
34+ assertThat(splits).containsExactly(
35+ zero,
36+ zero
37+ );
38+ }
39+
40+ @Test(groups = "unit")
41+ public void should_strip_trailing_0_bytes() {
42+ Token with0Bytes = token(ByteBuffer.wrap(new byte[]{ 4, 0, 0, 0 }));
43+ Token without0Bytes = token(ByteBuffer.wrap(new byte[]{ 4 }));
44+ Token fromStringWith0Bytes = factory.fromString("040000");
45+
46+ assertThat(with0Bytes)
47+ .isEqualTo(without0Bytes)
48+ .isEqualTo(fromStringWith0Bytes);
49+
50+ Token withMixed0Bytes = factory.fromString("0004000400");
51+ Token withoutMixed0Bytes = factory.fromString("00040004");
52+
53+ assertThat(withMixed0Bytes)
54+ .isEqualTo(withoutMixed0Bytes);
55+ }
56+
57+ @Test(groups = "unit")
58+ public void should_split_range_that_wraps_around_the_ring() {
59+ for(int start = 1; start < 128; start++) {
60+ for(int end = start; end < start; end++) {
61+ // Take the midpoint of the ring and offset by the midpoint of start+end.
62+ long expected = 0x81 + ((start + end) / 2);
63+ TokenRange tr = new TokenRange(token(start), token(end), factory);
64+ assertThat(factory.split(tr.getStart(), tr.getEnd(), 2))
65+ .as("Expected 0x%X for start: %d, end: %d", expected, start, end)
66+ .containsExactly(token(expected));
67+ }
68+ }
69+ }
70+
71+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
72+ public void should_not_be_allowed_to_split_with_min_token() {
73+ factory.split(minToken, minToken, 1);
74+ }
75+
76+ private static Token token(char c) {
77+ return new Token.OPPToken(ByteBuffer.wrap(new byte[]{ (byte)c }));
78+ }
79+
80+ private static Token token(long i) {
81+ return new Token.OPPToken(ByteBuffer.wrap(BigInteger.valueOf(i).toByteArray()));
82+ }
83+
84+ private static Token token(ByteBuffer buffer) {
85+ // note - protocol version is ignored in OPPFactory, so we actually don't care about the value
86+ return factory.deserialize(buffer, ProtocolVersion.NEWEST_SUPPORTED);
87+ }
88+}
added driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java +13 −0
@@ -0,0 +1,13 @@
1+package com.datastax.driver.core;
2+
3+import com.datastax.driver.core.Token.OPPToken;
4+
5+public class OPPTokenIntegrationTest extends TokenIntegrationTest {
6+ public OPPTokenIntegrationTest() {
7+ super("-p ByteOrderedPartitioner", DataType.blob());
8+ }
9+
10+ @Override protected Token.Factory tokenFactory() {
11+ return OPPToken.FACTORY;
12+ }
13+}
added driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java +11 −0
@@ -0,0 +1,11 @@
1+package com.datastax.driver.core;
2+
3+public class OPPTokenVnodeIntegrationTest extends TokenIntegrationTest {
4+ public OPPTokenVnodeIntegrationTest() {
5+ super("-p ByteOrderedPartitioner", DataType.blob(), true);
6+ }
7+
8+ @Override protected Token.Factory tokenFactory() {
9+ return Token.OPPToken.FACTORY;
10+ }
11+}
added driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java +62 −0
@@ -0,0 +1,62 @@
1+package com.datastax.driver.core;
2+
3+import java.util.List;
4+
5+import org.testng.annotations.Test;
6+
7+import static org.assertj.core.api.Assertions.assertThat;
8+import static org.testng.Assert.fail;
9+
10+public class RPTokenFactoryTest {
11+ Token.Factory factory = Token.RPToken.FACTORY;
12+
13+ @Test(groups = "unit")
14+ public void should_split_range() {
15+ List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("127605887595351923798765477786913079296"), 3);
16+ assertThat(splits).containsExactly(
17+ factory.fromString("42535295865117307932921825928971026432"),
18+ factory.fromString("85070591730234615865843651857942052864")
19+ );
20+ }
21+
22+ @Test(groups = "unit")
23+ public void should_split_range_that_wraps_around_the_ring() {
24+ List<Token> splits = factory.split(
25+ factory.fromString("127605887595351923798765477786913079296"),
26+ factory.fromString("85070591730234615865843651857942052864"),
27+ 3);
28+
29+ assertThat(splits).containsExactly(
30+ factory.fromString("0"),
31+ factory.fromString("42535295865117307932921825928971026432")
32+ );
33+ }
34+
35+ @Test(groups = "unit")
36+ public void should_split_range_producing_empty_splits_near_ring_end() {
37+ Token minToken = factory.fromString("-1");
38+ Token maxToken = factory.fromString("170141183460469231731687303715884105728");
39+
40+ // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring)
41+ List<Token> splits = factory.split(maxToken, minToken, 3);
42+ assertThat(splits).containsExactly(
43+ maxToken,
44+ maxToken
45+ );
46+
47+ splits = factory.split(minToken, factory.fromString("0"), 3);
48+ assertThat(splits).containsExactly(
49+ factory.fromString("0"),
50+ factory.fromString("0")
51+ );
52+ }
53+
54+ @Test(groups = "unit")
55+ public void should_split_whole_ring() {
56+ List<Token> splits = factory.split(factory.fromString("-1"), factory.fromString("-1"), 3);
57+ assertThat(splits).containsExactly(
58+ factory.fromString("56713727820156410577229101238628035242"),
59+ factory.fromString("113427455640312821154458202477256070485")
60+ );
61+ }
62+}
added driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java +13 −0
@@ -0,0 +1,13 @@
1+package com.datastax.driver.core;
2+
3+import com.datastax.driver.core.Token.RPToken;
4+
5+public class RPTokenIntegrationTest extends TokenIntegrationTest {
6+ public RPTokenIntegrationTest() {
7+ super("-p RandomPartitioner", DataType.varint());
8+ }
9+
10+ @Override protected Token.Factory tokenFactory() {
11+ return RPToken.FACTORY;
12+ }
13+}
added driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java +11 −0
@@ -0,0 +1,11 @@
1+package com.datastax.driver.core;
2+
3+public class RPTokenVnodeIntegrationTest extends TokenIntegrationTest {
4+ public RPTokenVnodeIntegrationTest() {
5+ super("-p RandomPartitioner", DataType.varint(), true);
6+ }
7+
8+ @Override protected Token.Factory tokenFactory() {
9+ return Token.RPToken.FACTORY;
10+ }
11+}
added driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +352 −0
@@ -0,0 +1,352 @@
1+package com.datastax.driver.core;
2+
3+import java.net.InetSocketAddress;
4+import java.util.*;
5+
6+import com.google.common.base.Function;
7+import com.google.common.collect.Iterables;
8+import com.google.common.collect.Lists;
9+import org.testng.annotations.AfterClass;
10+import org.testng.annotations.BeforeClass;
11+import org.testng.annotations.Test;
12+
13+import com.datastax.driver.core.exceptions.InvalidTypeException;
14+import com.datastax.driver.core.policies.LoadBalancingPolicy;
15+import com.datastax.driver.core.policies.RoundRobinPolicy;
16+import com.datastax.driver.core.policies.WhiteListPolicy;
17+
18+import static com.datastax.driver.core.Assertions.assertThat;
19+
20+/**
21+ * This class uses subclasses for each type of partitioner.
22+ *
23+ * There's normally a way to parametrize a TestNG class with @Factory and @DataProvider,
24+ * but it doesn't seem to work with multiple methods.
25+ */
26+public abstract class TokenIntegrationTest {
27+
28+ List<String> schema = Lists.newArrayList(
29+ "CREATE KEYSPACE IF NOT EXISTS test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}",
30+ "CREATE KEYSPACE IF NOT EXISTS test2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}",
31+ "USE test",
32+ "CREATE TABLE IF NOT EXISTS foo(i int primary key)",
33+ "INSERT INTO foo (i) VALUES (1)",
34+ "INSERT INTO foo (i) VALUES (2)",
35+ "INSERT INTO foo (i) VALUES (3)",
36+ "CREATE TABLE IF NOT EXISTS foo2(\"caseSensitiveKey\" int primary key)",
37+ "INSERT INTO foo2 (\"caseSensitiveKey\") VALUES (1)"
38+ );
39+
40+ private final String ccmOptions;
41+ private final DataType expectedTokenType;
42+ private final int numTokens;
43+ private final boolean useVnodes;
44+ CCMBridge ccm;
45+ Cluster cluster;
46+ Session session;
47+
48+ public TokenIntegrationTest(String ccmOptions, DataType expectedTokenType) {
49+ this(ccmOptions, expectedTokenType, false);
50+ }
51+
52+ public TokenIntegrationTest(String ccmOptions, DataType expectedTokenType, boolean useVnodes) {
53+ this.expectedTokenType = expectedTokenType;
54+ this.numTokens = useVnodes ? 256 : 1;
55+ this.ccmOptions = useVnodes ? ccmOptions + " --vnodes" : ccmOptions;
56+ this.useVnodes = useVnodes;
57+ }
58+
59+ @BeforeClass(groups = "short")
60+ public void setup() {
61+ ccm = CCMBridge.create("test", 3, ccmOptions);
62+
63+ // Only connect to node 1, which makes it easier to query system tables in should_expose_tokens_per_host()
64+ LoadBalancingPolicy lbp = new WhiteListPolicy(new RoundRobinPolicy(),
65+ Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(1), 9042)));
66+
67+ cluster = Cluster.builder()
68+ .addContactPoints(CCMBridge.ipOfNode(1))
69+ .withLoadBalancingPolicy(lbp)
70+ .build();
71+ cluster.init();
72+ session = cluster.connect();
73+
74+ for (String statement : schema)
75+ session.execute(statement);
76+ }
77+
78+ @AfterClass(groups = "short")
79+ public void teardown() {
80+ if (cluster != null)
81+ cluster.close();
82+ if (ccm != null)
83+ ccm.remove();
84+ }
85+
86+ /**
87+ * <p>
88+ * Validates that {@link TokenRange}s are exposed via a {@link Cluster}'s {@link Metadata} and they
89+ * can be used to query data.
90+ * </p>
91+ *
92+ * @test_category metadata:token
93+ * @expected_result token ranges are exposed and usable.
94+ * @jira_ticket JAVA-312
95+ * @since 2.0.10, 2.1.5
96+ */
97+ @Test(groups = "short")
98+ public void should_expose_token_ranges() throws Exception {
99+ Metadata metadata = cluster.getMetadata();
100+
101+ // Find the replica for a given partition key
102+ int testKey = 1;
103+ Set<Host> replicas = metadata.getReplicas("test", DataType.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum()));
104+ assertThat(replicas).hasSize(1);
105+ Host replica = replicas.iterator().next();
106+
107+ // Iterate the cluster's token ranges. For each one, use a range query to ask Cassandra which partition keys
108+ // are in this range.
109+ TokenRange foundRange = null;
110+ for (TokenRange range : metadata.getTokenRanges()) {
111+ List<Row> rows = rangeQuery("SELECT i FROM foo WHERE token(i) > ? and token(i) <= ?", range);
112+ for (Row row : rows) {
113+ if (row.getInt("i") == testKey) {
114+ // We should find our test key exactly once
115+ assertThat(foundRange)
116+ .describedAs("found the same key in two ranges: " + foundRange + " and " + range)
117+ .isNull();
118+ foundRange = range;
119+ // That range should be managed by the replica
120+ assertThat(metadata.getReplicas("test", range)).contains(replica);
121+ }
122+ }
123+ }
124+ assertThat(foundRange).isNotNull();
125+ }
126+
127+ private List<Row> rangeQuery(String query, TokenRange range) {
128+ List<Row> rows = Lists.newArrayList();
129+ for (TokenRange subRange : range.unwrap()) {
130+ rows.addAll(session.execute(query,
131+ subRange.getStart(), subRange.getEnd())
132+ .all());
133+ }
134+ return rows;
135+ }
136+
137+ /**
138+ * <p>
139+ * Validates that a {@link Token} can be retrieved and parsed by executing 'select token(name)' and
140+ * then used to find data matching that token.
141+ * </p>
142+ *
143+ * <p>
144+ * This test does the following:
145+ *
146+ * <ol>
147+ * <li>Retrieve the token for the key with value '1', get it by index, and ensure if is of the expected token type.</li>
148+ * <li>Retrieve the token for the key with value '1', get it by name, and ensure it matches the token by index.</li>
149+ * <li>Retrieve the token by alias for the key '1', and ensure it matches the token by index.</li>
150+ * <li>Retrieve the token for a case sensitive key.</li>
151+ * <li>Select data by token with a BoundStatement.</li>
152+ * <li>Select data by token using setToken by index.</li>
153+ * <li>Select data by token using setToken by name.</li>
154+ * <li>Select data by token with a SimpleStatement</li>
155+ * </ol>
156+ *
157+ * @test_category token
158+ * @expected_result tokens are selectable, properly parsed, and usable as input.
159+ * @jira_ticket JAVA-312
160+ * @since 2.0.10, 2.1.5
161+ */
162+ @Test(groups = "short")
163+ public void should_get_token_from_row_and_set_token_in_query() {
164+ // get by index:
165+ Row row = session.execute("SELECT token(i) FROM test.foo WHERE i = 1").one();
166+ Token token = row.getToken(0);
167+ assertThat(token.getType()).isEqualTo(expectedTokenType);
168+
169+ // get by "base" column name (will add token() around it):
170+ assertThat(
171+ row.getToken("i")
172+ ).isEqualTo(token);
173+
174+ // get by name:
175+ assertThat(
176+ session.execute("SELECT token(i) AS t FROM test.foo WHERE i = 1").one()
177+ .getToken("t")
178+ ).isEqualTo(token);
179+
180+ // get by "base" column name when it's case-sensitive
181+ session.execute("SELECT token(\"caseSensitiveKey\") FROM test.foo2 WHERE \"caseSensitiveKey\" = 1").one()
182+ .getToken("\"caseSensitiveKey\"");
183+
184+
185+ PreparedStatement pst = session.prepare("SELECT * FROM test.foo WHERE token(i) = ?");
186+ row = session.execute(pst.bind(token)).one();
187+ assertThat(row.getInt(0)).isEqualTo(1);
188+
189+ row = session.execute(pst.bind().setToken(0, token)).one();
190+ assertThat(row.getInt(0)).isEqualTo(1);
191+
192+ PreparedStatement pst2 = session.prepare("SELECT * FROM test.foo WHERE token(i) = :myToken");
193+ row = session.execute(pst2.bind().setToken("myToken", token)).one();
194+ assertThat(row.getInt(0)).isEqualTo(1);
195+
196+ row = session.execute("SELECT * FROM test.foo WHERE token(i) = ?", token).one();
197+ assertThat(row.getInt(0)).isEqualTo(1);
198+ }
199+
200+ /**
201+ * <p>
202+ * Ensures that an exception is raised when attempting to retrieve a token a non-token column.
203+ * </p>
204+ *
205+ * @test_category token
206+ * @expected_result an exception is raised.
207+ * @jira_ticket JAVA-312
208+ * @since 2.0.10, 2.1.5
209+ */
210+ @Test(groups = "short", expectedExceptions = InvalidTypeException.class)
211+ public void should_raise_exception_when_get_token_on_non_token() {
212+ Row row = session.execute("SELECT i FROM test.foo WHERE i = 1").one();
213+ row.getToken(0);
214+ }
215+
216+ /**
217+ * <p>
218+ * Ensures that @{link TokenRange}s are exposed at a per host level, the ranges are complete,
219+ * the entire ring is represented, and that ranges do not overlap.
220+ * </p>
221+ *
222+ * <p>
223+ * Also ensures that ranges from another replica are present when a Host is a replica for
224+ * another node.
225+ * </p>
226+ *
227+ * @test_category metadata:token
228+ * @expected_result The entire token range is represented collectively and the ranges do not overlap.
229+ * @jira_ticket JAVA-312
230+ * @since 2.0.10, 2.1.5
231+ */
232+ @Test(groups = "short")
233+ public void should_expose_token_ranges_per_host() {
234+ checkRangesPerHost("test", 1);
235+ checkRangesPerHost("test2", 2);
236+ assertThat(cluster).hasValidTokenRanges();
237+ }
238+
239+ private void checkRangesPerHost(String keyspace, int replicationFactor) {
240+ List<TokenRange> allRangesWithReplicas = Lists.newArrayList();
241+
242+ // Get each host's ranges, the count should match the replication factor
243+ for (int i = 1; i <= 3; i++) {
244+ Host host = TestUtils.findHost(cluster, i);
245+ Set<TokenRange> hostRanges = cluster.getMetadata().getTokenRanges(keyspace, host);
246+ // Special case: When using vnodes the tokens are not evenly assigned to each replica.
247+ if(!useVnodes) {
248+ assertThat(hostRanges).hasSize(replicationFactor * numTokens);
249+ }
250+ allRangesWithReplicas.addAll(hostRanges);
251+ }
252+
253+ // Special case check for vnodes to ensure that total number of replicated ranges is correct.
254+ assertThat(allRangesWithReplicas).hasSize(3 * numTokens * replicationFactor);
255+
256+ // Once we ignore duplicates, the number of ranges should match the number of nodes.
257+ Set<TokenRange> allRanges = new HashSet<TokenRange>(allRangesWithReplicas);
258+ assertThat(allRanges).hasSize(3*numTokens);
259+
260+ // And the ranges should cover the whole ring and no ranges intersect.
261+ assertThat(cluster).hasValidTokenRanges(keyspace);
262+ }
263+
264+ /**
265+ * <p>
266+ * Ensures that Tokens are exposed for each Host and that the match those in the system tables.
267+ * </p>
268+ *
269+ * <p>
270+ * Also validates that tokens are not present for multiple hosts.
271+ * </p>
272+ *
273+ * @test_category metadata:token
274+ * @expected_result Tokens are exposed by Host and match those in the system tables.
275+ * @jira_ticket JAVA-312
276+ * @since 2.0.10, 2.1.5
277+ */
278+ @Test(groups = "short")
279+ public void should_expose_tokens_per_host() {
280+ for (Host host : cluster.getMetadata().allHosts()) {
281+ assertThat(host.getTokens()).hasSize(numTokens);
282+
283+ // Check against the info in the system tables, which is a bit weak since it's exactly how the metadata is
284+ // constructed in the first place, but there's not much else we can do.
285+ // Note that this relies on all queries going to node 1, which is why we use a WhiteList LBP in setup().
286+ Row row = (host.listenAddress == null)
287+ ? session.execute("select tokens from system.local").one()
288+ : session.execute("select tokens from system.peers where peer = ?", host.listenAddress).one();
289+ Set<String> tokenStrings = row.getSet("tokens", String.class);
290+ assertThat(tokenStrings).hasSize(numTokens);
291+ Iterable<Token> tokensFromSystemTable = Iterables.transform(tokenStrings, new Function<String, Token>() {
292+ @Override public Token apply(String input) {
293+ return tokenFactory().fromString(input);
294+ }
295+ });
296+
297+ assertThat(host.getTokens()).containsOnlyOnce(Iterables.toArray(tokensFromSystemTable, Token.class));
298+ }
299+ }
300+
301+ /**
302+ * <p>
303+ * Ensures that for the {@link TokenRange}s returned by {@link Metadata#getTokenRanges()} that there exists at
304+ * most one {@link TokenRange} for which calling {@link TokenRange#isWrappedAround()} returns true and
305+ * {@link TokenRange#unwrap()} returns two {@link TokenRange}s.
306+ * </p>
307+ *
308+ * @test_category metadata:token
309+ * @expected_result Tokens are exposed by Host and match those in the system tables.
310+ * @jira_ticket JAVA-312
311+ * @since 2.0.10, 2.1.5
312+ */
313+ @Test(groups = "short")
314+ public void should_only_unwrap_one_range_for_all_ranges() {
315+ Set<TokenRange> ranges = cluster.getMetadata().getTokenRanges();
316+
317+ assertOnlyOneWrapped(ranges);
318+
319+ Iterable<TokenRange> splitRanges = Iterables.concat(Iterables.transform(ranges,
320+ new Function<TokenRange, Iterable<TokenRange>>() {
321+ @Override public Iterable<TokenRange> apply(TokenRange input) {
322+ return input.splitEvenly(10);
323+ }
324+ })
325+ );
326+
327+ assertOnlyOneWrapped(splitRanges);
328+ }
329+
330+ /**
331+ * Asserts that given the input {@link TokenRange}s that at most one of them wraps the token ring.
332+ * @param ranges Ranges to validate against.
333+ */
334+ protected void assertOnlyOneWrapped(Iterable<TokenRange> ranges) {
335+ TokenRange wrappedRange = null;
336+
337+ for(TokenRange range : ranges) {
338+ if(range.isWrappedAround()) {
339+ assertThat(wrappedRange)
340+ .as("Found a wrapped around TokenRange (%s) when one already exists (%s).", range, wrappedRange)
341+ .isNull();
342+ wrappedRange = range;
343+
344+ assertThat(range).unwrapsOverMinToken(tokenFactory());
345+ } else {
346+ assertThat(range).unwrapsToItself();
347+ }
348+ }
349+ }
350+
351+ protected abstract Token.Factory tokenFactory();
352+}
added driver-core/src/test/java/com/datastax/driver/core/TokenRangeAssert.java +62 −0
@@ -0,0 +1,62 @@
1+package com.datastax.driver.core;
2+
3+import java.util.Iterator;
4+import java.util.List;
5+
6+import org.assertj.core.api.AbstractAssert;
7+
8+import static org.assertj.core.api.Assertions.assertThat;
9+
10+public class TokenRangeAssert extends AbstractAssert<TokenRangeAssert, TokenRange> {
11+ protected TokenRangeAssert(TokenRange actual) {
12+ super(actual, TokenRangeAssert.class);
13+ }
14+
15+ public TokenRangeAssert intersects(TokenRange that) {
16+ assertThat(actual.intersects(that))
17+ .as("%s should intersect %s", actual, that)
18+ .isTrue();
19+ assertThat(that.intersects(actual))
20+ .as("%s should intersect %s", that, actual)
21+ .isTrue();
22+ return this;
23+ }
24+
25+ public TokenRangeAssert doesNotIntersect(TokenRange ... that) {
26+ for(TokenRange thatRange : that) {
27+ assertThat(actual.intersects(thatRange))
28+ .as("%s should not intersect %s", actual, thatRange)
29+ .isFalse();
30+ assertThat(thatRange.intersects(actual))
31+ .as("%s should not intersect %s", thatRange, actual)
32+ .isFalse();
33+ }
34+ return this;
35+ }
36+
37+ public TokenRangeAssert unwrapsToItself() {
38+ assertThat(actual.unwrap()).containsExactly(actual);
39+ return this;
40+ }
41+
42+ public TokenRangeAssert unwrapsOverMinToken(Token.Factory factory) {
43+ List<TokenRange> unwrapped = actual.unwrap();
44+ assertThat(unwrapped.size())
45+ .as("%s should unwrap to two ranges, but unwrapped to %s", actual, unwrapped)
46+ .isEqualTo(2);
47+
48+ Iterator<TokenRange> unwrappedIt = unwrapped.iterator();
49+ TokenRange firstRange = unwrappedIt.next();
50+ assertThat(firstRange.getEnd()).isEqualTo(factory.minToken());
51+
52+ TokenRange secondRange = unwrappedIt.next();
53+ assertThat(secondRange.getStart()).isEqualTo(factory.minToken());
54+
55+ return this;
56+ }
57+
58+ public TokenRangeAssert unwrapsTo(TokenRange... subRanges) {
59+ assertThat(actual.unwrap()).containsExactly(subRanges);
60+ return this;
61+ }
62+}
added driver-core/src/test/java/com/datastax/driver/core/TokenRangeTest.java +212 −0
@@ -0,0 +1,212 @@
1+package com.datastax.driver.core;
2+
3+import java.math.BigInteger;
4+import java.util.List;
5+
6+import org.testng.annotations.Test;
7+
8+import static org.testng.Assert.fail;
9+
10+import com.datastax.driver.core.Token.M3PToken;
11+
12+import static com.datastax.driver.core.Assertions.assertThat;
13+
14+public class TokenRangeTest {
15+ // The tests in this class don't depend on the kind of factory used, so use Murmur3 everywhere
16+ Token.Factory factory = Token.getFactory("Murmur3Partitioner");
17+ private Token minToken = factory.minToken();
18+
19+ @Test(groups = "unit")
20+ public void should_check_intersection() {
21+ // NB - to make the test more visual, we use watch face numbers
22+ assertThat(tokenRange(3, 9))
23+ .doesNotIntersect(tokenRange(11, 1))
24+ .doesNotIntersect(tokenRange(1, 2))
25+ .doesNotIntersect(tokenRange(11, 3))
26+ .doesNotIntersect(tokenRange(2, 3))
27+ .doesNotIntersect(tokenRange(3, 3))
28+ .intersects(tokenRange(2, 6))
29+ .intersects(tokenRange(2, 10))
30+ .intersects(tokenRange(6, 10))
31+ .intersects(tokenRange(4, 8))
32+ .intersects(tokenRange(3, 9))
33+ .doesNotIntersect(tokenRange(9, 10))
34+ .doesNotIntersect(tokenRange(10, 11))
35+ ;
36+ assertThat(tokenRange(9, 3))
37+ .doesNotIntersect(tokenRange(5, 7))
38+ .doesNotIntersect(tokenRange(7, 8))
39+ .doesNotIntersect(tokenRange(5, 9))
40+ .doesNotIntersect(tokenRange(8, 9))
41+ .doesNotIntersect(tokenRange(9, 9))
42+ .intersects(tokenRange(8, 2))
43+ .intersects(tokenRange(8, 4))
44+ .intersects(tokenRange(2, 4))
45+ .intersects(tokenRange(10, 2))
46+ .intersects(tokenRange(9, 3))
47+ .doesNotIntersect(tokenRange(3, 4))
48+ .doesNotIntersect(tokenRange(4, 5))
49+ ;
50+ assertThat(tokenRange(3, 3)).doesNotIntersect(tokenRange(3, 3));
51+
52+ // Reminder: minToken serves as both lower and upper bound
53+ assertThat(tokenRange(minToken, 5))
54+ .doesNotIntersect(tokenRange(6, 7))
55+ .doesNotIntersect(tokenRange(6, minToken))
56+ .intersects(tokenRange(6, 4))
57+ .intersects(tokenRange(2, 4))
58+ .intersects(tokenRange(minToken, 4))
59+ .intersects(tokenRange(minToken, 5))
60+ ;
61+
62+ assertThat(tokenRange(5, minToken))
63+ .doesNotIntersect(tokenRange(3, 4))
64+ .doesNotIntersect(tokenRange(minToken, 4))
65+ .intersects(tokenRange(6, 7))
66+ .intersects(tokenRange(4, 1))
67+ .intersects(tokenRange(6, minToken))
68+ .intersects(tokenRange(5, minToken))
69+ ;
70+
71+ assertThat(tokenRange(minToken, minToken))
72+ .intersects(tokenRange(3, 4))
73+ .intersects(tokenRange(3, minToken))
74+ .intersects(tokenRange(minToken, 3))
75+ .doesNotIntersect(tokenRange(3, 3))
76+ ;
77+ }
78+
79+ @Test(groups = "unit")
80+ public void should_merge_with_other_range() {
81+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(2, 3))).isEqualTo(tokenRange(2, 9));
82+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(2, 4))).isEqualTo(tokenRange(2, 9));
83+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(11, 3))).isEqualTo(tokenRange(11, 9));
84+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(11, 4))).isEqualTo(tokenRange(11, 9));
85+
86+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(4, 8))).isEqualTo(tokenRange(3, 9));
87+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(3, 9))).isEqualTo(tokenRange(3, 9));
88+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(3, 3))).isEqualTo(tokenRange(3, 9));
89+ assertThat(tokenRange(3, 3).mergeWith(tokenRange(3, 9))).isEqualTo(tokenRange(3, 9));
90+
91+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(9, 11))).isEqualTo(tokenRange(3, 11));
92+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(8, 11))).isEqualTo(tokenRange(3, 11));
93+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(9, 1))).isEqualTo(tokenRange(3, 1));
94+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(8, 1))).isEqualTo(tokenRange(3, 1));
95+
96+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(9, 3))).isEqualTo(tokenRange(minToken, minToken));
97+ assertThat(tokenRange(3, 9).mergeWith(tokenRange(9, 4))).isEqualTo(tokenRange(minToken, minToken));
98+ assertThat(tokenRange(3, 10).mergeWith(tokenRange(9, 4))).isEqualTo(tokenRange(minToken, minToken));
99+
100+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(8, 9))).isEqualTo(tokenRange(8, 3));
101+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(8, 10))).isEqualTo(tokenRange(8, 3));
102+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(4, 9))).isEqualTo(tokenRange(4, 3));
103+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(4, 10))).isEqualTo(tokenRange(4, 3));
104+
105+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(10, 2))).isEqualTo(tokenRange(9, 3));
106+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(9, 3))).isEqualTo(tokenRange(9, 3));
107+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(9, 9))).isEqualTo(tokenRange(9, 3));
108+ assertThat(tokenRange(9, 9).mergeWith(tokenRange(9, 3))).isEqualTo(tokenRange(9, 3));
109+
110+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(3, 5))).isEqualTo(tokenRange(9, 5));
111+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(2, 5))).isEqualTo(tokenRange(9, 5));
112+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(3, 7))).isEqualTo(tokenRange(9, 7));
113+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(2, 7))).isEqualTo(tokenRange(9, 7));
114+
115+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(3, 9))).isEqualTo(tokenRange(minToken, minToken));
116+ assertThat(tokenRange(9, 3).mergeWith(tokenRange(3, 10))).isEqualTo(tokenRange(minToken, minToken));
117+
118+ assertThat(tokenRange(3, 3).mergeWith(tokenRange(3, 3))).isEqualTo(tokenRange(3, 3));
119+
120+ assertThat(tokenRange(5, minToken).mergeWith(tokenRange(6, 7))).isEqualTo(tokenRange(5, minToken));
121+ assertThat(tokenRange(5, minToken).mergeWith(tokenRange(minToken, 3))).isEqualTo(tokenRange(5, 3));
122+ assertThat(tokenRange(5, minToken).mergeWith(tokenRange(3, 5))).isEqualTo(tokenRange(3, minToken));
123+
124+ assertThat(tokenRange(minToken, 5).mergeWith(tokenRange(2, 3))).isEqualTo(tokenRange(minToken, 5));
125+ assertThat(tokenRange(minToken, 5).mergeWith(tokenRange(7, minToken))).isEqualTo(tokenRange(7, 5));
126+ assertThat(tokenRange(minToken, 5).mergeWith(tokenRange(5, 7))).isEqualTo(tokenRange(minToken, 7));
127+ }
128+
129+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
130+ public void should_not_merge_with_nonadjacent_and_disjoint_ranges() {
131+ tokenRange(0,5).mergeWith(tokenRange(7,14));
132+ }
133+
134+ @Test(groups = "unit")
135+ public void should_return_non_empty_range_if_other_range_is_empty() {
136+ assertThat(tokenRange(1,5).mergeWith(tokenRange(5,5))).isEqualTo(tokenRange(1,5));
137+ }
138+
139+ @Test(groups = "unit")
140+ public void should_unwrap_to_non_wrapping_ranges() {
141+ assertThat(tokenRange(9, 3)).unwrapsTo(tokenRange(9, minToken), tokenRange(minToken, 3));
142+ assertThat(tokenRange(3, 9)).unwrapsToItself();
143+ assertThat(tokenRange(3, minToken)).unwrapsToItself();
144+ assertThat(tokenRange(minToken, 3)).unwrapsToItself();
145+ assertThat(tokenRange(3, 3)).unwrapsToItself();
146+ assertThat(tokenRange(minToken, minToken)).unwrapsToItself();
147+ }
148+
149+ @Test(groups = "unit")
150+ public void should_split_evenly() {
151+ // Simply exercise splitEvenly, split logic is exercised in TokenFactoryTest implementation for each partitioner.
152+ List<TokenRange> splits = tokenRange(3, 9).splitEvenly(3);
153+
154+ assertThat(splits).hasSize(3);
155+ assertThat(splits).containsExactly(tokenRange(3, 5), tokenRange(5, 7), tokenRange(7, 9));
156+ }
157+
158+
159+ @Test(groups = "unit")
160+ public void should_throw_error_with_less_than_1_splits() {
161+ for(int i = -255; i < 1; i++) {
162+ try {
163+ tokenRange(0, 1).splitEvenly(i);
164+ fail("Expected error when providing " + i + " splits.");
165+ } catch(IllegalArgumentException e) {
166+ // expected.
167+ }
168+ }
169+ }
170+
171+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
172+ public void should_not_split_empty_token_range() {
173+ tokenRange(0, 0).splitEvenly(1);
174+ }
175+
176+ @Test(groups = "unit")
177+ public void should_create_empty_token_ranges_if_too_many_splits() {
178+ TokenRange range = tokenRange(0,10);
179+
180+ List<TokenRange> ranges = range.splitEvenly(255);
181+ assertThat(ranges).hasSize(255);
182+
183+ for(int i = 0; i < ranges.size(); i++) {
184+ TokenRange tr = ranges.get(i);
185+ if(i < 10) {
186+ assertThat(tr).isEqualTo(tokenRange(i, i+1));
187+ } else {
188+ assertThat(tr.isEmpty());
189+ }
190+ }
191+ }
192+
193+ private TokenRange tokenRange(long start, long end) {
194+ return new TokenRange(newM3PToken(start), newM3PToken(end), factory);
195+ }
196+
197+ private TokenRange tokenRange(Token start, long end) {
198+ return new TokenRange(start, newM3PToken(end), factory);
199+ }
200+
201+ private TokenRange tokenRange(long start, Token end) {
202+ return new TokenRange(newM3PToken(start), end, factory);
203+ }
204+
205+ private TokenRange tokenRange(Token start, Token end) {
206+ return new TokenRange(start, end, factory);
207+ }
208+
209+ private Token newM3PToken(long value) {
210+ return factory.fromString(Long.toString(value));
211+ }
212+}
No newline at the end of the file