kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 5a403d3000f4b7b5ecfda9a41d365fee71606e03c6aa1b2b4411bab08bd5e9d3 |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-03-30 17:50 +02:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-03-30 17:50 +02:00 |
| Parents | c0c391746aac, cc782d1a51f5 |
9 files changed
modified driver-core/CHANGELOG.rst +1 −0
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | (JAVA-562) |
| 28 | 28 | - [improvement] Rename threads to indicate that they are for the driver |
| 29 | 29 | (JAVA-583) |
| 30 | +- [new feature] Expose paging state (JAVA-550) | |
| 30 | 31 | |
| 31 | 32 | Merged from 2.0.9_fixes branch: |
| 32 | 33 |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +5 −4
| @@ -74,8 +74,8 @@ | ||
| 74 | 74 | // this explicitly because MultiPage implementation don't support info == null. |
| 75 | 75 | assert r.metadata.pagingState == null || info != null; |
| 76 | 76 | return r.metadata.pagingState == null |
| 77 | - ? new SinglePage(columnDefs, tokenFactory, r.data, info) | |
| 78 | - : new MultiPage(columnDefs, tokenFactory, 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); | |
| 79 | 79 | |
| 80 | 80 | case SET_KEYSPACE: |
| 81 | 81 | case SCHEMA_CHANGE: |
| @@ -228,7 +228,7 @@ | ||
| 228 | 228 | // that this will never change, so apply the generic check by peeking at the first row. |
| 229 | 229 | super(metadata, tokenFactory, rows.peek()); |
| 230 | 230 | this.currentPage = rows; |
| 231 | - this.infos.offer(info); | |
| 231 | + this.infos.offer(info.withPagingState(pagingState).withStatement(statement)); | |
| 232 | 232 | |
| 233 | 233 | this.fetchState = new FetchingState(pagingState, null); |
| 234 | 234 | this.session = session; |
| @@ -322,9 +322,10 @@ | ||
| 322 | 322 | case RESULT: |
| 323 | 323 | Responses.Result rm = (Responses.Result)response; |
| 324 | 324 | info = update(info, rm, MultiPage.this.session); |
| 325 | - | |
| 326 | 325 | if (rm.kind == Responses.Result.Kind.ROWS) { |
| 327 | 326 | Responses.Result.Rows rows = (Responses.Result.Rows)rm; |
| 327 | + if (rows.metadata.pagingState != null) | |
| 328 | + info = info.withPagingState(rows.metadata.pagingState).withStatement(statement); | |
| 328 | 329 | MultiPage.this.nextPages.offer(rows.data); |
| 329 | 330 | MultiPage.this.fetchState = rows.metadata.pagingState == null ? null : new FetchingState(rows.metadata.pagingState, null); |
| 330 | 331 | } else if (rm.kind == Responses.Result.Kind.VOID) { |
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +34 −6
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.nio.ByteBuffer; | |
| 18 | 19 | import java.util.List; |
| 19 | 20 | |
| 20 | 21 | /** |
| @@ -32,28 +33,39 @@ | ||
| 32 | 33 | * query.</li> |
| 33 | 34 | * </ul> |
| 34 | 35 | */ |
| 35 | -public class ExecutionInfo | |
| 36 | -{ | |
| 36 | +public class ExecutionInfo { | |
| 37 | 37 | private final List<Host> triedHosts; |
| 38 | 38 | private final ConsistencyLevel achievedConsistency; |
| 39 | 39 | private final QueryTrace trace; |
| 40 | + private final ByteBuffer pagingState; | |
| 41 | + private final Statement statement; | |
| 40 | 42 | |
| 41 | - private ExecutionInfo(List<Host> triedHosts, ConsistencyLevel achievedConsistency, QueryTrace trace) { | |
| 43 | + private ExecutionInfo(List<Host> triedHosts, ConsistencyLevel achievedConsistency, QueryTrace trace, ByteBuffer pagingState, Statement statement) { | |
| 42 | 44 | this.triedHosts = triedHosts; |
| 43 | 45 | this.achievedConsistency = achievedConsistency; |
| 44 | 46 | this.trace = trace; |
| 47 | + this.pagingState = pagingState; | |
| 48 | + this.statement = statement; | |
| 45 | 49 | } |
| 46 | 50 | |
| 47 | 51 | ExecutionInfo(List<Host> triedHosts) { |
| 48 | - this(triedHosts, null, null); | |
| 52 | + this(triedHosts, null, null, null, null); | |
| 49 | 53 | } |
| 50 | 54 | |
| 51 | 55 | ExecutionInfo withTrace(QueryTrace newTrace) { |
| 52 | - return new ExecutionInfo(triedHosts, achievedConsistency, newTrace); | |
| 56 | + return new ExecutionInfo(triedHosts, achievedConsistency, newTrace, pagingState, statement); | |
| 53 | 57 | } |
| 54 | 58 | |
| 55 | 59 | ExecutionInfo withAchievedConsistency(ConsistencyLevel newConsistency) { |
| 56 | - return new ExecutionInfo(triedHosts, newConsistency, trace); | |
| 60 | + return new ExecutionInfo(triedHosts, newConsistency, trace, pagingState, statement); | |
| 61 | + } | |
| 62 | + | |
| 63 | + ExecutionInfo withPagingState(ByteBuffer pagingState) { | |
| 64 | + return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, statement); | |
| 65 | + } | |
| 66 | + | |
| 67 | + ExecutionInfo withStatement(Statement statement) { | |
| 68 | + return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, statement); | |
| 57 | 69 | } |
| 58 | 70 | |
| 59 | 71 | /** |
| @@ -119,4 +131,20 @@ | ||
| 119 | 131 | public QueryTrace getQueryTrace() { |
| 120 | 132 | return trace; |
| 121 | 133 | } |
| 134 | + | |
| 135 | + /** | |
| 136 | + * The paging state of the query. | |
| 137 | + * | |
| 138 | + * This object represents the next page to be fetched if this query is | |
| 139 | + * multi page. It can be saved and reused later on the same statement. | |
| 140 | + * | |
| 141 | + * @return the paging state or null if there is no next page. | |
| 142 | + * | |
| 143 | + * @see Statement#setPagingState(PagingState) | |
| 144 | + */ | |
| 145 | + public PagingState getPagingState() { | |
| 146 | + if (this.pagingState == null) | |
| 147 | + return null; | |
| 148 | + return new PagingState(this.pagingState, this.statement); | |
| 149 | + } | |
| 122 | 150 | } |
added driver-core/src/main/java/com/datastax/driver/core/PagingState.java +179 −0
| @@ -0,0 +1,179 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | + | |
| 17 | +package com.datastax.driver.core; | |
| 18 | + | |
| 19 | +import java.nio.ByteBuffer; | |
| 20 | +import java.security.MessageDigest; | |
| 21 | +import java.security.NoSuchAlgorithmException; | |
| 22 | +import java.util.Arrays; | |
| 23 | + | |
| 24 | +import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 25 | +import com.datastax.driver.core.exceptions.PagingStateException; | |
| 26 | +import com.datastax.driver.core.utils.Bytes; | |
| 27 | + | |
| 28 | +/** | |
| 29 | + * The paging state of a query. | |
| 30 | + * | |
| 31 | + * This object represents the next page to be fetched if the query is | |
| 32 | + * multi page. It can be saved and reused later on the same statement. | |
| 33 | + * | |
| 34 | + * The PagingState can be serialized and deserialized either as a String | |
| 35 | + * or as a byte array. | |
| 36 | + * | |
| 37 | + * @see Statement#setPagingState(PagingState) | |
| 38 | + */ | |
| 39 | +public class PagingState { | |
| 40 | + | |
| 41 | + private byte[] pagingState; | |
| 42 | + private byte[] hash; | |
| 43 | + | |
| 44 | + PagingState(ByteBuffer pagingState, Statement statement) { | |
| 45 | + this.pagingState = Bytes.getArray(pagingState); | |
| 46 | + this.hash = hash(statement); | |
| 47 | + } | |
| 48 | + | |
| 49 | + private PagingState(byte[] complete) { | |
| 50 | + // Check the sizes in the beginning of the buffer, otherwise we cannot build the paging state object | |
| 51 | + ByteBuffer pagingStateBB = ByteBuffer.wrap(complete); | |
| 52 | + int pagingSize = pagingStateBB.getShort(); | |
| 53 | + int hashSize = pagingStateBB.getShort(); | |
| 54 | + if (pagingSize + hashSize != pagingStateBB.remaining()) { | |
| 55 | + throw new PagingStateException("Cannot deserialize paging state, invalid format. " | |
| 56 | + + "The serialized form was corrupted, or not initially generated from a PagingState object."); | |
| 57 | + } | |
| 58 | + this.pagingState = extractPagingState(complete); | |
| 59 | + this.hash = extractHashDigest(complete); | |
| 60 | + } | |
| 61 | + | |
| 62 | + private byte[] hash(Statement statement) { | |
| 63 | + byte[] digest; | |
| 64 | + ByteBuffer[] values; | |
| 65 | + MessageDigest md; | |
| 66 | + assert !(statement instanceof BatchStatement); | |
| 67 | + try { | |
| 68 | + md = MessageDigest.getInstance("MD5"); | |
| 69 | + if (statement instanceof BoundStatement) { | |
| 70 | + BoundStatement bs = ((BoundStatement)statement); | |
| 71 | + md.update(bs.preparedStatement().getQueryString().getBytes()); | |
| 72 | + values = bs.values; | |
| 73 | + } else { | |
| 74 | + //it is a RegularStatement since Batch statements are not allowed | |
| 75 | + RegularStatement rs = (RegularStatement)statement; | |
| 76 | + md.update(rs.getQueryString().getBytes()); | |
| 77 | + values = rs.getValues(); | |
| 78 | + } | |
| 79 | + if (values != null) { | |
| 80 | + for (ByteBuffer value : values) { | |
| 81 | + md.update(value.duplicate()); | |
| 82 | + } | |
| 83 | + } | |
| 84 | + md.update(this.pagingState); | |
| 85 | + digest = md.digest(); | |
| 86 | + | |
| 87 | + } catch (NoSuchAlgorithmException e) { | |
| 88 | + throw new RuntimeException("MD5 doesn't seem to be available on this JVM", e); | |
| 89 | + } | |
| 90 | + return digest; | |
| 91 | + } | |
| 92 | + | |
| 93 | + boolean matches(Statement statement) { | |
| 94 | + byte[] toTest = hash(statement); | |
| 95 | + return Arrays.equals(toTest, this.hash); | |
| 96 | + } | |
| 97 | + | |
| 98 | + private static byte[] extractPagingState(byte[] complete) { | |
| 99 | + ByteBuffer completeBB = ByteBuffer.wrap(complete); | |
| 100 | + short size = completeBB.getShort(); | |
| 101 | + byte[] array = new byte[size]; | |
| 102 | + // Go forward of 2 bytes | |
| 103 | + completeBB.getShort(); | |
| 104 | + completeBB.get(array); | |
| 105 | + return array; | |
| 106 | + } | |
| 107 | + | |
| 108 | + private static byte[] extractHashDigest(byte[] complete) { | |
| 109 | + ByteBuffer completeBB = ByteBuffer.wrap(complete); | |
| 110 | + short pagingSize = completeBB.getShort(); | |
| 111 | + short hashSize = completeBB.getShort(); | |
| 112 | + completeBB.position(pagingSize + 4); | |
| 113 | + byte[] array = new byte[hashSize]; | |
| 114 | + completeBB.get(array); | |
| 115 | + return array; | |
| 116 | + } | |
| 117 | + | |
| 118 | + private ByteBuffer generateCompleteOutput() { | |
| 119 | + ByteBuffer res = ByteBuffer.allocate(pagingState.length + hash.length + 4); | |
| 120 | + | |
| 121 | + res.putShort((short)pagingState.length); | |
| 122 | + res.putShort((short)hash.length); | |
| 123 | + | |
| 124 | + res.put(pagingState); | |
| 125 | + res.put(hash); | |
| 126 | + | |
| 127 | + res.rewind(); | |
| 128 | + | |
| 129 | + return res; | |
| 130 | + } | |
| 131 | + | |
| 132 | + ByteBuffer getRawState() { | |
| 133 | + return ByteBuffer.wrap(this.pagingState); | |
| 134 | + } | |
| 135 | + | |
| 136 | + @Override | |
| 137 | + public String toString() { | |
| 138 | + return Bytes.toRawHexString(generateCompleteOutput()); | |
| 139 | + } | |
| 140 | + | |
| 141 | + /** | |
| 142 | + * Create a PagingState object from a string previously generated with {@link #toString()}. | |
| 143 | + * | |
| 144 | + * @param string the string value. | |
| 145 | + * @return the PagingState object created. | |
| 146 | + * | |
| 147 | + * @throws PagingStateException if the string does not have the correct format. | |
| 148 | + */ | |
| 149 | + public static PagingState fromString(String string) { | |
| 150 | + try { | |
| 151 | + byte[] complete = Bytes.fromRawHexString(string, 0); | |
| 152 | + return new PagingState(complete); | |
| 153 | + } catch (Exception e) { | |
| 154 | + throw new PagingStateException("Cannot deserialize paging state, invalid format. " | |
| 155 | + + "The serialized form was corrupted, or not initially generated from a PagingState object.", e); | |
| 156 | + } | |
| 157 | + } | |
| 158 | + | |
| 159 | + /** | |
| 160 | + * Return a representation of the paging state object as a byte array. | |
| 161 | + * | |
| 162 | + * @return the paging state as a byte array. | |
| 163 | + */ | |
| 164 | + public byte[] toBytes() { | |
| 165 | + return generateCompleteOutput().array(); | |
| 166 | + } | |
| 167 | + | |
| 168 | + /** | |
| 169 | + * Create a PagingState object from a byte array previously generated with {@link #toBytes()}. | |
| 170 | + * | |
| 171 | + * @param pagingState The byte array representation. | |
| 172 | + * @return the PagingState object created. | |
| 173 | + * | |
| 174 | + * @throws PagingStateException if the byte array does not have the correct format. | |
| 175 | + */ | |
| 176 | + public static PagingState fromBytes(byte[] pagingState) { | |
| 177 | + return new PagingState(pagingState); | |
| 178 | + } | |
| 179 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +9 −5
| @@ -28,7 +28,6 @@ | ||
| 28 | 28 | import org.slf4j.Logger; |
| 29 | 29 | import org.slf4j.LoggerFactory; |
| 30 | 30 | |
| 31 | - | |
| 32 | 31 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 33 | 32 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| 34 | 33 | import com.datastax.driver.core.policies.LoadBalancingPolicy; |
| @@ -327,8 +326,8 @@ | ||
| 327 | 326 | CloseFuture removePool(Host host) { |
| 328 | 327 | final HostConnectionPool pool = pools.remove(host); |
| 329 | 328 | return pool == null |
| 330 | - ? CloseFuture.immediateFuture() | |
| 331 | - : pool.closeAsync(); | |
| 329 | + ? CloseFuture.immediateFuture() | |
| 330 | + : pool.closeAsync(); | |
| 332 | 331 | } |
| 333 | 332 | |
| 334 | 333 | /* |
| @@ -451,6 +450,7 @@ | ||
| 451 | 450 | Message.Request makeRequestMessage(Statement statement, ConsistencyLevel cl, ConsistencyLevel scl, ByteBuffer pagingState) { |
| 452 | 451 | int protoVersion = cluster.manager.protocolVersion(); |
| 453 | 452 | int fetchSize = statement.getFetchSize(); |
| 453 | + ByteBuffer usedPagingState = pagingState; | |
| 454 | 454 | |
| 455 | 455 | if (protoVersion == 1) { |
| 456 | 456 | assert pagingState == null; |
| @@ -467,6 +467,10 @@ | ||
| 467 | 467 | if (fetchSize == Integer.MAX_VALUE) |
| 468 | 468 | fetchSize = -1; |
| 469 | 469 | |
| 470 | + if (pagingState == null) { | |
| 471 | + usedPagingState = statement.getPagingState(); | |
| 472 | + } | |
| 473 | + | |
| 470 | 474 | if (statement instanceof RegularStatement) { |
| 471 | 475 | RegularStatement rs = (RegularStatement)statement; |
| 472 | 476 | |
| @@ -483,12 +487,12 @@ | ||
| 483 | 487 | |
| 484 | 488 | List<ByteBuffer> values = rawValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawValues); |
| 485 | 489 | String qString = rs.getQueryString(); |
| 486 | - Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(cl, values, false, fetchSize, pagingState, scl); | |
| 490 | + Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(cl, values, false, fetchSize, usedPagingState, scl); | |
| 487 | 491 | return new Requests.Query(qString, options); |
| 488 | 492 | } else if (statement instanceof BoundStatement) { |
| 489 | 493 | BoundStatement bs = (BoundStatement)statement; |
| 490 | 494 | boolean skipMetadata = protoVersion != 1 && bs.statement.getPreparedId().resultSetMetadata != null; |
| 491 | - Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(cl, Arrays.asList(bs.values), skipMetadata, fetchSize, pagingState, scl); | |
| 495 | + Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(cl, Arrays.asList(bs.values), skipMetadata, fetchSize, usedPagingState, scl); | |
| 492 | 496 | return new Requests.Execute(bs.statement.getPreparedId().id, options); |
| 493 | 497 | } else { |
| 494 | 498 | assert statement instanceof BatchStatement : statement; |
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +78 −4
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.nio.ByteBuffer; |
| 19 | 19 | |
| 20 | +import com.datastax.driver.core.exceptions.PagingStateException; | |
| 20 | 21 | import com.datastax.driver.core.policies.RetryPolicy; |
| 21 | 22 | |
| 22 | 23 | /** |
| @@ -32,10 +33,14 @@ | ||
| 32 | 33 | // used when preparing a statement and for other internal queries. Do not expose publicly. |
| 33 | 34 | static final Statement DEFAULT = new Statement() { |
| 34 | 35 | @Override |
| 35 | - public ByteBuffer getRoutingKey() { return null; } | |
| 36 | + public ByteBuffer getRoutingKey() { | |
| 37 | + return null; | |
| 38 | + } | |
| 36 | 39 | |
| 37 | 40 | @Override |
| 38 | - public String getKeyspace() { return null; } | |
| 41 | + public String getKeyspace() { | |
| 42 | + return null; | |
| 43 | + } | |
| 39 | 44 | }; |
| 40 | 45 | |
| 41 | 46 | private volatile ConsistencyLevel consistency; |
| @@ -45,8 +50,11 @@ | ||
| 45 | 50 | |
| 46 | 51 | private volatile RetryPolicy retryPolicy; |
| 47 | 52 | |
| 53 | + private volatile ByteBuffer pagingState; | |
| 54 | + | |
| 48 | 55 | // We don't want to expose the constructor, because the code relies on this being only sub-classed by RegularStatement, BoundStatement and BatchStatement |
| 49 | - Statement() {} | |
| 56 | + Statement() { | |
| 57 | + } | |
| 50 | 58 | |
| 51 | 59 | /** |
| 52 | 60 | * Sets the consistency level for the query. |
| @@ -252,4 +260,70 @@ | ||
| 252 | 260 | public int getFetchSize() { |
| 253 | 261 | return fetchSize; |
| 254 | 262 | } |
| 255 | -} | |
| 263 | + | |
| 264 | + /** | |
| 265 | + * Sets the paging state. | |
| 266 | + * <p> | |
| 267 | + * This will cause the next execution of this statement to fetch results from a given | |
| 268 | + * page, rather than restarting from the beginning. | |
| 269 | + * <p> | |
| 270 | + * You get the paging state from a previous execution of the statement. This is typically | |
| 271 | + * used to iterate in a "stateless" manner (e.g. across HTTP requests): | |
| 272 | + * <pre> | |
| 273 | + * {@code | |
| 274 | + * Statement st = new SimpleStatement("your query"); | |
| 275 | + * ResultSet rs = session.execute(st.setFetchSize(20)); | |
| 276 | + * int available = rs.getAvailableWithoutFetching(); | |
| 277 | + * for (int i = 0; i < available; i++) { | |
| 278 | + * Row row = rs.one(); | |
| 279 | + * // Do something with row (e.g. display it to the user...) | |
| 280 | + * } | |
| 281 | + * // Get state and serialize as string or byte[] to store it for the next execution | |
| 282 | + * // (e.g. pass it as a parameter in the "next page" URI) | |
| 283 | + * PagingState pagingState = rs.getExecutionInfo().getPagingState(); | |
| 284 | + * String savedState = pagingState.toString(); | |
| 285 | + * | |
| 286 | + * // Next execution: | |
| 287 | + * // Get serialized state back (e.g. get URI parameter) | |
| 288 | + * String savedState = ... | |
| 289 | + * Statement st = new SimpleStatement("your query"); | |
| 290 | + * st.setPagingState(PagingState.fromString(savedState)); | |
| 291 | + * ResultSet rs = session.execute(st.setFetchSize(20)); | |
| 292 | + * int available = rs.getAvailableWithoutFetching(); | |
| 293 | + * for (int i = 0; i < available; i++) { | |
| 294 | + * ... | |
| 295 | + * } | |
| 296 | + * } | |
| 297 | + * </pre> | |
| 298 | + * <p> | |
| 299 | + * Note that the paging state can only be reused between perfectly identical statements | |
| 300 | + * (same query string, same bound parameters). Altering the contents of the paging state | |
| 301 | + * or trying to set it on a different statement will cause this method to fail. | |
| 302 | + * | |
| 303 | + * @param pagingState the paging state to set, or {@code null} to remove any state that was | |
| 304 | + * previously set on this statement. | |
| 305 | + * @return this {@code Statement} object. | |
| 306 | + * | |
| 307 | + * @throws PagingStateException if the paging state does not match this statement. | |
| 308 | + */ | |
| 309 | + public Statement setPagingState(PagingState pagingState) { | |
| 310 | + if (this instanceof BatchStatement) { | |
| 311 | + throw new UnsupportedOperationException("Cannot set the paging state on a batch statement"); | |
| 312 | + } else { | |
| 313 | + if (pagingState == null) { | |
| 314 | + this.pagingState = null; | |
| 315 | + } else if (pagingState.matches(this)) { | |
| 316 | + this.pagingState = pagingState.getRawState(); | |
| 317 | + } else { | |
| 318 | + throw new PagingStateException("Paging state mismatch, " | |
| 319 | + + "this means that either the paging state contents were altered, " | |
| 320 | + + "or you're trying to apply it to a different statement"); | |
| 321 | + } | |
| 322 | + } | |
| 323 | + return this; | |
| 324 | + } | |
| 325 | + | |
| 326 | + ByteBuffer getPagingState() { | |
| 327 | + return pagingState; | |
| 328 | + } | |
| 329 | +} | |
| No newline at the end of the file |
added driver-core/src/main/java/com/datastax/driver/core/exceptions/PagingStateException.java +31 −0
| @@ -0,0 +1,31 @@ | ||
| 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 | + | |
| 17 | +package com.datastax.driver.core.exceptions; | |
| 18 | + | |
| 19 | +public class PagingStateException extends DriverException { | |
| 20 | + | |
| 21 | + private static final long serialVersionUID = 0; | |
| 22 | + | |
| 23 | + public PagingStateException(String msg) { | |
| 24 | + super(msg); | |
| 25 | + } | |
| 26 | + | |
| 27 | + public PagingStateException(String msg, Throwable cause) { | |
| 28 | + super(msg, cause); | |
| 29 | + } | |
| 30 | + | |
| 31 | +} | |
| No newline at the end of the file |
modified driver-core/src/main/java/com/datastax/driver/core/utils/Bytes.java +37 −2
| @@ -100,6 +100,29 @@ | ||
| 100 | 100 | return toRawHexString(bytes, array, 2); |
| 101 | 101 | } |
| 102 | 102 | |
| 103 | + /** | |
| 104 | + * Converts a blob to its CQL hex string representation. | |
| 105 | + * <p> | |
| 106 | + * A CQL blob string representation consist of the hexadecimal | |
| 107 | + * representation of the blob bytes. | |
| 108 | + * | |
| 109 | + * @param bytes the blob/bytes to convert to a string. | |
| 110 | + * @return the CQL string representation of {@code bytes}. If {@code bytes} | |
| 111 | + * is {@code null}, this method returns {@code null}. | |
| 112 | + */ | |
| 113 | + public static String toRawHexString(ByteBuffer bytes) { | |
| 114 | + if (bytes == null) | |
| 115 | + return null; | |
| 116 | + | |
| 117 | + if (bytes.remaining() == 0) { | |
| 118 | + return ""; | |
| 119 | + } | |
| 120 | + | |
| 121 | + | |
| 122 | + char[] array = new char[2 * (bytes.remaining())]; | |
| 123 | + return toRawHexString(bytes, array, 0); | |
| 124 | + } | |
| 125 | + | |
| 103 | 126 | /** |
| 104 | 127 | * Converts a blob to its CQL hex string representation. |
| 105 | 128 | * <p> |
| @@ -165,7 +188,7 @@ | ||
| 165 | 188 | bytes.duplicate().get(array); |
| 166 | 189 | return array; |
| 167 | 190 | } |
| 168 | - | |
| 191 | + | |
| 169 | 192 | private static String toRawHexString(ByteBuffer bytes, char[] array, int offset) { |
| 170 | 193 | int size = bytes.remaining(); |
| 171 | 194 | int bytesOffset = bytes.position(); |
| @@ -178,7 +201,19 @@ | ||
| 178 | 201 | return wrapCharArray(array); |
| 179 | 202 | } |
| 180 | 203 | |
| 181 | - static byte[] fromRawHexString(String str, int strOffset) { | |
| 204 | + /** | |
| 205 | + * Converts a CQL hex string representation into a byte array. | |
| 206 | + * <p> | |
| 207 | + * A CQL blob string representation consist of the hexadecimal | |
| 208 | + * representation of the blob bytes. | |
| 209 | + * | |
| 210 | + * @param str the string converted in hex representation. | |
| 211 | + * @param strOffset he offset for starting the string conversion | |
| 212 | + * | |
| 213 | + * @return the byte array which the String was representing. | |
| 214 | + */ | |
| 215 | + | |
| 216 | + public static byte[] fromRawHexString(String str, int strOffset) { | |
| 182 | 217 | byte[] bytes = new byte[(str.length() - strOffset) / 2]; |
| 183 | 218 | for (int i = 0; i < bytes.length; i++) { |
| 184 | 219 | byte halfByte1 = charToByte[str.charAt(strOffset + i * 2)]; |
added driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +197 −0
| @@ -0,0 +1,197 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.util.Collection; | |
| 4 | +import java.util.Collections; | |
| 5 | +import java.util.Iterator; | |
| 6 | + | |
| 7 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 8 | +import org.slf4j.Logger; | |
| 9 | +import org.slf4j.LoggerFactory; | |
| 10 | +import org.testng.annotations.BeforeClass; | |
| 11 | +import org.testng.annotations.Test; | |
| 12 | + | |
| 13 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 14 | + | |
| 15 | +import com.datastax.driver.core.exceptions.PagingStateException; | |
| 16 | + | |
| 17 | +public class PagingStateTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 18 | + private static final Logger logger = LoggerFactory.getLogger(PagingStateTest.class); | |
| 19 | + public static final String KEY = "paging_test"; | |
| 20 | + | |
| 21 | + @Override | |
| 22 | + protected Collection<String> getTableDefinitions() { | |
| 23 | + return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))"); | |
| 24 | + } | |
| 25 | + | |
| 26 | + @BeforeClass(groups = "short") | |
| 27 | + public void initData() { | |
| 28 | + for (int i = 0; i < 100; i++) { | |
| 29 | + session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", KEY, i)); | |
| 30 | + } | |
| 31 | + } | |
| 32 | + | |
| 33 | + /** | |
| 34 | + * Validates that {@link PagingState} can be reused with the same Statement. | |
| 35 | + * | |
| 36 | + * @test_category paging | |
| 37 | + * @expected_result {@link ResultSet} from the query with the provided {@link PagingState} starts from the | |
| 38 | + * subsequent row from the first query. | |
| 39 | + */ | |
| 40 | + @Test(groups = "short") | |
| 41 | + public void should_complete_when_using_paging_state() { | |
| 42 | + SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY)); | |
| 43 | + ResultSet result = session.execute(st.setFetchSize(20)); | |
| 44 | + int pageSize = result.getAvailableWithoutFetching(); | |
| 45 | + String savedPagingStateString = result.getExecutionInfo().getPagingState().toString(); | |
| 46 | + | |
| 47 | + st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY)); | |
| 48 | + result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString))); | |
| 49 | + | |
| 50 | + //We have the result starting from the next page we stopped | |
| 51 | + assertThat(result.one().getInt("v")).isEqualTo(pageSize); | |
| 52 | + } | |
| 53 | + | |
| 54 | + /** | |
| 55 | + * <p> | |
| 56 | + * Validates that if the {@link PagingState} is altered in any way that it may not be reused. | |
| 57 | + * The paging state is altered in the following ways: | |
| 58 | + * | |
| 59 | + * <ol> | |
| 60 | + * <li>Altering a byte in the paging state raw bytes.</li> | |
| 61 | + * <li>Setting the {@link PagingState} on a different Statement. (should fail hash validation)</li> | |
| 62 | + * </ol> | |
| 63 | + * | |
| 64 | + * @test_category paging | |
| 65 | + * @expected_result {@link PagingState} refused to be reused if it is changed or used on a different statement. | |
| 66 | + */ | |
| 67 | + @Test(groups = "short") | |
| 68 | + public void should_fail_if_paging_state_altered() { | |
| 69 | + boolean setWithFalseContent = false; | |
| 70 | + boolean setWithWrongStatement = false; | |
| 71 | + | |
| 72 | + SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY)); | |
| 73 | + ResultSet result = session.execute(st.setFetchSize(20)); | |
| 74 | + | |
| 75 | + PagingState savedPagingState = result.getExecutionInfo().getPagingState(); | |
| 76 | + byte[] savedPagingStateBuffer = savedPagingState.toBytes(); | |
| 77 | + String savedPagingStateString = savedPagingState.toString(); | |
| 78 | + | |
| 79 | + // corrupting the paging state | |
| 80 | + savedPagingStateBuffer[6] = (byte)42; | |
| 81 | + | |
| 82 | + try { | |
| 83 | + st.setFetchSize(20).setPagingState(PagingState.fromBytes(savedPagingStateBuffer)); | |
| 84 | + } catch (PagingStateException e) { | |
| 85 | + setWithFalseContent = true; | |
| 86 | + logger.debug(e.getMessage()); | |
| 87 | + } finally { | |
| 88 | + assertThat(setWithFalseContent).isTrue(); | |
| 89 | + assertThat(st.getPagingState()).isNull(); | |
| 90 | + } | |
| 91 | + | |
| 92 | + // Changing the statement | |
| 93 | + st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", "paging")); | |
| 94 | + try { | |
| 95 | + st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString)); | |
| 96 | + } catch (PagingStateException e) { | |
| 97 | + setWithWrongStatement = true; | |
| 98 | + logger.debug(e.getMessage()); | |
| 99 | + } finally { | |
| 100 | + assertThat(setWithWrongStatement).isTrue(); | |
| 101 | + assertThat(st.getPagingState()).isNull(); | |
| 102 | + } | |
| 103 | + } | |
| 104 | + | |
| 105 | + /** | |
| 106 | + * Validates that {@link PagingState} can be reused with the same {@link BoundStatement}. | |
| 107 | + * | |
| 108 | + * @test_category paging | |
| 109 | + * @expected_result {@link ResultSet} from the query with the provided paging state starts from the subsequent row | |
| 110 | + * from the first query. | |
| 111 | + */ | |
| 112 | + @Test(groups = "short") | |
| 113 | + @CassandraVersion(major=2.0) | |
| 114 | + public void should_be_able_to_use_state_with_bound_statement() { | |
| 115 | + PreparedStatement prepared = session.prepare("SELECT v from test where k=?"); | |
| 116 | + BoundStatement bs = prepared.bind(KEY); | |
| 117 | + | |
| 118 | + ResultSet result = session.execute(bs.setFetchSize(20)); | |
| 119 | + int pageSize = result.getAvailableWithoutFetching(); | |
| 120 | + PagingState pagingState = result.getExecutionInfo().getPagingState(); | |
| 121 | + | |
| 122 | + result = session.execute(bs.setFetchSize(20).setPagingState(pagingState)); | |
| 123 | + | |
| 124 | + //We have the result starting from the next page we stopped | |
| 125 | + assertThat(result.one().getInt("v")).isEqualTo(pageSize); | |
| 126 | + } | |
| 127 | + | |
| 128 | + /** | |
| 129 | + * Validates that {@link PagingState} cannot be reused with a different {@link BoundStatement} than the original, | |
| 130 | + * even if its source {@link PreparedStatement} was the same. | |
| 131 | + * | |
| 132 | + * @test_category paging | |
| 133 | + * @expected_result A failure is thrown when setting paging state on a different {@link BoundStatement}. | |
| 134 | + */ | |
| 135 | + @Test(groups = "short", expectedExceptions = {PagingStateException.class}) | |
| 136 | + @CassandraVersion(major=2.0) | |
| 137 | + public void should_not_be_able_to_use_state_with_different_bound_statement() { | |
| 138 | + PreparedStatement prepared = session.prepare("SELECT v from test where k=?"); | |
| 139 | + BoundStatement bs0 = prepared.bind(KEY); | |
| 140 | + | |
| 141 | + ResultSet result = session.execute(bs0.setFetchSize(20)); | |
| 142 | + PagingState pagingState = result.getExecutionInfo().getPagingState(); | |
| 143 | + | |
| 144 | + BoundStatement bs1 = prepared.bind("different_key"); | |
| 145 | + session.execute(bs1.setFetchSize(20).setPagingState(pagingState)); | |
| 146 | + } | |
| 147 | + | |
| 148 | + /** | |
| 149 | + * Validates if all results of a query are paged in through a queries result set that the {@link PagingState} it | |
| 150 | + * returns will return an empty set when queried with. | |
| 151 | + * | |
| 152 | + * @test_category paging | |
| 153 | + * @expected_result Query with the {@link PagingState} returns 0 rows. | |
| 154 | + */ | |
| 155 | + @Test(groups = "short") | |
| 156 | + public void should_return_no_rows_when_paged_to_end() { | |
| 157 | + SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY)); | |
| 158 | + ResultSet result = session.execute(st.setFetchSize(20)); | |
| 159 | + | |
| 160 | + // Consume enough of the iterator to cause all the results to be paged in. | |
| 161 | + Iterator<Row> rowIt = result.iterator(); | |
| 162 | + for (int i = 0; i < 83; i++) { | |
| 163 | + rowIt.next().getInt("v"); | |
| 164 | + } | |
| 165 | + | |
| 166 | + String savedPagingStateString = result.getExecutionInfo().getPagingState().toString(); | |
| 167 | + | |
| 168 | + st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY)); | |
| 169 | + result = session.execute(st.setFetchSize(20).setPagingState(PagingState.fromString(savedPagingStateString))); | |
| 170 | + | |
| 171 | + assertThat(result.one()).isNull(); | |
| 172 | + } | |
| 173 | + | |
| 174 | + @Test(groups = "unit", expectedExceptions = {PagingStateException.class}) | |
| 175 | + public void should_fail_when_given_invalid_string() { | |
| 176 | + // An invalid string cannot be parsed and a PagingStateException is thrown. | |
| 177 | + PagingState.fromString("0101"); | |
| 178 | + } | |
| 179 | + | |
| 180 | + @Test(groups = "unit", expectedExceptions = {PagingStateException.class}) | |
| 181 | + public void should_fail_when_given_invalid_byte_array() { | |
| 182 | + // Given an expected page state of size 1 and hash of size 1, we should expect 6 bytes, but only receive 5. | |
| 183 | + byte[] complete = { 0x00, 0x01, 0x00, 0x01, 0x00 }; | |
| 184 | + PagingState.fromBytes(complete); | |
| 185 | + } | |
| 186 | + | |
| 187 | + @Test(groups = "unit", expectedExceptions = {UnsupportedOperationException.class}) | |
| 188 | + public void should_fail_when_setting_paging_state_on_batch_statement() { | |
| 189 | + // Should not be able to set paging state on a batch statement. | |
| 190 | + PagingState emptyStatement = PagingState.fromString("00000000"); | |
| 191 | + | |
| 192 | + BatchStatement batch = new BatchStatement(); | |
| 193 | + batch.setPagingState(emptyStatement); | |
| 194 | + } | |
| 195 | + | |
| 196 | +} | |
| 197 | + |