Elffuss BraidHub

kikocis/java-driver public

Merge pull request #276 from datastax/java312

Expose node token and range information (JAVA-312).
Changeset37bbc95ff88d4ce65cb5b544fdb3af76c3a0965a3227f82f9ed3a8148142cbb9
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-02-19 18:03 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-02-19 18:03 +01:00
Parentsb1ca3ae13f03, ffaefeab81b6

Browse the files at this changeset

26 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -7,6 +7,7 @@
77 - [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518)
88 - [improvement] Add connection heartbeat (JAVA-533)
99 - [improvement] Reduce level of logs on missing rpc_address (JAVA-568)
10+- [improvement] Expose node token and range information (JAVA-312)
1011
1112 Merged from 2.0.9_fixes branch:
1213
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +15 −8
@@ -40,10 +40,12 @@
4040 private static final Queue<List<ByteBuffer>> EMPTY_QUEUE = new ArrayDeque<List<ByteBuffer>>(0);
4141
4242 protected final ColumnDefinitions metadata;
43+ protected final Token.Factory tokenFactory;
4344 private final boolean wasApplied;
4445
45- private ArrayBackedResultSet(ColumnDefinitions metadata, List<ByteBuffer> firstRow) {
46+ private ArrayBackedResultSet(ColumnDefinitions metadata, Token.Factory tokenFactory, List<ByteBuffer> firstRow) {
4647 this.metadata = metadata;
48+ this.tokenFactory = tokenFactory;
4749 this.wasApplied = checkWasApplied(firstRow, metadata);
4850 }
4951
@@ -65,12 +67,15 @@
6567 columnDefs = r.metadata.columns;
6668 }
6769
70+ Token.Factory tokenFactory = (session == null) ? null
71+ : session.getCluster().getMetadata().tokenFactory();
72+
6873 // info can be null only for internal calls, but we don't page those. We assert
6974 // this explicitly because MultiPage implementation don't support info == null.
7075 assert r.metadata.pagingState == null || info != null;
7176 return r.metadata.pagingState == null
72- ? new SinglePage(columnDefs, r.data, info)
73- : new MultiPage(columnDefs, r.data, info, r.metadata.pagingState, session, statement);
77+ ? new SinglePage(columnDefs, tokenFactory, r.data, info)
78+ : new MultiPage(columnDefs, tokenFactory, r.data, info, r.metadata.pagingState, session, statement);
7479
7580 case SET_KEYSPACE:
7681 case SCHEMA_CHANGE:
@@ -89,7 +94,7 @@
8994 }
9095
9196 private static ArrayBackedResultSet empty(ExecutionInfo info) {
92- return new SinglePage(ColumnDefinitions.EMPTY, EMPTY_QUEUE, info);
97+ return new SinglePage(ColumnDefinitions.EMPTY, null, EMPTY_QUEUE, info);
9398 }
9499
95100 public ColumnDefinitions getColumnDefinitions() {
@@ -148,9 +153,10 @@
148153 private final ExecutionInfo info;
149154
150155 private SinglePage(ColumnDefinitions metadata,
156+ Token.Factory tokenFactory,
151157 Queue<List<ByteBuffer>> rows,
152158 ExecutionInfo info) {
153- super(metadata, rows.peek());
159+ super(metadata, tokenFactory, rows.peek());
154160 this.info = info;
155161 this.rows = rows;
156162 }
@@ -160,7 +166,7 @@
160166 }
161167
162168 public Row one() {
163- return ArrayBackedRow.fromData(metadata, rows.poll());
169+ return ArrayBackedRow.fromData(metadata, tokenFactory, rows.poll());
164170 }
165171
166172 public int getAvailableWithoutFetching() {
@@ -210,6 +216,7 @@
210216 private final Statement statement;
211217
212218 private MultiPage(ColumnDefinitions metadata,
219+ Token.Factory tokenFactory,
213220 Queue<List<ByteBuffer>> rows,
214221 ExecutionInfo info,
215222 ByteBuffer pagingState,
@@ -219,7 +226,7 @@
219226 // Note: as of Cassandra 2.1.0, it turns out that the result of a CAS update is never paged, so
220227 // we could hard-code the result of wasApplied in this class to "true". However, we can not be sure
221228 // that this will never change, so apply the generic check by peeking at the first row.
222- super(metadata, rows.peek());
229+ super(metadata, tokenFactory, rows.peek());
223230 this.currentPage = rows;
224231 this.infos.offer(info);
225232
@@ -235,7 +242,7 @@
235242
236243 public Row one() {
237244 prepareNextRow();
238- return ArrayBackedRow.fromData(metadata, currentPage.poll());
245+ return ArrayBackedRow.fromData(metadata, tokenFactory, currentPage.poll());
239246 }
240247
241248 public int getAvailableWithoutFetching() {
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java +33 −3
@@ -21,6 +21,7 @@
2121 import java.nio.ByteBuffer;
2222 import java.util.*;
2323
24+import com.datastax.driver.core.exceptions.DriverInternalError;
2425 import com.datastax.driver.core.exceptions.InvalidTypeException;
2526
2627 /**
@@ -29,18 +30,20 @@
2930 class ArrayBackedRow implements Row {
3031
3132 private final ColumnDefinitions metadata;
33+ private final Token.Factory tokenFactory;
3234 private final List<ByteBuffer> data;
3335
34- private ArrayBackedRow(ColumnDefinitions metadata, List<ByteBuffer> data) {
36+ private ArrayBackedRow(ColumnDefinitions metadata, Token.Factory tokenFactory, List<ByteBuffer> data) {
3537 this.metadata = metadata;
38+ this.tokenFactory = tokenFactory;
3639 this.data = data;
3740 }
3841
39- static Row fromData(ColumnDefinitions metadata, List<ByteBuffer> data) {
42+ static Row fromData(ColumnDefinitions metadata, Token.Factory tokenFactory, List<ByteBuffer> data) {
4043 if (data == null)
4144 return null;
4245
43- return new ArrayBackedRow(metadata, data);
46+ return new ArrayBackedRow(metadata, tokenFactory, data);
4447 }
4548
4649 public ColumnDefinitions getColumnDefinitions() {
@@ -239,6 +242,33 @@
239242 return getInet(metadata.getFirstIdx(name));
240243 }
241244
245+ public Token getToken(int i) {
246+ if (tokenFactory == null)
247+ throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
248+
249+ metadata.checkType(i, tokenFactory.getTokenType().getName());
250+
251+ ByteBuffer value = data.get(i);
252+ if (value == null || value.remaining() == 0)
253+ return null;
254+
255+ return tokenFactory.deserialize(value);
256+ }
257+
258+ public Token getToken(String name) {
259+ // first, try with `token(name)`, preserving case sensitivity
260+ String tokenName = (name.length() >= 2 && name.charAt(0) == '"' && name.charAt(name.length() - 1) == '"')
261+ ? "\"token(" + name.substring(1, name.length() - 1) + ")\""
262+ : "token(" + name + ")";
263+ int[] indexes = metadata.findAllIdx(tokenName);
264+ if (indexes != null) {
265+ return getToken(indexes[0]);
266+ }
267+
268+ // Otherwise, use normal name
269+ return getToken(metadata.getFirstIdx(name));
270+ }
271+
242272 @SuppressWarnings("unchecked")
243273 public <T> List<T> getList(int i, Class<T> elementsClass) {
244274 DataType type = metadata.getType(i);
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +39 −0
@@ -185,6 +185,9 @@
185185 }
186186 break;
187187 default:
188+ if (toSet instanceof Token)
189+ toSet = ((Token)toSet).getValue();
190+
188191 Class<?> providedClass = toSet.getClass();
189192 Class<?> expectedClass = columnType.getName().javaType;
190193 if (!expectedClass.isAssignableFrom(providedClass))
@@ -818,6 +821,42 @@
818821 return this;
819822 }
820823
824+ /**
825+ * Sets the {@code i}th value to the provided {@link Token}.
826+ *
827+ * @param i the index of the variable to set.
828+ * @param v the value to set.
829+ * @return this BoundStatement.
830+ *
831+ * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}.
832+ * @throws InvalidTypeException if column {@code i} is not of the type of the token's value.
833+ */
834+ public BoundStatement setToken(int i, Token v) {
835+ metadata().checkType(i, v.getType().getName());
836+ return setValue(i, v.getType().serialize(v.getValue()));
837+ }
838+
839+ /**
840+ * Sets the value for (all occurrences of) variable {@code name} to the
841+ * provided token.
842+ *
843+ * @param name the name of the variable to set; if multiple variables
844+ * {@code name} are prepared, all of them are set.
845+ * @param v the value to set.
846+ * @return this BoundStatement.
847+ *
848+ * @throws IllegalArgumentException if {@code name} is not a prepared
849+ * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}.
850+ * @throws InvalidTypeException if (any occurrence of) {@code name} is
851+ * not of the type of the token's value.
852+ */
853+ public BoundStatement setToken(String name, Token v) {
854+ int[] indexes = metadata().getAllIdx(name);
855+ for (int i = 0; i < indexes.length; i++)
856+ setToken(indexes[i], v);
857+ return this;
858+ }
859+
821860 /**
822861 * Sets the {@code i}th value to the provided list.
823862 * <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
@@ -64,6 +65,8 @@
6465 // (partly because the 'System.local' doesn't have it for some weird reason for instance).
6566 volatile InetAddress listenAddress;
6667
68+ private volatile Set<Token> tokens;
69+
6770 // ClusterMetadata keeps one Host object per inet address and we rely on this (more precisely,
6871 // we rely on the fact that we can use Object equality as a valid equality), so don't use
6972 // that constructor but ClusterMetadata.getHost instead.
@@ -156,6 +159,19 @@
156159 return cassandraVersion;
157160 }
158161
162+ /**
163+ * Returns the tokens that this host owns.
164+ *
165+ * @return the (immutable) set of tokens.
166+ */
167+ public Set<Token> getTokens() {
168+ return tokens;
169+ }
170+
171+ void setTokens(Set<Token> tokens) {
172+ this.tokens = tokens;
173+ }
174+
159175 /**
160176 * Returns whether the host is considered up by the driver.
161177 * <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
@@ -234,19 +234,61 @@
234234 return '"' + id + '"';
235235 }
236236
237+ /**
238+ * Returns the token ranges that define data distribution in the ring.
239+ * <p>
240+ * Note that this information is refreshed asynchronously by the control
241+ * connection, when schema or ring topology changes. It might occasionally
242+ * be stale.
243+ *
244+ * @return the token ranges.
245+ */
246+ public Set<TokenRange> getTokenRanges() {
247+ TokenMap current = tokenMap;
248+ return (current == null) ? Collections.<TokenRange>emptySet() : current.tokenRanges;
249+ }
250+
251+ /**
252+ * Returns the token ranges that are replicated on the given host, for the given
253+ * keyspace.
254+ * <p>
255+ * Note that this information is refreshed asynchronously by the control
256+ * connection, when schema or ring topology changes. It might occasionally
257+ * be stale (or even empty).
258+ *
259+ * @param keyspace the name of the keyspace to get token ranges for.
260+ * @param host the host.
261+ * @return the (immutable) set of token ranges for {@code host} as known
262+ * by the driver.
263+ */
264+ public Set<TokenRange> getTokenRanges(String keyspace, Host host) {
265+ keyspace = handleId(keyspace);
266+ TokenMap current = tokenMap;
267+ if (current == null) {
268+ return Collections.emptySet();
269+ } else {
270+ Map<Host, Set<TokenRange>> dcRanges = current.hostsToRanges.get(keyspace);
271+ if (dcRanges == null) {
272+ return Collections.emptySet();
273+ } else {
274+ Set<TokenRange> ranges = dcRanges.get(host);
275+ return (ranges == null) ? Collections.<TokenRange>emptySet() : ranges;
276+ }
277+ }
278+ }
279+
237280 /**
238281 * Returns the set of hosts that are replica for a given partition key.
239282 * <p>
240- * Note that this method is a best effort method. Consumers should not rely
241- * too heavily on the result of this method not being stale (or even empty).
283+ * Note that this information is refreshed asynchronously by the control
284+ * connection, when schema or ring topology changes. It might occasionally
285+ * be stale (or even empty).
242286 *
243287 * @param keyspace the name of the keyspace to get replicas for.
244288 * @param partitionKey the partition key for which to find the set of
245289 * replica.
246- * @return the (immutable) set of replicas for {@code partitionKey} as know
247- * by the driver. No strong guarantee is provided on the stalelessness of
248- * this information. It is also not guarantee that the returned set won't
249- * be empty (which is then some form of staleness).
290+ * @return the (immutable) set of replicas for {@code partitionKey} as known
291+ * by the driver.
250292 */
251293 public Set<Host> getReplicas(String keyspace, ByteBuffer partitionKey) {
252294 keyspace = handleId(keyspace);
@@ -259,6 +301,28 @@
259301 }
260302 }
261303
304+ /**
305+ * Returns the set of hosts that are replica for a given token range.
306+ * <p>
307+ * Note that this information is refreshed asynchronously by the control
308+ * connection, when schema or ring topology changes. It might occasionally
309+ * be stale (or even empty).
310+ *
311+ * @param keyspace the name of the keyspace to get replicas for.
312+ * @param range the token range.
313+ * @return the (immutable) set of replicas for {@code range} as known by the driver.
314+ */
315+ public Set<Host> getReplicas(String keyspace, TokenRange range) {
316+ keyspace = handleId(keyspace);
317+ TokenMap current = tokenMap;
318+ if (current == null) {
319+ return Collections.emptySet();
320+ } else {
321+ Set<Host> hosts = current.getReplicas(keyspace, range.getEnd());
322+ return hosts == null ? Collections.<Host>emptySet() : hosts;
323+ }
324+ }
325+
262326 /**
263327 * The Cassandra name for the cluster connect to.
264328 *
@@ -335,24 +399,42 @@
335399 return sb.toString();
336400 }
337401
402+ Token.Factory tokenFactory() {
403+ TokenMap current = tokenMap;
404+ return (current == null) ? null : current.factory;
405+ }
406+
338407 static class TokenMap {
339408
340409 private final Token.Factory factory;
341410 private final Map<String, Map<Token, Set<Host>>> tokenToHosts;
411+ private final Map<String, Map<Host, Set<TokenRange>>> hostsToRanges;
342412 private final List<Token> ring;
413+ private final Set<TokenRange> tokenRanges;
343414 final Set<Host> hosts;
344415
345- private TokenMap(Token.Factory factory, Map<String, Map<Token, Set<Host>>> tokenToHosts, List<Token> ring, Set<Host> hosts) {
416+ private TokenMap(Token.Factory factory,
417+ Map<Host, Set<Token>> primaryToTokens,
418+ Map<String, Map<Token, Set<Host>>> tokenToHosts,
419+ Map<String, Map<Host, Set<TokenRange>>> hostsToRanges,
420+ List<Token> ring, Set<TokenRange> tokenRanges, Set<Host> hosts) {
346421 this.factory = factory;
347422 this.tokenToHosts = tokenToHosts;
423+ this.hostsToRanges = hostsToRanges;
348424 this.ring = ring;
425+ this.tokenRanges = tokenRanges;
349426 this.hosts = hosts;
427+ for (Map.Entry<Host, Set<Token>> entry : primaryToTokens.entrySet()) {
428+ Host host = entry.getKey();
429+ host.setTokens(ImmutableSet.copyOf(entry.getValue()));
430+ }
350431 }
351432
352433 public static TokenMap build(Token.Factory factory, Map<Host, Collection<String>> allTokens, Collection<KeyspaceMetadata> keyspaces) {
353434
354435 Set<Host> hosts = allTokens.keySet();
355436 Map<Token, Host> tokenToPrimary = new HashMap<Token, Host>();
437+ Map<Host, Set<Token>> primaryToTokens = new HashMap<Host, Set<Token>>();
356438 Set<Token> allSorted = new TreeSet<Token>();
357439
358440 for (Map.Entry<Host, Collection<String>> entry : allTokens.entrySet()) {
@@ -362,6 +444,12 @@
362444 Token t = factory.fromString(tokenStr);
363445 allSorted.add(t);
364446 tokenToPrimary.put(t, host);
447+ Set<Token> hostTokens = primaryToTokens.get(host);
448+ if (hostTokens == null) {
449+ hostTokens = new HashSet<Token>();
450+ primaryToTokens.put(host, hostTokens);
451+ }
452+ hostTokens.add(t);
365453 } catch (IllegalArgumentException e) {
366454 // If we failed parsing that token, skip it
367455 }
@@ -369,18 +457,23 @@
369457 }
370458
371459 List<Token> ring = new ArrayList<Token>(allSorted);
460+ Set<TokenRange> tokenRanges = makeTokenRanges(ring, factory);
372461
373462 Map<String, Map<Token, Set<Host>>> tokenToHosts = new HashMap<String, Map<Token, Set<Host>>>();
463+ Map<String, Map<Host, Set<TokenRange>>> hostsToRanges = new HashMap<String, Map<Host, Set<TokenRange>>>();
374464 for (KeyspaceMetadata keyspace : keyspaces)
375465 {
376466 ReplicationStrategy strategy = keyspace.replicationStrategy();
377- if (strategy == null) {
378- tokenToHosts.put(keyspace.getName(), makeNonReplicatedMap(tokenToPrimary));
379- } else {
380- tokenToHosts.put(keyspace.getName(), strategy.computeTokenToReplicaMap(tokenToPrimary, ring));
381- }
467+ Map<Token, Set<Host>> ksTokens = (strategy == null)
468+ ? makeNonReplicatedMap(tokenToPrimary)
469+ : strategy.computeTokenToReplicaMap(tokenToPrimary, ring);
470+
471+ tokenToHosts.put(keyspace.getName(), ksTokens);
472+
473+ Map<Host, Set<TokenRange>> ksRanges = computeHostsToRangesMap(tokenRanges, ksTokens, hosts.size());
474+ hostsToRanges.put(keyspace.getName(), ksRanges);
382475 }
383- return new TokenMap(factory, tokenToHosts, ring, hosts);
476+ return new TokenMap(factory, primaryToTokens, tokenToHosts, hostsToRanges, ring, tokenRanges, hosts);
384477 }
385478
386479 private Set<Host> getReplicas(String keyspace, Token token) {
@@ -389,7 +482,12 @@
389482 if (keyspaceHosts == null)
390483 return Collections.emptySet();
391484
392- // Find the primary replica
485+ // If the token happens to be one of the "primary" tokens, get result directly
486+ Set<Host> hosts = keyspaceHosts.get(token);
487+ if (hosts != null)
488+ return hosts;
489+
490+ // Otherwise, find closest "primary" token on the ring
393491 int i = Collections.binarySearch(ring, token);
394492 if (i < 0) {
395493 i = -i - 1;
@@ -406,5 +504,35 @@
406504 output.put(entry.getKey(), ImmutableSet.of(entry.getValue()));
407505 return output;
408506 }
507+
508+ private static Set<TokenRange> makeTokenRanges(List<Token> ring, Token.Factory factory) {
509+ ImmutableSet.Builder<TokenRange> builder = ImmutableSet.builder();
510+ for (int i = 0; i < ring.size(); i++) {
511+ Token start = ring.get(i);
512+ Token end = ring.get((i + 1) % ring.size());
513+ builder.add(new TokenRange(start, end, factory));
514+ }
515+ return builder.build();
516+ }
517+
518+ private static Map<Host, Set<TokenRange>> computeHostsToRangesMap(Set<TokenRange> tokenRanges, Map<Token, Set<Host>> ksTokens, int hostCount) {
519+ Map<Host, ImmutableSet.Builder<TokenRange>> builders = Maps.newHashMapWithExpectedSize(hostCount);
520+ for (TokenRange range : tokenRanges) {
521+ Set<Host> replicas = ksTokens.get(range.getEnd());
522+ for (Host host : replicas) {
523+ ImmutableSet.Builder<TokenRange> hostRanges = builders.get(host);
524+ if (hostRanges == null) {
525+ hostRanges = ImmutableSet.builder();
526+ builders.put(host, hostRanges);
527+ }
528+ hostRanges.add(range);
529+ }
530+ }
531+ Map<Host, Set<TokenRange>> ksRanges = Maps.newHashMapWithExpectedSize(hostCount);
532+ for (Map.Entry<Host, ImmutableSet.Builder<TokenRange>> entry : builders.entrySet()) {
533+ ksRanges.put(entry.getKey(), entry.getValue().build());
534+ }
535+ return ksRanges;
536+ }
409537 }
410538 }
modified driver-core/src/main/java/com/datastax/driver/core/Row.java +44 −0
@@ -404,6 +404,50 @@
404404 */
405405 public InetAddress getInet(String name);
406406
407+ /**
408+ * Returns the {@code i}th value of this row as a {@link Token}.
409+ *
410+ * @param i the index ({@code 0 <= i < size()}) of the column to retrieve.
411+ * @return the value of the {@code i}th column in this row as an Token.
412+ * If the value is NULL, {@code null} is returned.
413+ *
414+ * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
415+ * @throws InvalidTypeException if column {@code i} is not of the type of token values
416+ * for this cluster (this depends on the configured partitioner).
417+ */
418+ public Token getToken(int i);
419+
420+ /**
421+ * Returns the value of column {@code name} as a {@link Token}.
422+ * <p>
423+ * This method will first try with {@code token(name)}, because in most cases the column
424+ * is named that way since it results from the application of a CQL function:
425+ * <pre>
426+ * {@code
427+ * ResultSet rs = session.execute("SELECT token(k) FROM my_table WHERE k = 1");
428+ * Token token = rs.one().getToken("k"); // retrieves token(k)
429+ * }
430+ * </pre>
431+ * If that fails, it will try will {@code name}. This handles the case where the column
432+ * was aliased:
433+ * <pre>
434+ * {@code
435+ * ResultSet rs = session.execute("SELECT token(k) AS t FROM my_table WHERE k = 1");
436+ * Token token = rs.one().getToken("t");
437+ * }
438+ * </pre>
439+ *
440+ * @param name the name of the column to retrieve.
441+ * @return the value of column {@code name} as a Token.
442+ * If the value is NULL, {@code null} is returned.
443+ *
444+ * @throws IllegalArgumentException if {@code name} is not part of the
445+ * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
446+ * @throws InvalidTypeException if column {@code name} is not of the type of token values
447+ * for this cluster (this depends on the configured partitioner).
448+ */
449+ public Token getToken(String name);
450+
407451 /**
408452 * Returns the {@code i}th value of this row as a list.
409453 *
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +5 −2
@@ -92,11 +92,14 @@
9292 private static ByteBuffer[] convert(Object[] values) {
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]);
97+ if (value instanceof Token)
98+ value = ((Token)value).getValue();
99+ serializedValues[i] = DataType.serializeValue(value);
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;
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);
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) {
216+ return new M3PToken((Long) getTokenType().deserialize(buffer));
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) {
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) {
528+ return new RPToken((BigInteger)getTokenType().deserialize(buffer));
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;
@@ -89,11 +90,11 @@
8990 return bridge;
9091 }
9192
92- public static CCMBridge create(String name, int nbNodes) {
93+ public static CCMBridge create(String name, int nbNodes, String... options) {
9394 checkArgument(!"current".equals(name.toLowerCase()),
9495 "cluster can't be called \"current\"");
9596 CCMBridge bridge = new CCMBridge();
96- bridge.execute("ccm create %s -n %d -s -i %s -b %s", name, nbNodes, IP_PREFIX, CASSANDRA_VERSION);
97+ bridge.execute("ccm create %s -n %d -s -i %s -b %s " + Joiner.on(" ").join(options), name, nbNodes, IP_PREFIX, CASSANDRA_VERSION);
9798 return bridge;
9899 }
99100
@@ -150,6 +151,11 @@
150151 execute("ccm remove");
151152 }
152153
154+ public void remove(int n) {
155+ logger.info("Removing: " + IP_PREFIX + n);
156+ execute("ccm node%d remove", n);
157+ }
158+
153159 public void ring() {
154160 ring(1);
155161 }
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 +83 −0
@@ -0,0 +1,83 @@
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 com.google.common.collect.Lists;
8+import org.testng.annotations.Test;
9+
10+import static org.assertj.core.api.Assertions.assertThat;
11+import static org.testng.Assert.fail;
12+
13+public class OPPTokenFactoryTest {
14+ private static final Token.Factory factory = Token.OPPToken.FACTORY;
15+
16+ private static final Token minToken = factory.deserialize(ByteBuffer.allocate(0));
17+
18+ @Test(groups = "unit")
19+ public void should_split_range() {
20+ List<Token> splits = factory.split(token('a'), token('d'), 3);
21+ assertThat(splits).containsExactly(
22+ token('b'),
23+ token('c')
24+ );
25+ }
26+
27+ @Test(groups = "unit")
28+ public void should_split_range_producing_empty_splits_near_ring_end() {
29+ // the first token following min
30+ Token zero = factory.deserialize(ByteBuffer.wrap(new byte[]{0}));
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 = factory.deserialize(ByteBuffer.wrap(new byte[]{4,0,0,0}));
43+ Token without0Bytes = factory.deserialize(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 Token token(char c) {
77+ return new Token.OPPToken(ByteBuffer.wrap(new byte[]{ (byte)c }));
78+ }
79+
80+ private Token token(long i) {
81+ return new Token.OPPToken(ByteBuffer.wrap(BigInteger.valueOf(i).toByteArray()));
82+ }
83+}
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));
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