Elffuss BraidHub

kikocis/java-driver public

Merge branch '3.0.x' into 3.1.x
Changesetabdd6dc3f2811d5cd7395c439650c0b931d0eb305b995ee9dfa4a0887e8442b8
Authorolim7t <omichallat+github@gmail.com> · 2016-09-30 10:08 -07:00
Committerolim7t <omichallat+github@gmail.com> · 2016-09-30 10:10 -07:00
Parents1918c7803ffc, 9504c653c731

Browse the files at this changeset

67 files changed

modified changelog/README.md +21 −0
@@ -1,5 +1,26 @@
11 ## Changelog
22
3+### 3.1.1
4+
5+Merged from 3.0.x:
6+
7+- [improvement] JAVA-1246: Driver swallows the real exception in a few cases
8+- [improvement] JAVA-1261: Throw error when attempting to page in I/O thread.
9+- [bug] JAVA-1258: Regression: Mapper cannot map a materialized view after JAVA-1126.
10+- [bug] JAVA-1101: Batch and BatchStatement should consider inner statements to determine query idempotence
11+- [improvement] JAVA-1262: Use ParseUtils for quoting & unquoting.
12+- [improvement] JAVA-1275: Use Netty's default thread factory
13+- [bug] JAVA-1285: QueryBuilder routing key auto-discovery should handle case-sensitive column names.
14+- [bug] JAVA-1283: Don't cache failed query preparations in the mapper.
15+- [improvement] JAVA-1277: Expose AbstractSession.checkNotInEventLoop.
16+- [bug] JAVA-1272: BuiltStatement not able to print its query string if it contains mapped UDTs.
17+- [bug] JAVA-1292: 'Adjusted frame length' error breaks driver's ability to read data.
18+- [improvement] JAVA-1293: Make DecoderForStreamIdSize.MAX_FRAME_LENGTH configurable.
19+- [improvement] JAVA-1053: Add a metric for authentication errors
20+- [improvement] JAVA-1263: Eliminate unnecessary memory copies in FrameCompressor implementations.
21+- [improvement] JAVA-893: Make connection pool non-blocking
22+
23+
324 ### 3.1.0
425
526 - [new feature] JAVA-1153: Add PER PARTITION LIMIT to Select QueryBuilder.
modified clirr-ignores.xml +12 −1
@@ -19,7 +19,6 @@
1919 <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
2020 </difference>
2121
22-
2322 <difference>
2423 <differenceType>1001</differenceType> <!-- decreased visibility -->
2524 <className>com/datastax/driver/mapping/ColumnMapper$Kind</className>
@@ -136,4 +135,16 @@
136135 <justification>Introduced more generic parent type PercentileTracker (API was marked as beta and still subject to change)</justification>
137136 </difference>
138137
138+ <difference>
139+ <differenceType>8001</differenceType> <!-- class removed -->
140+ <className>com/datastax/driver/core/FrameCompressor$SnappyCompressor</className>
141+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
142+ </difference>
143+
144+ <difference>
145+ <differenceType>8001</differenceType> <!-- class removed -->
146+ <className>com/datastax/driver/core/FrameCompressor$LZ4Compressor</className>
147+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
148+ </difference>
149+
139150 </differences>
modified driver-core/pom.xml +2 −0
@@ -342,6 +342,8 @@
342342 <include>**/ControlConnectionTest.java</include>
343343 <include>**/ExtendedPeerCheckDisabledTest.java</include>
344344 <include>**/UUIDsPID*.java</include>
345+ <include>**/FrameLengthTest.java</include>
346+ <include>**/HeapCompressionTest.java</include>
345347 </includes>
346348 </configuration>
347349 </plugin>
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +30 −5
@@ -19,6 +19,7 @@
1919 import com.google.common.util.concurrent.Futures;
2020 import com.google.common.util.concurrent.ListenableFuture;
2121 import com.google.common.util.concurrent.Uninterruptibles;
22+import io.netty.util.concurrent.EventExecutor;
2223
2324 import java.nio.ByteBuffer;
2425 import java.util.Map;
@@ -31,6 +32,9 @@
3132 */
3233 public abstract class AbstractSession implements Session {
3334
35+ private static final boolean CHECK_IO_DEADLOCKS = SystemProperties.getBoolean(
36+ "com.datastax.driver.CHECK_IO_DEADLOCKS", true);
37+
3438 /**
3539 * {@inheritDoc}
3640 */
@@ -131,12 +135,12 @@
131135 if (statement.hasValues())
132136 throw new IllegalArgumentException("A statement to prepare should not have values");
133137
134- ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.getQueryString(), statement.getOutgoingPayload());
138+ final CodecRegistry codecRegistry = getCluster().getConfiguration().getCodecRegistry();
139+ ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.getQueryString(codecRegistry), statement.getOutgoingPayload());
135140 return Futures.transform(prepared, new Function<PreparedStatement, PreparedStatement>() {
136141 @Override
137142 public PreparedStatement apply(PreparedStatement prepared) {
138143 ProtocolVersion protocolVersion = getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
139- CodecRegistry codecRegistry = getCluster().getConfiguration().getCodecRegistry();
140144 ByteBuffer routingKey = statement.getRoutingKey(protocolVersion, codecRegistry);
141145 if (routingKey != null)
142146 prepared.setRoutingKey(routingKey);
@@ -179,9 +183,30 @@
179183 /**
180184 * Checks that the current thread is not one of the Netty I/O threads used by the driver.
181185 * <p/>
182- * This is called from the synchronous methods of this class to prevent deadlock issues.
186+ * This method is called from all the synchronous methods of this class to prevent deadlock issues.
187+ * <p/>
188+ * User code extending this class can also call this method at any time to check if any code
189+ * making blocking calls is being wrongly executed on a Netty I/O thread.
190+ * <p/>
191+ * Note that the check performed by this method has a small overhead; if
192+ * that is an issue, checks can be disabled by setting the System property
193+ * {@code com.datastax.driver.CHECK_IO_DEADLOCKS} to {@code false}.
194+ *
195+ * @throws IllegalStateException if the current thread is one of the Netty I/O thread used by the driver.
183196 */
184- protected void checkNotInEventLoop() {
185- // This method is concrete only to avoid a breaking change. See subclass for the actual implementation.
197+ public void checkNotInEventLoop() {
198+ Connection.Factory connectionFactory = getCluster().manager.connectionFactory;
199+ if (!CHECK_IO_DEADLOCKS || connectionFactory == null)
200+ return;
201+ for (EventExecutor executor : connectionFactory.eventLoopGroup) {
202+ if (executor.inEventLoop()) {
203+ throw new IllegalStateException(
204+ "Detected a synchronous call on an I/O thread, this can cause deadlocks or unpredictable " +
205+ "behavior. This generally happens when a Future callback calls a synchronous Session " +
206+ "method (execute() or prepare()), or iterates a result set past the fetch size " +
207+ "(causing an internal synchronous fetch of the next page of results). " +
208+ "Avoid this in your callbacks, or schedule them on a different executor.");
209+ }
210+ }
186211 }
187212 }
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −0
@@ -307,6 +307,7 @@
307307 // We need to know if there is more result, so fetch the next page and
308308 // wait on it.
309309 try {
310+ session.checkNotInEventLoop();
310311 Uninterruptibles.getUninterruptibly(fetchMoreResults());
311312 } catch (ExecutionException e) {
312313 throw DriverThrowables.propagateCause(e);
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +9 −1
@@ -90,7 +90,7 @@
9090 if (statement instanceof RegularStatement) {
9191 RegularStatement st = (RegularStatement) statement;
9292 ByteBuffer[] vals = st.getValues(protocolVersion, codecRegistry);
93- String query = st.getQueryString();
93+ String query = st.getQueryString(codecRegistry);
9494 idAndVals.ids.add(query);
9595 idAndVals.values.add(vals == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(vals));
9696 } else {
@@ -243,6 +243,14 @@
243243 return null;
244244 }
245245
246+ @Override
247+ public Boolean isIdempotent() {
248+ if (idempotent != null) {
249+ return idempotent;
250+ }
251+ return isBatchIdempotent(statements);
252+ }
253+
246254 void ensureAllSet() {
247255 for (Statement statement : statements)
248256 if (statement instanceof BoundStatement)
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +10 −2
@@ -25,6 +25,7 @@
2525 import com.google.common.base.Throwables;
2626 import com.google.common.collect.*;
2727 import com.google.common.util.concurrent.*;
28+import io.netty.util.concurrent.DefaultThreadFactory;
2829 import org.slf4j.Logger;
2930 import org.slf4j.LoggerFactory;
3031
@@ -852,7 +853,7 @@
852853 addContactPoints(InetAddress.getAllByName(address));
853854 return this;
854855 } catch (UnknownHostException e) {
855- throw new IllegalArgumentException(e.getMessage());
856+ throw new IllegalArgumentException("Failed to add contact point: " + address, e);
856857 }
857858 }
858859
@@ -1544,7 +1545,14 @@
15441545 }
15451546
15461547 ThreadFactory threadFactory(String name) {
1547- return new ThreadFactoryBuilder().setNameFormat(clusterName + "-" + name + "-%d").build();
1548+ return new ThreadFactoryBuilder()
1549+ .setNameFormat(clusterName + "-" + name + "-%d")
1550+ // Back with Netty's thread factory in order to create FastThreadLocalThread instances. This allows
1551+ // an optimization around ThreadLocals (we could use DefaultThreadFactory directly but it creates
1552+ // slightly different thread names, so keep we keep a ThreadFactoryBuilder wrapper for backward
1553+ // compatibility).
1554+ .setThreadFactory(new DefaultThreadFactory("ignored name"))
1555+ .build();
15481556 }
15491557
15501558 private ListeningExecutorService makeExecutor(int threads, String name, LinkedBlockingQueue<Runnable> workQueue) {
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +130 −25
@@ -19,6 +19,7 @@
1919 import com.datastax.driver.core.exceptions.*;
2020 import com.datastax.driver.core.utils.MoreFutures;
2121 import com.google.common.annotations.VisibleForTesting;
22+import com.google.common.base.Objects;
2223 import com.google.common.collect.Lists;
2324 import com.google.common.collect.MapMaker;
2425 import com.google.common.util.concurrent.*;
@@ -27,6 +28,7 @@
2728 import io.netty.channel.group.ChannelGroup;
2829 import io.netty.channel.group.DefaultChannelGroup;
2930 import io.netty.channel.socket.SocketChannel;
31+import io.netty.handler.codec.DecoderException;
3032 import io.netty.handler.timeout.IdleStateEvent;
3133 import io.netty.handler.timeout.IdleStateHandler;
3234 import io.netty.util.Timeout;
@@ -84,7 +86,9 @@
8486 final AtomicInteger inFlight = new AtomicInteger(0);
8587
8688 private final AtomicInteger writer = new AtomicInteger(0);
87- private volatile String keyspace;
89+
90+ private final AtomicReference<SetKeyspaceAttempt> targetKeyspace;
91+ private final SetKeyspaceAttempt defaultKeyspaceAttempt;
8892
8993 private volatile boolean isInitialized;
9094 private final AtomicBoolean isDefunct = new AtomicBoolean();
@@ -94,8 +98,9 @@
9498
9599 private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>();
96100
101+ private final ListenableFuture<Connection> thisFuture;
102+
97103 /**
98- * /**
99104 * Create a new connection to a Cassandra node and associate it with the given pool.
100105 *
101106 * @param name the connection name
@@ -110,6 +115,9 @@
110115 this.dispatcher = new Dispatcher();
111116 this.name = name;
112117 this.ownerRef.set(owner);
118+ this.thisFuture = Futures.immediateFuture(this);
119+ this.defaultKeyspaceAttempt = new SetKeyspaceAttempt(null, thisFuture);
120+ this.targetKeyspace = new AtomicReference<SetKeyspaceAttempt>(defaultKeyspaceAttempt);
113121 }
114122
115123 /**
@@ -248,7 +256,13 @@
248256 throw new TransportException(address, String.format("Error initializing connection: %s", error.message));
249257 case AUTHENTICATE:
250258 Responses.Authenticate authenticate = (Responses.Authenticate) response;
251- Authenticator authenticator = factory.authProvider.newAuthenticator(address, authenticate.authenticator);
259+ Authenticator authenticator;
260+ try {
261+ authenticator = factory.authProvider.newAuthenticator(address, authenticate.authenticator);
262+ } catch (AuthenticationException e) {
263+ incrementAuthErrorMetric();
264+ throw e;
265+ }
252266 switch (protocolVersion) {
253267 case V1:
254268 if (authenticator instanceof ProtocolV1Authenticator)
@@ -319,6 +333,7 @@
319333 case READY:
320334 return checkClusterName(protocolVersion, executor);
321335 case ERROR:
336+ incrementAuthErrorMetric();
322337 throw new AuthenticationException(address, ((Responses.Error) authResponse).message);
323338 default:
324339 throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
@@ -374,6 +389,7 @@
374389 if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
375390 message = String.format("Cannot use authenticator %s with protocol version 1, "
376391 + "only plain text authentication is supported with this protocol version", authenticator);
392+ incrementAuthErrorMetric();
377393 throw new AuthenticationException(address, message);
378394 default:
379395 throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type));
@@ -382,6 +398,12 @@
382398 };
383399 }
384400
401+ private void incrementAuthErrorMetric() {
402+ if (factory.manager.configuration.getMetricsOptions().isEnabled()) {
403+ factory.manager.metrics.getErrorMetrics().getAuthenticationErrors().inc();
404+ }
405+ }
406+
385407 private UnsupportedProtocolVersionException unsupportedProtocolVersionException(ProtocolVersion triedVersion, ProtocolVersion serverProtocolVersion) {
386408 logger.debug("Got unsupported protocol version error from {} for version {} server supports version {}", address, triedVersion, serverProtocolVersion);
387409 return new UnsupportedProtocolVersionException(address, triedVersion, serverProtocolVersion);
@@ -403,7 +425,6 @@
403425 else if (Host.statesLogger.isDebugEnabled())
404426 Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage());
405427
406-
407428 Host host = factory.manager.metadata.getHost(address);
408429 if (host != null) {
409430 // Sometimes close() can be called before defunct(); avoid decrementing the connection count twice, but
@@ -437,14 +458,14 @@
437458 }
438459
439460 String keyspace() {
440- return keyspace;
461+ return targetKeyspace.get().keyspace;
441462 }
442463
443464 void setKeyspace(String keyspace) throws ConnectionException {
444465 if (keyspace == null)
445466 return;
446467
447- if (this.keyspace != null && this.keyspace.equals(keyspace))
468+ if (Objects.equal(keyspace(), keyspace))
448469 return;
449470
450471 try {
@@ -468,24 +489,59 @@
468489 }
469490 }
470491
471- ListenableFuture<Void> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException {
472- logger.trace("{} Setting keyspace {}", this, keyspace);
473- // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
474- Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
475- return Futures.transform(future, new AsyncFunction<Message.Response, Void>() {
476- @Override
477- public ListenableFuture<Void> apply(Message.Response response) throws Exception {
478- if (response instanceof SetKeyspace) {
479- Connection.this.keyspace = ((SetKeyspace) response).keyspace;
480- return MoreFutures.VOID_SUCCESS;
481- } else if (response.type == ERROR) {
482- Responses.Error error = (Responses.Error) response;
483- throw defunct(error.asException(address));
484- } else {
485- throw defunct(new DriverInternalError("Unexpected response while setting keyspace: " + response));
486- }
492+ ListenableFuture<Connection> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException {
493+ SetKeyspaceAttempt existingAttempt = targetKeyspace.get();
494+ if (Objects.equal(existingAttempt.keyspace, keyspace))
495+ return existingAttempt.future;
496+
497+ final SettableFuture<Connection> ksFuture = SettableFuture.create();
498+ final SetKeyspaceAttempt attempt = new SetKeyspaceAttempt(keyspace, ksFuture);
499+
500+ // Check for an existing keyspace attempt.
501+ while (true) {
502+ existingAttempt = targetKeyspace.get();
503+ // if existing attempts' keyspace matches what we are trying to set, use it.
504+ if (attempt.equals(existingAttempt)) {
505+ return existingAttempt.future;
506+ } else if (!existingAttempt.future.isDone()) {
507+ // If the existing attempt is still in flight, fail this attempt immediately.
508+ ksFuture.setException(new DriverException("Aborting attempt to set keyspace to '" + keyspace + "' since there is already an in flight attempt to set keyspace to '" + existingAttempt.keyspace + "'. "
509+ + "This can happen if you try to USE different keyspaces from the same session simultaneously."));
510+ return ksFuture;
511+ } else if (targetKeyspace.compareAndSet(existingAttempt, attempt)) {
512+ // Otherwise, if the existing attempt is done, start a new set keyspace attempt for the new keyspace.
513+ logger.debug("{} Setting keyspace {}", this, keyspace);
514+ // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
515+ Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
516+ Futures.addCallback(future, new FutureCallback<Message.Response>() {
517+
518+ @Override
519+ public void onSuccess(Message.Response response) {
520+ if (response instanceof SetKeyspace) {
521+ logger.debug("{} Keyspace set to {}", Connection.this, keyspace);
522+ ksFuture.set(Connection.this);
523+ } else {
524+ // Unset this attempt so new attempts may be made for the same keyspace.
525+ targetKeyspace.compareAndSet(attempt, defaultKeyspaceAttempt);
526+ if (response.type == ERROR) {
527+ Responses.Error error = (Responses.Error) response;
528+ ksFuture.setException(defunct(error.asException(address)));
529+ } else {
530+ ksFuture.setException(defunct(new DriverInternalError("Unexpected response while setting keyspace: " + response)));
531+ }
532+ }
533+ }
534+
535+ @Override
536+ public void onFailure(Throwable t) {
537+ targetKeyspace.compareAndSet(attempt, defaultKeyspaceAttempt);
538+ ksFuture.setException(t);
539+ }
540+ }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor());
541+
542+ return ksFuture;
487543 }
488- }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor());
544+ }
489545 }
490546
491547 /**
@@ -993,7 +1049,7 @@
9931049 ResponseHandler handler = pending.remove(streamId);
9941050 streamIdHandler.release(streamId);
9951051 if (handler == null) {
996- /**
1052+ /*
9971053 * During normal operation, we should not receive responses for which we don't have a handler. There is
9981054 * two cases however where this can happen:
9991055 * 1) The connection has been defuncted due to some internal error and we've raced between removing the
@@ -1046,6 +1102,27 @@
10461102 if (writer.get() > 0)
10471103 return;
10481104
1105+ if (cause instanceof DecoderException) {
1106+ Throwable error = cause.getCause();
1107+ // Special case, if we encountered a FrameTooLongException, raise exception on handler and don't defunct it since
1108+ // the connection is in an ok state.
1109+ if (error != null && error instanceof FrameTooLongException) {
1110+ FrameTooLongException ftle = (FrameTooLongException) error;
1111+ int streamId = ftle.getStreamId();
1112+ ResponseHandler handler = pending.remove(streamId);
1113+ streamIdHandler.release(streamId);
1114+ if (handler == null) {
1115+ streamIdHandler.unmark(streamId);
1116+ if (logger.isDebugEnabled())
1117+ logger.debug("{} FrameTooLongException received on stream {} but no handler set anymore (either the request has "
1118+ + "timed out or it was closed due to another error).", Connection.this, streamId);
1119+ return;
1120+ }
1121+ handler.cancelTimeout();
1122+ handler.callback.onException(Connection.this, ftle, System.nanoTime() - handler.startTime, handler.retryCount);
1123+ return;
1124+ }
1125+ }
10491126 defunct(new TransportException(address, String.format("Unexpected exception triggered (%s)", cause), cause));
10501127 }
10511128
@@ -1145,6 +1222,34 @@
11451222 }
11461223 }
11471224
1225+ private class SetKeyspaceAttempt {
1226+ private final String keyspace;
1227+ private final ListenableFuture<Connection> future;
1228+
1229+ SetKeyspaceAttempt(String keyspace, ListenableFuture<Connection> future) {
1230+ this.keyspace = keyspace;
1231+ this.future = future;
1232+ }
1233+
1234+ @Override
1235+ public boolean equals(Object o) {
1236+ if (this == o)
1237+ return true;
1238+ if (!(o instanceof SetKeyspaceAttempt))
1239+ return false;
1240+
1241+ SetKeyspaceAttempt that = (SetKeyspaceAttempt) o;
1242+
1243+ return keyspace != null ? keyspace.equals(that.keyspace) : that.keyspace == null;
1244+
1245+ }
1246+
1247+ @Override
1248+ public int hashCode() {
1249+ return keyspace != null ? keyspace.hashCode() : 0;
1250+ }
1251+ }
1252+
11481253 static class Future extends AbstractFuture<Message.Response> implements RequestHandler.Callback {
11491254
11501255 private final Message.Request request;
@@ -1314,7 +1419,7 @@
13141419 pipeline.addLast("ssl", sslOptions.newSSLHandler(channel));
13151420 }
13161421
1317-// pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO));
1422+ // pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO));
13181423
13191424 pipeline.addLast("frameDecoder", new Frame.Decoder());
13201425 pipeline.addLast("frameEncoder", frameEncoder);
modified driver-core/src/main/java/com/datastax/driver/core/Frame.java +29 −20
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.datastax.driver.core.exceptions.FrameTooLongException;
1920 import io.netty.buffer.ByteBuf;
2021 import io.netty.channel.ChannelHandler;
2122 import io.netty.channel.ChannelHandlerContext;
@@ -189,42 +190,44 @@
189190 }
190191
191192 static final class Decoder extends ByteToMessageDecoder {
192- static final DecoderForStreamIdSize decoderV1 = new DecoderForStreamIdSize(1);
193- static final DecoderForStreamIdSize decoderV3 = new DecoderForStreamIdSize(2);
193+ private DecoderForStreamIdSize decoder;
194194
195195 @Override
196196 protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
197197 if (buffer.readableBytes() < 1)
198198 return;
199199
200- int version = buffer.getByte(0);
201- // version first bit is the "direction" of the frame (request or response)
202- version = version & 0x7F;
200+ // Initialize sub decoder on first message. No synchronization needed as
201+ // decode is always called from same thread.
202+ if (decoder == null) {
203+ int version = buffer.getByte(buffer.readerIndex());
204+ // version first bit is the "direction" of the frame (request or response)
205+ version = version & 0x7F;
206+ decoder = new DecoderForStreamIdSize(version, version >= 3 ? 2 : 1);
207+ }
203208
204- DecoderForStreamIdSize decoder = (version >= 3) ? decoderV3 : decoderV1;
205209 Object frame = decoder.decode(ctx, buffer);
206210 if (frame != null)
207211 out.add(frame);
208212 }
209213
210214 static class DecoderForStreamIdSize extends LengthFieldBasedFrameDecoder {
211- private static final int MAX_FRAME_LENGTH = 256 * 1024 * 1024; // 256 MB
212- private final int opcodeOffset;
213-
214- DecoderForStreamIdSize(int streamIdSize) {
215+ // The maximum response frame length allowed. Note that C* does not currently restrict the length of its responses (CASSANDRA-12630).
216+ private static final int MAX_FRAME_LENGTH = SystemProperties.getInt("com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB", 256) * 1024 * 1024; // 256 MB
217+ private final int protocolVersion;
218+
219+ DecoderForStreamIdSize(int protocolVersion, int streamIdSize) {
215220 super(MAX_FRAME_LENGTH, /*lengthOffset=*/ 3 + streamIdSize, 4, 0, 0, true);
216- this.opcodeOffset = 2 + streamIdSize;
221+ this.protocolVersion = protocolVersion;
217222 }
218223
219224 @Override
220225 protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
226+ // Capture current index in case we need to get the stream id.
227+ // If a TooLongFrameException is thrown the readerIndex will advance to the end of
228+ // the buffer (or past the frame) so we need the position as we entered this method.
229+ int curIndex = buffer.readerIndex();
221230 try {
222- if (buffer.readableBytes() < opcodeOffset + 1)
223- return null;
224-
225- // Validate the opcode (this will throw if it's not a response)
226- Message.Response.Type.fromOpcode(buffer.getByte(opcodeOffset));
227-
228231 ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);
229232 if (frame == null) {
230233 return null;
@@ -232,11 +235,17 @@
232235 // Do not deallocate `frame` just yet, because it is stored as Frame.body and will be used
233236 // in Message.ProtocolDecoder or Frame.Decompressor if compression is enabled (we deallocate
234237 // it there).
235- return Frame.create(frame);
238+ Frame theFrame = Frame.create(frame);
239+ // Validate the opcode (this will throw if it's not a response)
240+ Message.Response.Type.fromOpcode(theFrame.header.opcode);
241+ return theFrame;
236242 } catch (CorruptedFrameException e) {
237- throw new DriverInternalError(e.getMessage());
243+ throw new DriverInternalError(e);
238244 } catch (TooLongFrameException e) {
239- throw new DriverInternalError(e.getMessage());
245+ int streamId = protocolVersion > 2 ?
246+ buffer.getShort(curIndex + 2) :
247+ buffer.getByte(curIndex + 2);
248+ throw new FrameTooLongException(streamId);
240249 }
241250 }
242251 }
modified driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java +14 −124
@@ -15,138 +15,28 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.datastax.driver.core.exceptions.DriverInternalError;
19-import io.netty.buffer.Unpooled;
20-import net.jpountz.lz4.LZ4Factory;
21-import org.slf4j.Logger;
22-import org.slf4j.LoggerFactory;
23-import org.xerial.snappy.Snappy;
18+import io.netty.buffer.ByteBuf;
2419
2520 import java.io.IOException;
21+import java.nio.ByteBuffer;
2622
2723 abstract class FrameCompressor {
2824
29- private static final Logger logger = LoggerFactory.getLogger(FrameCompressor.class);
25+ abstract Frame compress(Frame frame) throws IOException;
3026
31- public abstract Frame compress(Frame frame) throws IOException;
27+ abstract Frame decompress(Frame frame) throws IOException;
3228
33- public abstract Frame decompress(Frame frame) throws IOException;
34-
35- public static class SnappyCompressor extends FrameCompressor {
36-
37- public static final SnappyCompressor instance;
38-
39- static {
40- SnappyCompressor i;
41- try {
42- i = new SnappyCompressor();
43- } catch (NoClassDefFoundError e) {
44- i = null;
45- logger.warn("Cannot find Snappy class, you should make sure the Snappy library is in the classpath if you intend to use it. Snappy compression will not be available for the protocol.");
46- } catch (Throwable e) {
47- i = null;
48- logger.warn("Error loading Snappy library ({}). Snappy compression will not be available for the protocol.", e.toString());
49- }
50- instance = i;
51- }
52-
53- private SnappyCompressor() {
54- // this would throw java.lang.NoClassDefFoundError if Snappy class
55- // wasn't found at runtime which should be processed by the calling method
56- Snappy.getNativeLibraryVersion();
57- }
58-
59- @Override
60- public Frame compress(Frame frame) throws IOException {
61- byte[] input = CBUtil.readRawBytes(frame.body);
62- byte[] output = new byte[Snappy.maxCompressedLength(input.length)];
63-
64- int written = Snappy.compress(input, 0, input.length, output, 0);
65- return frame.with(Unpooled.wrappedBuffer(output, 0, written));
66- }
67-
68- @Override
69- public Frame decompress(Frame frame) throws IOException {
70- byte[] input = CBUtil.readRawBytes(frame.body);
71-
72- if (!Snappy.isValidCompressedBuffer(input, 0, input.length))
73- throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");
74-
75- byte[] output = new byte[Snappy.uncompressedLength(input)];
76- int size = Snappy.uncompress(input, 0, input.length, output, 0);
77- return frame.with(Unpooled.wrappedBuffer(output, 0, size));
78- }
29+ protected static ByteBuffer inputNioBuffer(ByteBuf buf) {
30+ // Using internalNioBuffer(...) as we only hold the reference in this method and so can
31+ // reduce Object allocations.
32+ int index = buf.readerIndex();
33+ int len = buf.readableBytes();
34+ return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len);
7935 }
8036
81- public static class LZ4Compressor extends FrameCompressor {
82-
83- public static final LZ4Compressor instance;
84-
85- static {
86- LZ4Compressor i;
87- try {
88- i = new LZ4Compressor();
89- } catch (NoClassDefFoundError e) {
90- i = null;
91- logger.warn("Cannot find LZ4 class, you should make sure the LZ4 library is in the classpath if you intend to use it. LZ4 compression will not be available for the protocol.");
92- } catch (Throwable e) {
93- i = null;
94- logger.warn("Error loading LZ4 library ({}). LZ4 compression will not be available for the protocol.", e.toString());
95- }
96- instance = i;
97- }
98-
99- private static final int INTEGER_BYTES = 4;
100- private final net.jpountz.lz4.LZ4Compressor compressor;
101- private final net.jpountz.lz4.LZ4FastDecompressor decompressor;
102-
103- private LZ4Compressor() {
104- final LZ4Factory lz4Factory = LZ4Factory.fastestInstance();
105- logger.info("Using {}", lz4Factory.toString());
106- compressor = lz4Factory.fastCompressor();
107- decompressor = lz4Factory.fastDecompressor();
108- }
109-
110- @Override
111- public Frame compress(Frame frame) throws IOException {
112- byte[] input = CBUtil.readRawBytes(frame.body);
113-
114- int maxCompressedLength = compressor.maxCompressedLength(input.length);
115- byte[] output = new byte[INTEGER_BYTES + maxCompressedLength];
116-
117- output[0] = (byte) (input.length >>> 24);
118- output[1] = (byte) (input.length >>> 16);
119- output[2] = (byte) (input.length >>> 8);
120- output[3] = (byte) (input.length);
121-
122- try {
123- int written = compressor.compress(input, 0, input.length, output, INTEGER_BYTES, maxCompressedLength);
124- return frame.with(Unpooled.wrappedBuffer(output, 0, INTEGER_BYTES + written));
125- } catch (Exception e) {
126- throw new IOException(e);
127- }
128- }
129-
130- @Override
131- public Frame decompress(Frame frame) throws IOException {
132- byte[] input = CBUtil.readRawBytes(frame.body);
133-
134- int uncompressedLength = ((input[0] & 0xFF) << 24)
135- | ((input[1] & 0xFF) << 16)
136- | ((input[2] & 0xFF) << 8)
137- | ((input[3] & 0xFF));
138-
139- byte[] output = new byte[uncompressedLength];
140-
141- try {
142- int read = decompressor.decompress(input, INTEGER_BYTES, output, 0, uncompressedLength);
143- if (read != input.length - INTEGER_BYTES)
144- throw new IOException("Compressed lengths mismatch");
145-
146- return frame.with(Unpooled.wrappedBuffer(output));
147- } catch (Exception e) {
148- throw new IOException(e);
149- }
150- }
37+ protected static ByteBuffer outputNioBuffer(ByteBuf buf) {
38+ int index = buf.writerIndex();
39+ int len = buf.writableBytes();
40+ return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len);
15141 }
15242 }
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +95 −113
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.AuthenticationException;
19+import com.datastax.driver.core.exceptions.BusyPoolException;
1920 import com.datastax.driver.core.exceptions.ConnectionException;
2021 import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
2122 import com.datastax.driver.core.utils.MoreFutures;
@@ -26,16 +27,10 @@
2627 import org.slf4j.Logger;
2728 import org.slf4j.LoggerFactory;
2829
29-import java.util.ArrayList;
30-import java.util.List;
31-import java.util.ListIterator;
32-import java.util.Set;
30+import java.util.*;
3331 import java.util.concurrent.*;
3432 import java.util.concurrent.atomic.AtomicInteger;
3533 import java.util.concurrent.atomic.AtomicReference;
36-import java.util.concurrent.locks.Condition;
37-import java.util.concurrent.locks.Lock;
38-import java.util.concurrent.locks.ReentrantLock;
3934
4035 import static com.datastax.driver.core.Connection.State.*;
4136
@@ -62,9 +57,8 @@
6257 @VisibleForTesting
6358 final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
6459
65- private volatile int waiter = 0;
66- private final Lock waitLock = new ReentrantLock(true);
67- private final Condition hasAvailableConnection = waitLock.newCondition();
60+ private final Queue<SettableFuture<Connection>> pendingBorrows = new ConcurrentLinkedQueue<SettableFuture<Connection>>();
61+ private final AtomicInteger pendingBorrowCount = new AtomicInteger();
6862
6963 private final Runnable newConnectionTask;
7064
@@ -81,7 +75,7 @@
8175 // following threshold, we just replace the connection by a new one.
8276 private final int minAllowedStreams;
8377
84- public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
78+ HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
8579 assert hostDistance != HostDistance.IGNORED;
8680 this.host = host;
8781 this.hostDistance = hostDistance;
@@ -196,17 +190,13 @@
196190 return manager.configuration().getPoolingOptions();
197191 }
198192
199- public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
193+ ListenableFuture<Connection> borrowConnection(int maxQueueSize) {
200194 Phase phase = this.phase.get();
201195 if (phase != Phase.READY)
202- // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
203- // That being said, maybe having a specific exception could be cleaner.
204- throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
196+ return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is " + phase));
205197
206198 if (connections.isEmpty()) {
207- if (!host.convictionPolicy.canReconnectNow())
208- throw new TimeoutException("Connection pool is empty, currently trying to reestablish connections");
209- else {
199+ if (host.convictionPolicy.canReconnectNow()) {
210200 int coreSize = options().getCoreConnectionsPerHost(hostDistance);
211201 if (coreSize == 0) {
212202 maybeSpawnNewConnection();
@@ -218,10 +208,7 @@
218208 manager.blockingExecutor().submit(newConnectionTask);
219209 }
220210 }
221- Connection c = waitForConnection(timeout, unit);
222- totalInFlight.incrementAndGet();
223- c.setKeyspace(manager.poolsState.keyspace);
224- return c;
211+ return enqueue(maxQueueSize);
225212 }
226213 }
227214
@@ -238,18 +225,17 @@
238225 if (leastBusy == null) {
239226 // We could have raced with a shutdown since the last check
240227 if (isClosed())
241- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
228+ return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
242229 // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
243230 // the previous check to connections and now. But in that case, the line above will have trigger the creation of
244231 // a new connection, so just wait that connection and move on
245- leastBusy = waitForConnection(timeout, unit);
232+ return enqueue(maxQueueSize);
246233 } else {
247234 while (true) {
248235 int inFlight = leastBusy.inFlight.get();
249236
250237 if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
251- leastBusy = waitForConnection(timeout, unit);
252- break;
238+ return enqueue(maxQueueSize);
253239 }
254240
255241 if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
@@ -276,96 +262,37 @@
276262 maybeSpawnNewConnection();
277263 }
278264
279- leastBusy.setKeyspace(manager.poolsState.keyspace);
280- return leastBusy;
281- }
282-
283- private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException {
284- waitLock.lock();
285- waiter++;
286- try {
287- hasAvailableConnection.await(timeout, unit);
288- } finally {
289- waiter--;
290- waitLock.unlock();
291- }
292- }
293-
294- private void signalAvailableConnection() {
295- // Quick check if it's worth signaling to avoid locking
296- if (waiter == 0)
297- return;
298-
299- waitLock.lock();
300- try {
301- hasAvailableConnection.signal();
302- } finally {
303- waitLock.unlock();
304- }
265+ return leastBusy.setKeyspaceAsync(manager.poolsState.keyspace);
305266 }
306267
307- private void signalAllAvailableConnection() {
308- // Quick check if it's worth signaling to avoid locking
309- if (waiter == 0)
310- return;
311-
312- waitLock.lock();
313- try {
314- hasAvailableConnection.signalAll();
315- } finally {
316- waitLock.unlock();
268+ private ListenableFuture<Connection> enqueue(int maxQueueSize) {
269+ if (maxQueueSize == 0) {
270+ return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), 0));
317271 }
318- }
319272
320- private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
321- if (timeout == 0)
322- throw new TimeoutException("All connections are busy and pool timeout is 0");
323-
324- long start = System.nanoTime();
325- long remaining = timeout;
326- do {
327- try {
328- awaitAvailableConnection(remaining, unit);
329- } catch (InterruptedException e) {
330- Thread.currentThread().interrupt();
331- // If we're interrupted fine, check if there is a connection available but stop waiting otherwise
332- timeout = 0; // this will make us stop the loop if we don't get a connection right away
273+ while (true) {
274+ int count = pendingBorrowCount.get();
275+ if (count >= maxQueueSize) {
276+ return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), maxQueueSize));
333277 }
334-
335- if (isClosed())
336- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
337-
338- int minInFlight = Integer.MAX_VALUE;
339- Connection leastBusy = null;
340- for (Connection connection : connections) {
341- int inFlight = connection.inFlight.get();
342- if (inFlight < minInFlight) {
343- minInFlight = inFlight;
344- leastBusy = connection;
345- }
278+ if (pendingBorrowCount.compareAndSet(count, count + 1)) {
279+ break;
346280 }
281+ }
347282
348- // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next
349- // iteration anyway
350- if (leastBusy != null) {
351- while (true) {
352- int inFlight = leastBusy.inFlight.get();
353-
354- if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance)))
355- break;
356-
357- if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
358- return leastBusy;
359- }
360- }
283+ SettableFuture<Connection> future = SettableFuture.create();
284+ pendingBorrows.add(future);
361285
362- remaining = timeout - Cluster.timeSince(start, unit);
363- } while (remaining > 0);
286+ // If we raced with shutdown, make sure the future will be completed. This has no effect if it was properly
287+ // handled in closeAsync.
288+ if (phase.get() == Phase.CLOSING) {
289+ future.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
290+ }
364291
365- throw new TimeoutException("All connections are busy");
292+ return future;
366293 }
367294
368- public void returnConnection(Connection connection) {
295+ void returnConnection(Connection connection) {
369296 connection.inFlight.decrementAndGet();
370297 totalInFlight.decrementAndGet();
371298
@@ -384,7 +311,60 @@
384311 if (connection.maxAvailableStreams() < minAllowedStreams) {
385312 replaceConnection(connection);
386313 } else {
387- signalAvailableConnection();
314+ dequeue(connection);
315+ }
316+ }
317+ }
318+
319+ // When a connection gets returned to the pool, check if there are pending borrows that can be completed with it.
320+ private void dequeue(Connection connection) {
321+ while (!pendingBorrows.isEmpty()) {
322+
323+ // We can only reuse the connection if it's under its maximum number of inFlight requests.
324+ // Do this atomically, as we could be competing with other borrowConnection or dequeue calls.
325+ while (true) {
326+ int inFlight = connection.inFlight.get();
327+ if (inFlight >= Math.min(connection.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
328+ // Connection is full again, stop dequeuing
329+ return;
330+ }
331+ if (connection.inFlight.compareAndSet(inFlight, inFlight + 1)) {
332+ // We acquired the right to reuse the connection for one request, proceed
333+ break;
334+ }
335+ }
336+
337+ final SettableFuture<Connection> pendingBorrow = pendingBorrows.poll();
338+ if (pendingBorrow == null) {
339+ // Another thread has emptied the queue since our last check, restore the count
340+ connection.inFlight.decrementAndGet();
341+ } else {
342+ totalInFlight.incrementAndGet();
343+ pendingBorrowCount.decrementAndGet();
344+ // Ensure that the keyspace set on the connection is the one set on the pool state, in the general case it will be.
345+ ListenableFuture<Connection> setKeyspaceFuture = connection.setKeyspaceAsync(manager.poolsState.keyspace);
346+ // Slight optimization, if the keyspace was already correct the future will be complete, so simply complete it here.
347+ if (setKeyspaceFuture.isDone()) {
348+ try {
349+ pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture));
350+ } catch (ExecutionException e) {
351+ pendingBorrow.setException(e.getCause());
352+ }
353+ } else {
354+ // Otherwise the keyspace did need to be set, tie the pendingBorrow future to the set keyspace completion.
355+ Futures.addCallback(setKeyspaceFuture, new FutureCallback<Connection>() {
356+
357+ @Override
358+ public void onSuccess(Connection c) {
359+ pendingBorrow.set(c);
360+ }
361+
362+ @Override
363+ public void onFailure(Throwable t) {
364+ pendingBorrow.setException(t);
365+ }
366+ });
367+ }
388368 }
389369 }
390370 }
@@ -453,6 +433,7 @@
453433 }
454434 logger.debug("Creating new connection on busy pool to {}", host);
455435 newConnection = manager.connectionFactory().open(this);
436+ newConnection.setKeyspace(manager.poolsState.keyspace);
456437 }
457438 connections.add(newConnection);
458439
@@ -465,7 +446,7 @@
465446 return false;
466447 }
467448
468- signalAvailableConnection();
449+ dequeue(newConnection);
469450 return true;
470451 } catch (InterruptedException e) {
471452 Thread.currentThread().interrupt();
@@ -600,11 +581,11 @@
600581 connection.closeAsync();
601582 }
602583
603- public final boolean isClosed() {
584+ final boolean isClosed() {
604585 return closeFuture.get() != null;
605586 }
606587
607- public final CloseFuture closeAsync() {
588+ final CloseFuture closeAsync() {
608589
609590 CloseFuture future = closeFuture.get();
610591 if (future != null)
@@ -612,8 +593,9 @@
612593
613594 phase.set(Phase.CLOSING);
614595
615- // Wake up all threads that wait
616- signalAllAvailableConnection();
596+ for (SettableFuture<Connection> pendingBorrow : pendingBorrows) {
597+ pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
598+ }
617599
618600 future = new CloseFuture.Forwarding(discardAvailableConnections());
619601
@@ -622,7 +604,7 @@
622604 : closeFuture.get(); // We raced, it's ok, return the future that was actually set
623605 }
624606
625- public int opened() {
607+ int opened() {
626608 return open.get();
627609 }
628610
@@ -657,7 +639,7 @@
657639
658640 // This creates connections if we have less than core connections (if we
659641 // have more than core, connection will just get trash when we can).
660- public void ensureCoreConnections() {
642+ void ensureCoreConnections() {
661643 if (isClosed())
662644 return;
663645
added driver-core/src/main/java/com/datastax/driver/core/LZ4Compressor.java +182 −0
@@ -0,0 +1,182 @@
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+package com.datastax.driver.core;
17+
18+import io.netty.buffer.ByteBuf;
19+import net.jpountz.lz4.LZ4Factory;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+
23+import java.io.IOException;
24+import java.nio.ByteBuffer;
25+
26+class LZ4Compressor extends FrameCompressor {
27+
28+ private static final Logger logger = LoggerFactory.getLogger(LZ4Compressor.class);
29+
30+ static final LZ4Compressor instance;
31+
32+ static {
33+ LZ4Compressor i;
34+ try {
35+ i = new LZ4Compressor();
36+ } catch (NoClassDefFoundError e) {
37+ i = null;
38+ logger.warn("Cannot find LZ4 class, you should make sure the LZ4 library is in the classpath if you intend to use it. LZ4 compression will not be available for the protocol.");
39+ } catch (Throwable e) {
40+ i = null;
41+ logger.warn("Error loading LZ4 library ({}). LZ4 compression will not be available for the protocol.", e.toString());
42+ }
43+ instance = i;
44+ }
45+
46+ private static final int INTEGER_BYTES = 4;
47+ private final net.jpountz.lz4.LZ4Compressor compressor;
48+ private final net.jpountz.lz4.LZ4FastDecompressor decompressor;
49+
50+ private LZ4Compressor() {
51+ final LZ4Factory lz4Factory = LZ4Factory.fastestInstance();
52+ logger.info("Using {}", lz4Factory.toString());
53+ compressor = lz4Factory.fastCompressor();
54+ decompressor = lz4Factory.fastDecompressor();
55+ }
56+
57+ @Override
58+ Frame compress(Frame frame) throws IOException {
59+ ByteBuf input = frame.body;
60+
61+ // TODO: JAVA-1306: Use the same API calls for direct and heap buffers when LZ4 updated.
62+ ByteBuf frameBody = input.isDirect() ? compressDirect(input) : compressHeap(input);
63+ return frame.with(frameBody);
64+ }
65+
66+ private ByteBuf compressDirect(ByteBuf input) throws IOException {
67+ int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes());
68+ // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
69+ // LZ4Compressor.compress and so eliminate memory copies.
70+ ByteBuf output = input.alloc().directBuffer(INTEGER_BYTES + maxCompressedLength);
71+ try {
72+ ByteBuffer in = inputNioBuffer(input);
73+ // Increase reader index.
74+ input.readerIndex(input.writerIndex());
75+
76+ output.writeInt(in.remaining());
77+
78+ ByteBuffer out = outputNioBuffer(output);
79+ int written = compressor.compress(in, in.position(), in.remaining(), out, out.position(), out.remaining());
80+ // Set the writer index so the amount of written bytes is reflected
81+ output.writerIndex(output.writerIndex() + written);
82+ } catch (Exception e) {
83+ // release output buffer so we not leak and rethrow exception.
84+ output.release();
85+ throw new IOException(e);
86+ }
87+ return output;
88+ }
89+
90+ private ByteBuf compressHeap(ByteBuf input) throws IOException {
91+ int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes());
92+
93+ // Not a direct buffer so use byte arrays...
94+ int inOffset = input.arrayOffset() + input.readerIndex();
95+ byte[] in = input.array();
96+ int len = input.readableBytes();
97+ // Increase reader index.
98+ input.readerIndex(input.writerIndex());
99+
100+ // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
101+ // can eliminate the overhead of allocate a new byte[].
102+ ByteBuf output = input.alloc().heapBuffer(INTEGER_BYTES + maxCompressedLength);
103+ try {
104+ output.writeInt(len);
105+ // calculate the correct offset.
106+ int offset = output.arrayOffset() + output.writerIndex();
107+ byte[] out = output.array();
108+ int written = compressor.compress(in, inOffset, len, out, offset);
109+
110+ // Set the writer index so the amount of written bytes is reflected
111+ output.writerIndex(output.writerIndex() + written);
112+ } catch (Exception e) {
113+ // release output buffer so we not leak and rethrow exception.
114+ output.release();
115+ throw new IOException(e);
116+ }
117+ return output;
118+ }
119+
120+ @Override
121+ Frame decompress(Frame frame) throws IOException {
122+ ByteBuf input = frame.body;
123+
124+ // TODO: JAVA-1306: Use the same API calls for direct and heap buffers when LZ4 updated.
125+ ByteBuf frameBody = input.isDirect() ? decompressDirect(input) : decompressHeap(input);
126+ return frame.with(frameBody);
127+ }
128+
129+ private ByteBuf decompressDirect(ByteBuf input) throws IOException {
130+ // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
131+ // LZ4Compressor.decompress and so eliminate memory copies.
132+ int readable = input.readableBytes();
133+ int uncompressedLength = input.readInt();
134+ ByteBuffer in = inputNioBuffer(input);
135+ // Increase reader index.
136+ input.readerIndex(input.writerIndex());
137+ ByteBuf output = input.alloc().directBuffer(uncompressedLength);
138+ try {
139+ ByteBuffer out = outputNioBuffer(output);
140+ int read = decompressor.decompress(in, in.position(), out, out.position(), out.remaining());
141+ if (read != readable - INTEGER_BYTES)
142+ throw new IOException("Compressed lengths mismatch");
143+
144+ // Set the writer index so the amount of written bytes is reflected
145+ output.writerIndex(output.writerIndex() + uncompressedLength);
146+ } catch (Exception e) {
147+ // release output buffer so we not leak and rethrow exception.
148+ output.release();
149+ throw new IOException(e);
150+ }
151+ return output;
152+ }
153+
154+ private ByteBuf decompressHeap(ByteBuf input) throws IOException {
155+ // Not a direct buffer so use byte arrays...
156+ byte[] in = input.array();
157+ int len = input.readableBytes();
158+ int uncompressedLength = input.readInt();
159+ int inOffset = input.arrayOffset() + input.readerIndex();
160+ // Increase reader index.
161+ input.readerIndex(input.writerIndex());
162+
163+ // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
164+ // can eliminate the overhead of allocate a new byte[].
165+ ByteBuf output = input.alloc().heapBuffer(uncompressedLength);
166+ try {
167+ int offset = output.arrayOffset() + output.writerIndex();
168+ byte out[] = output.array();
169+ int read = decompressor.decompress(in, inOffset, out, offset, uncompressedLength);
170+ if (read != len - INTEGER_BYTES)
171+ throw new IOException("Compressed lengths mismatch");
172+
173+ // Set the writer index so the amount of written bytes is reflected
174+ output.writerIndex(output.writerIndex() + uncompressedLength);
175+ } catch (Exception e) {
176+ // release output buffer so we not leak and rethrow exception.
177+ output.release();
178+ throw new IOException(e);
179+ }
180+ return output;
181+ }
182+}
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +2 −9
@@ -135,14 +135,7 @@
135135 return id.toLowerCase();
136136
137137 // Check if it's enclosed in quotes. If it is, remove them and unescape internal double quotes
138- if (!id.isEmpty() && id.charAt(0) == '"' && id.charAt(id.length() - 1) == '"')
139- return id.substring(1, id.length() - 1).replaceAll("\"\"", "\"");
140-
141- // Otherwise, just return the id.
142- // Note that this is a bit at odds with the rules explained above, because the client can pass an
143- // identifier that contains special characters, without the need to quote it.
144- // Still it's better to be lenient here rather than throwing an exception.
145- return id;
138+ return ParseUtils.unDoubleQuote(id);
146139 }
147140
148141 // Escape a CQL3 identifier based on its value as read from the schema
@@ -217,7 +210,7 @@
217210 * or even {@link Cluster#connect(String)}.
218211 */
219212 public static String quote(String id) {
220- return '"' + id.replace("\"", "\"\"") + '"';
213+ return ParseUtils.doubleQuote(id);
221214 }
222215
223216 /**
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +10 −0
@@ -268,6 +268,7 @@
268268 public class Errors {
269269
270270 private final Counter connectionErrors = registry.counter("connection-errors");
271+ private final Counter authenticationErrors = registry.counter("authentication-errors");
271272
272273 private final Counter writeTimeouts = registry.counter("write-timeouts");
273274 private final Counter readTimeouts = registry.counter("read-timeouts");
@@ -311,6 +312,15 @@
311312 return connectionErrors;
312313 }
313314
315+ /**
316+ * Returns the number of authentication errors while connecting to Cassandra nodes.
317+ *
318+ * @return the number of errors.
319+ */
320+ public Counter getAuthenticationErrors() {
321+ return authenticationErrors;
322+ }
323+
314324 /**
315325 * Returns the number of write requests that returned a timeout (independently
316326 * of the final decision taken by the {@link com.datastax.driver.core.policies.RetryPolicy}).
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +8 −2
@@ -89,7 +89,10 @@
8989 *
9090 * @param threadFactory The {@link ThreadFactory} to use when creating a new {@code EventLoopGroup} instance;
9191 * The driver will provide its own internal thread factory here.
92- * It is safe to ignore it and use another thread factory.
92+ * It is safe to ignore it and use another thread factory. Note however that for optimal
93+ * performance it is recommended to use a factory that returns
94+ * {@link io.netty.util.concurrent.FastThreadLocalThread} instances (such as Netty's
95+ * {@link java.util.concurrent.Executors.DefaultThreadFactory}).
9396 * @return the {@code EventLoopGroup} instance to use.
9497 */
9598 public EventLoopGroup eventLoopGroup(ThreadFactory threadFactory) {
@@ -205,7 +208,10 @@
205208 *
206209 * @param threadFactory The {@link ThreadFactory} to use when creating a new {@link HashedWheelTimer} instance;
207210 * The driver will provide its own internal thread factory here.
208- * It is safe to ignore it and use another thread factory.
211+ * It is safe to ignore it and use another thread factory. Note however that for optimal
212+ * performance it is recommended to use a factory that returns
213+ * {@link io.netty.util.concurrent.FastThreadLocalThread} instances (such as Netty's
214+ * {@link java.util.concurrent.Executors.DefaultThreadFactory}).
209215 * @return the {@link Timer} instance to use.
210216 */
211217 public Timer timer(ThreadFactory threadFactory) {
modified driver-core/src/main/java/com/datastax/driver/core/ParseUtils.java +141 −25
@@ -232,7 +232,7 @@
232232 * by single quotes, and {@code false} otherwise.
233233 */
234234 public static boolean isQuoted(String value) {
235- return value != null && value.length() > 1 && value.charAt(0) == '\'' && value.charAt(value.length() - 1) == '\'';
235+ return isQuoted(value, '\'');
236236 }
237237
238238 /**
@@ -243,7 +243,7 @@
243243 * @return The quoted string.
244244 */
245245 public static String quote(String value) {
246- return '\'' + replaceChar(value, '\'', "''") + '\'';
246+ return quote(value, '\'');
247247 }
248248
249249 /**
@@ -254,9 +254,41 @@
254254 * @return The unquoted string.
255255 */
256256 public static String unquote(String value) {
257- if (!isQuoted(value))
258- return value;
259- return value.substring(1, value.length() - 1).replace("''", "'");
257+ return unquote(value, '\'');
258+ }
259+
260+ /**
261+ * Return {@code true} if the given string is surrounded
262+ * by double quotes, and {@code false} otherwise.
263+ *
264+ * @param value The string to inspect.
265+ * @return {@code true} if the given string is surrounded
266+ * by double quotes, and {@code false} otherwise.
267+ */
268+ public static boolean isDoubleQuoted(String value) {
269+ return isQuoted(value, '\"');
270+ }
271+
272+ /**
273+ * Double quote the given string; double quotes are escaped.
274+ * If the given string is null, this method returns a quoted empty string ({@code ""}).
275+ *
276+ * @param value The value to double quote.
277+ * @return The double quoted string.
278+ */
279+ public static String doubleQuote(String value) {
280+ return quote(value, '"');
281+ }
282+
283+ /**
284+ * Unquote the given string if it is double quoted; double quotes are unescaped.
285+ * If the given string is not double quoted, it is returned without any modification.
286+ *
287+ * @param value The string to un-double quote.
288+ * @return The un-double quoted string.
289+ */
290+ public static String unDoubleQuote(String value) {
291+ return unquote(value, '"');
260292 }
261293
262294 /**
@@ -428,45 +460,129 @@
428460 }
429461
430462 /**
431- * Simple method to replace a single character.
432- * {@code String.replace()} is a bit too inefficient (see JAVA-67).
433- * This methods is specially useful for escaping single quotes
434- * in CQL strings:
435- * <p/>
436- * <pre>{@code
437- * ParseUtils.replaceChar(value, '\'', "''");
438- * }</pre>
463+ * Return {@code true} if the given string is surrounded
464+ * by the quote character given, and {@code false} otherwise.
465+ *
466+ * @param value The string to inspect.
467+ * @return {@code true} if the given string is surrounded
468+ * by the quote character, and {@code false} otherwise.
469+ */
470+ private static boolean isQuoted(String value, char quoteChar) {
471+ return value != null && value.length() > 1
472+ && value.charAt(0) == quoteChar && value.charAt(value.length() - 1) == quoteChar;
473+ }
474+
475+ /**
476+ * @param quoteChar " or '
477+ * @return A quoted empty string.
478+ */
479+ private static String emptyQuoted(char quoteChar) {
480+ // don't handle non quote characters, this is done so that these are interned and don't create
481+ // repeated empty quoted strings.
482+ assert quoteChar == '"' || quoteChar == '\'';
483+ if (quoteChar == '"')
484+ return "\"\"";
485+ else
486+ return "''";
487+ }
488+
489+
490+ /**
491+ * Quotes text and escapes any existing quotes in the text.
492+ * {@code String.replace()} is a bit too inefficient (see JAVA-67, JAVA-1262).
439493 *
440- * @param text The text.
441- * @param search The character to search for.
442- * @param replacement The replacement.
443- * @return The text with all occurrences of {@code search} replaced with {@code replacement}.
494+ * @param text The text.
495+ * @param quoteChar The character to use as a quote.
496+ * @return The text with surrounded in quotes with all existing quotes escaped with (i.e. ' becomes '')
444497 */
445- private static String replaceChar(String text, char search, String replacement) {
498+ private static String quote(String text, char quoteChar) {
446499 if (text == null || text.isEmpty())
447- return "";
500+ return emptyQuoted(quoteChar);
448501
449502 int nbMatch = 0;
450503 int start = -1;
451504 do {
452- start = text.indexOf(search, start + 1);
505+ start = text.indexOf(quoteChar, start + 1);
453506 if (start != -1)
454507 ++nbMatch;
455508 } while (start != -1);
456509
510+ // no quotes found that need to be escaped, simply surround in quotes and return.
457511 if (nbMatch == 0)
512+ return quoteChar + text + quoteChar;
513+
514+ // 2 for beginning and end quotes.
515+ // length for original text
516+ // nbMatch for escape characters to add to quotes to be escaped.
517+ int newLength = 2 + text.length() + nbMatch;
518+ char[] result = new char[newLength];
519+ result[0] = quoteChar;
520+ result[newLength - 1] = quoteChar;
521+ int newIdx = 1;
522+ for (int i = 0; i < text.length(); i++) {
523+ char c = text.charAt(i);
524+ if (c == quoteChar) {
525+ // escape quote with another occurrence.
526+ result[newIdx++] = c;
527+ result[newIdx++] = c;
528+ } else {
529+ result[newIdx++] = c;
530+ }
531+ }
532+ return new String(result);
533+ }
534+
535+ /**
536+ * Unquotes text and unescapes non surrounding quotes.
537+ * {@code String.replace()} is a bit too inefficient (see JAVA-67, JAVA-1262).
538+ *
539+ * @param text The text
540+ * @param quoteChar The character to use as a quote.
541+ * @return The text with surrounding quotes removed and non surrounding quotes unescaped (i.e. '' becomes ')
542+ */
543+ private static String unquote(String text, char quoteChar) {
544+ if (!isQuoted(text, quoteChar))
458545 return text;
459546
460- int newLength = text.length() + nbMatch * (replacement.length() - 1);
547+ if (text.length() == 2)
548+ return "";
549+
550+ String search = emptyQuoted(quoteChar);
551+ int nbMatch = 0;
552+ int start = -1;
553+ do {
554+ start = text.indexOf(search, start + 2);
555+ // ignore the second to last character occurrence, as the last character is a quote.
556+ if (start != -1 && start != text.length() - 2)
557+ ++nbMatch;
558+ } while (start != -1);
559+
560+ // no escaped quotes found, simply remove surrounding quotes and return.
561+ if (nbMatch == 0)
562+ return text.substring(1, text.length() - 1);
563+
564+ // length of the new string will be its current length - the number of occurrences.
565+ int newLength = text.length() - nbMatch - 2;
461566 char[] result = new char[newLength];
462567 int newIdx = 0;
463- for (int i = 0; i < text.length(); i++) {
568+ // track whenever a quoteChar is encountered and the previous character is not a quoteChar.
569+ boolean firstFound = false;
570+ for (int i = 1; i < text.length() - 1; i++) {
464571 char c = text.charAt(i);
465- if (c == search) {
466- for (int r = 0; r < replacement.length(); r++)
467- result[newIdx++] = replacement.charAt(r);
572+ if (c == quoteChar) {
573+ if (firstFound) {
574+ // The previous character was a quoteChar, don't add this to result, this action in
575+ // effect removes consecutive quotes.
576+ firstFound = false;
577+ } else {
578+ // found a quoteChar and the previous character was not a quoteChar, include in result.
579+ firstFound = true;
580+ result[newIdx++] = c;
581+ }
468582 } else {
583+ // non quoteChar encountered, include in result.
469584 result[newIdx++] = c;
585+ firstFound = false;
470586 }
471587 }
472588 return new String(result);
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +40 −16
@@ -128,10 +128,16 @@
128128 public static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
129129
130130 /**
131- * The default value for {@link #getPoolTimeoutMillis()} ({@value}).
131+ * @deprecated see {@link #setPoolTimeoutMillis(int)}
132132 */
133+ @Deprecated
133134 public static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
134135
136+ /**
137+ * The default value for {@link #getMaxQueueSize()} ({@value}).
138+ */
139+ public static final int DEFAULT_MAX_QUEUE_SIZE = 256;
140+
135141 /**
136142 * The default value for {@link #getHeartbeatIntervalSeconds()} ({@value}).
137143 */
@@ -151,7 +157,7 @@
151157 private volatile int maxRequestsPerConnectionRemote = UNSET;
152158
153159 private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
154- private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
160+ private volatile int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE;
155161 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
156162
157163 private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR;
@@ -400,30 +406,48 @@
400406 }
401407
402408 /**
403- * Returns the timeout when trying to acquire a connection from a host's pool.
404- *
405- * @return the timeout.
409+ * @deprecated see {@link #setPoolTimeoutMillis(int)}. This method always returns 0.
406410 */
411+ @Deprecated
407412 public int getPoolTimeoutMillis() {
408- return poolTimeoutMillis;
413+ return 0;
414+ }
415+
416+ /**
417+ * @deprecated the connection pool does not use a timeout anymore, incoming requests are now throttled with a
418+ * threshold on the {@link #setMaxQueueSize(int) queue size}. This method has no effect.
419+ */
420+ @Deprecated
421+ public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
422+ return this;
423+ }
424+
425+ /**
426+ * Returns the maximum number of requests that get enqueued if no connection is available.
427+ *
428+ * @return the maximum queue size.
429+ */
430+ public int getMaxQueueSize() {
431+ return maxQueueSize;
409432 }
410433
411434 /**
412- * Sets the timeout when trying to acquire a connection from a host's pool.
435+ * Sets the maximum number of requests that get enqueued if no connection is available.
413436 * <p/>
414- * If no connection is available within that time, the driver will try the
415- * next host from the query plan.
437+ * If the queue grows past this value, new requests will be rejected immediately (and the driver will move to the
438+ * next host in the query plan). This limit is per connection pool, not global to the driver.
416439 * <p/>
417- * The default is 5 seconds. If this option is set to zero, the driver won't wait at all.
440+ * The default value is {@value DEFAULT_MAX_QUEUE_SIZE}. If this option is set to zero, the driver will never
441+ * enqueue requests.
418442 *
419- * @param poolTimeoutMillis the new value in milliseconds.
443+ * @param maxQueueSize the new value.
420444 * @return this {@code PoolingOptions}
421- * @throws IllegalArgumentException if the timeout is negative.
445+ * @throws IllegalArgumentException if the value is negative.
422446 */
423- public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
424- if (poolTimeoutMillis < 0)
425- throw new IllegalArgumentException("Pool timeout must be positive");
426- this.poolTimeoutMillis = poolTimeoutMillis;
447+ public PoolingOptions setMaxQueueSize(int maxQueueSize) {
448+ if (maxQueueSize < 0)
449+ throw new IllegalArgumentException("Max queue size must be positive");
450+ this.maxQueueSize = maxQueueSize;
427451 return this;
428452 }
429453
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +2 −2
@@ -41,7 +41,7 @@
4141 SNAPPY("snappy") {
4242 @Override
4343 FrameCompressor compressor() {
44- return FrameCompressor.SnappyCompressor.instance;
44+ return SnappyCompressor.instance;
4545 }
4646 },
4747 /**
@@ -50,7 +50,7 @@
5050 LZ4("lz4") {
5151 @Override
5252 FrameCompressor compressor() {
53- return FrameCompressor.LZ4Compressor.instance;
53+ return LZ4Compressor.instance;
5454 }
5555 };
5656
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +2 −0
@@ -29,6 +29,7 @@
2929 * Note: it's not an interface mainly because we don't want to expose it.
3030 */
3131 abstract class ReplicationStrategy {
32+ private static final Logger logger = LoggerFactory.getLogger(ReplicationStrategy.class);
3233
3334 static ReplicationStrategy create(Map<String, String> replicationOptions) {
3435
@@ -55,6 +56,7 @@
5556 }
5657 } catch (NumberFormatException e) {
5758 // Cassandra wouldn't let that pass in the first place so this really should never happen
59+ logger.error("Failed to parse replication options: " + replicationOptions, e);
5860 return null;
5961 }
6062 }
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +61 −57
@@ -21,6 +21,9 @@
2121 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type;
2222 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan;
2323 import com.google.common.collect.Sets;
24+import com.google.common.util.concurrent.FutureCallback;
25+import com.google.common.util.concurrent.Futures;
26+import com.google.common.util.concurrent.ListenableFuture;
2427 import io.netty.util.Timeout;
2528 import io.netty.util.TimerTask;
2629 import org.slf4j.Logger;
@@ -109,7 +112,7 @@
109112
110113 SpeculativeExecution execution = new SpeculativeExecution(request, position);
111114 runningExecutions.add(execution);
112- execution.sendRequest();
115+ execution.findNextHostAndQuery();
113116 }
114117
115118 private void scheduleExecution(long delayMillis) {
@@ -262,12 +265,10 @@
262265 logger.trace("[{}] Starting", id);
263266 }
264267
265- void sendRequest() {
268+ void findNextHostAndQuery() {
266269 try {
267270 Host host;
268271 while (!isDone.get() && (host = queryPlan.next()) != null && !queryStateRef.get().isCancelled()) {
269- if (logger.isTraceEnabled())
270- logger.trace("[{}] Querying node {}", id, host);
271272 if (query(host))
272273 return;
273274 }
@@ -279,48 +280,63 @@
279280 }
280281
281282 private boolean query(final Host host) {
282- HostConnectionPool currentPool = manager.pools.get(host);
283- if (currentPool == null || currentPool.isClosed())
283+ HostConnectionPool pool = manager.pools.get(host);
284+ if (pool == null || pool.isClosed())
284285 return false;
285286
287+ if (logger.isTraceEnabled())
288+ logger.trace("[{}] Querying node {}", id, host);
289+
286290 if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true))
287291 scheduleExecution(speculativeExecutionPlan.nextExecution(host));
288292
289- Connection connection = null;
290- try {
291- connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS);
292- if (current != null) {
293- if (triedHosts == null)
294- triedHosts = new CopyOnWriteArrayList<Host>();
295- triedHosts.add(current);
293+ ListenableFuture<Connection> connectionFuture = pool.borrowConnection(
294+ manager.configuration().getPoolingOptions().getMaxQueueSize());
295+ Futures.addCallback(connectionFuture, new FutureCallback<Connection>() {
296+ @Override
297+ public void onSuccess(Connection connection) {
298+ if (current != null) {
299+ if (triedHosts == null)
300+ triedHosts = new CopyOnWriteArrayList<Host>();
301+ triedHosts.add(current);
302+ }
303+ current = host;
304+ try {
305+ write(connection, SpeculativeExecution.this);
306+ } catch (ConnectionException e) {
307+ // If we have any problem with the connection, move to the next node.
308+ if (metricsEnabled())
309+ metrics().getErrorMetrics().getConnectionErrors().inc();
310+ if (connection != null)
311+ connection.release();
312+ logError(host.getSocketAddress(), e);
313+ findNextHostAndQuery();
314+ } catch (BusyConnectionException e) {
315+ // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host.
316+ connection.release();
317+ logError(host.getSocketAddress(), e);
318+ findNextHostAndQuery();
319+ } catch (RuntimeException e) {
320+ if (connection != null)
321+ connection.release();
322+ logger.error("Unexpected error while querying " + host.getAddress(), e);
323+ logError(host.getSocketAddress(), e);
324+ findNextHostAndQuery();
325+ }
296326 }
297- current = host;
298- write(connection, this);
299- return true;
300- } catch (ConnectionException e) {
301- // If we have any problem with the connection, move to the next node.
302- if (metricsEnabled())
303- metrics().getErrorMetrics().getConnectionErrors().inc();
304- if (connection != null)
305- connection.release();
306- logError(host.getSocketAddress(), e);
307- return false;
308- } catch (BusyConnectionException e) {
309- // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host.
310- connection.release();
311- logError(host.getSocketAddress(), e);
312- return false;
313- } catch (TimeoutException e) {
314- // We timeout, log it but move to the next node.
315- logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)", e));
316- return false;
317- } catch (RuntimeException e) {
318- if (connection != null)
319- connection.release();
320- logger.error("Unexpected error while querying " + host.getAddress(), e);
321- logError(host.getSocketAddress(), e);
322- return false;
323- }
327+
328+ @Override
329+ public void onFailure(Throwable t) {
330+ if (t instanceof BusyPoolException) {
331+ logError(host.getSocketAddress(), t);
332+ } else {
333+ logger.error("Unexpected error while querying " + host.getAddress(), t);
334+ logError(host.getSocketAddress(), t);
335+ }
336+ findNextHostAndQuery();
337+ }
338+ });
339+ return true;
324340 }
325341
326342 private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException {
@@ -415,23 +431,11 @@
415431 if (newConsistencyLevel != null)
416432 this.retryConsistencyLevel = newConsistencyLevel;
417433
418- // We should not retry on the current thread as this will be an IO thread.
419- manager.executor().execute(new Runnable() {
420- @Override
421- public void run() {
422- if (queryStateRef.get().isCancelled())
423- return;
424- try {
425- if (retryCurrent) {
426- if (query(h))
427- return;
428- }
429- sendRequest();
430- } catch (Exception e) {
431- setFinalException(null, new DriverInternalError("Unexpected exception while retrying query", e));
432- }
433- }
434- });
434+ if (queryStateRef.get().isCancelled())
435+ return;
436+
437+ if (!retryCurrent || !query(h))
438+ findNextHostAndQuery();
435439 }
436440
437441 private void logError(InetSocketAddress address, Throwable exception) {
modified driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java +1 −1
@@ -24,7 +24,7 @@
2424 * Note that the methods defined by this interface will be executed by internal driver threads, and are
2525 * therefore expected to have short execution times. If you need to perform long computations or blocking
2626 * calls in response to schema change events, it is strongly recommended to schedule them asynchronously
27- * on a separate thread provided by our application code.
27+ * on a separate thread provided by your application code.
2828 */
2929 public interface SchemaChangeListener {
3030
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +25 −37
@@ -28,7 +28,6 @@
2828 import com.google.common.collect.ImmutableList;
2929 import com.google.common.collect.Lists;
3030 import com.google.common.util.concurrent.*;
31-import io.netty.util.concurrent.EventExecutor;
3231 import org.slf4j.Logger;
3332 import org.slf4j.LoggerFactory;
3433
@@ -48,9 +47,6 @@
4847
4948 private static final Logger logger = LoggerFactory.getLogger(Session.class);
5049
51- private static final boolean CHECK_IO_DEADLOCKS = SystemProperties.getBoolean(
52- "com.datastax.driver.CHECK_IO_DEADLOCKS", true);
53-
5450 final Cluster cluster;
5551 final ConcurrentMap<Host, HostConnectionPool> pools;
5652 final HostConnectionPool.PoolState poolsState;
@@ -564,7 +560,7 @@
564560 List<ByteBuffer> positionalValues = rawPositionalValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawPositionalValues);
565561 Map<String, ByteBuffer> namedValues = rawNamedValues == null ? Collections.<String, ByteBuffer>emptyMap() : rawNamedValues;
566562
567- String qString = rs.getQueryString();
563+ String qString = rs.getQueryString(codecRegistry);
568564
569565 Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(Message.Request.Type.QUERY, consistency, positionalValues, namedValues,
570566 false, fetchSize, usedPagingState, serialConsistency, defaultTimestamp);
@@ -627,22 +623,30 @@
627623
628624 try {
629625 // Preparing is not critical: if it fails, it will fix itself later when the user tries to execute
630- // the prepared query. So don't block if no connection is available, simply abort.
631- final Connection c = entry.getValue().borrowConnection(0, TimeUnit.MILLISECONDS);
632- ListenableFuture<Response> future = c.write(new Requests.Prepare(query));
633- Futures.addCallback(future, new FutureCallback<Response>() {
634- @Override
635- public void onSuccess(Response result) {
636- c.release();
637- }
638-
639- @Override
640- public void onFailure(Throwable t) {
641- logger.debug(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), t);
642- c.release();
643- }
644- });
645- futures.add(future);
626+ // the prepared query. So don't wait if no connection is available, simply abort.
627+ ListenableFuture<Connection> connectionFuture = entry.getValue().borrowConnection(0);
628+ ListenableFuture<Response> prepareFuture = Futures.transform(connectionFuture,
629+ new AsyncFunction<Connection, Response>() {
630+ @Override
631+ public ListenableFuture<Response> apply(final Connection c) throws Exception {
632+ Connection.Future responseFuture = c.write(new Requests.Prepare(query));
633+ Futures.addCallback(responseFuture, new FutureCallback<Response>() {
634+ @Override
635+ public void onSuccess(Response result) {
636+ c.release();
637+ }
638+
639+ @Override
640+ public void onFailure(Throwable t) {
641+ logger.debug(String.format("Unexpected error while preparing query (%s) on %s",
642+ query, entry.getKey()), t);
643+ c.release();
644+ }
645+ });
646+ return responseFuture;
647+ }
648+ });
649+ futures.add(prepareFuture);
646650 } catch (Exception e) {
647651 // Again, not being able to prepare the query right now is no big deal, so just ignore
648652 }
@@ -665,22 +669,6 @@
665669 }
666670 }
667671
668- @Override
669- protected void checkNotInEventLoop() {
670- Connection.Factory connectionFactory = cluster.manager.connectionFactory;
671- if (!CHECK_IO_DEADLOCKS || connectionFactory == null)
672- return;
673- for (EventExecutor executor : connectionFactory.eventLoopGroup) {
674- if (executor.inEventLoop()) {
675- throw new IllegalStateException(
676- "Detected a synchronous Session call (execute() or prepare()) on an I/O thread, " +
677- "this can cause deadlocks or unpredictable behavior. " +
678- "Make sure your Future callbacks only use async calls, or schedule them on a " +
679- "different executor.");
680- }
681- }
682- }
683-
684672 private static class State implements Session.State {
685673
686674 private final SessionManager session;
added driver-core/src/main/java/com/datastax/driver/core/SnappyCompressor.java +170 −0
@@ -0,0 +1,170 @@
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+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.exceptions.DriverInternalError;
19+import io.netty.buffer.ByteBuf;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+import org.xerial.snappy.Snappy;
23+
24+import java.io.IOException;
25+import java.nio.ByteBuffer;
26+
27+class SnappyCompressor extends FrameCompressor {
28+
29+ private static final Logger logger = LoggerFactory.getLogger(SnappyCompressor.class);
30+
31+ static final SnappyCompressor instance;
32+
33+ static {
34+ SnappyCompressor i;
35+ try {
36+ i = new SnappyCompressor();
37+ } catch (NoClassDefFoundError e) {
38+ i = null;
39+ logger.warn("Cannot find Snappy class, you should make sure the Snappy library is in the classpath if you intend to use it. Snappy compression will not be available for the protocol.");
40+ } catch (Throwable e) {
41+ i = null;
42+ logger.warn("Error loading Snappy library ({}). Snappy compression will not be available for the protocol.", e.toString());
43+ }
44+ instance = i;
45+ }
46+
47+ private SnappyCompressor() {
48+ // this would throw java.lang.NoClassDefFoundError if Snappy class
49+ // wasn't found at runtime which should be processed by the calling method
50+ Snappy.getNativeLibraryVersion();
51+ }
52+
53+ @Override
54+ Frame compress(Frame frame) throws IOException {
55+ ByteBuf input = frame.body;
56+ ByteBuf frameBody = input.isDirect() ? compressDirect(input) : compressHeap(input);
57+ return frame.with(frameBody);
58+ }
59+
60+ private ByteBuf compressDirect(ByteBuf input) throws IOException {
61+ int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes());
62+ // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
63+ // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
64+ ByteBuf output = input.alloc().directBuffer(maxCompressedLength);
65+ try {
66+ ByteBuffer in = inputNioBuffer(input);
67+ // Increase reader index.
68+ input.readerIndex(input.writerIndex());
69+
70+ ByteBuffer out = outputNioBuffer(output);
71+ int written = Snappy.compress(in, out);
72+ // Set the writer index so the amount of written bytes is reflected
73+ output.writerIndex(output.writerIndex() + written);
74+ } catch (IOException e) {
75+ // release output buffer so we not leak and rethrow exception.
76+ output.release();
77+ throw e;
78+ }
79+ return output;
80+ }
81+
82+ private ByteBuf compressHeap(ByteBuf input) throws IOException {
83+ int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes());
84+ int inOffset = input.arrayOffset() + input.readerIndex();
85+ byte[] in = input.array();
86+ int len = input.readableBytes();
87+ // Increase reader index.
88+ input.readerIndex(input.writerIndex());
89+
90+ // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
91+ // can eliminate the overhead of allocate a new byte[].
92+ ByteBuf output = input.alloc().heapBuffer(maxCompressedLength);
93+ try {
94+ // Calculate the correct offset.
95+ int offset = output.arrayOffset() + output.writerIndex();
96+ byte[] out = output.array();
97+ int written = Snappy.compress(in, inOffset, len, out, offset);
98+
99+ // Increase the writerIndex with the written bytes.
100+ output.writerIndex(output.writerIndex() + written);
101+ } catch (IOException e) {
102+ // release output buffer so we not leak and rethrow exception.
103+ output.release();
104+ throw e;
105+ }
106+ return output;
107+ }
108+
109+ @Override
110+ Frame decompress(Frame frame) throws IOException {
111+ ByteBuf input = frame.body;
112+ ByteBuf frameBody = input.isDirect() ? decompressDirect(input) : decompressHeap(input);
113+ return frame.with(frameBody);
114+ }
115+
116+ private ByteBuf decompressDirect(ByteBuf input) throws IOException {
117+ ByteBuffer in = inputNioBuffer(input);
118+ // Increase reader index.
119+ input.readerIndex(input.writerIndex());
120+
121+ if (!Snappy.isValidCompressedBuffer(in))
122+ throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");
123+
124+ // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
125+ // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
126+ ByteBuf output = input.alloc().directBuffer(Snappy.uncompressedLength(in));
127+ try {
128+ ByteBuffer out = outputNioBuffer(output);
129+
130+ int size = Snappy.uncompress(in, out);
131+ // Set the writer index so the amount of written bytes is reflected
132+ output.writerIndex(output.writerIndex() + size);
133+ } catch (IOException e) {
134+ // release output buffer so we not leak and rethrow exception.
135+ output.release();
136+ throw e;
137+ }
138+ return output;
139+ }
140+
141+ private ByteBuf decompressHeap(ByteBuf input) throws IOException {
142+ // Not a direct buffer so use byte arrays...
143+ int inOffset = input.arrayOffset() + input.readerIndex();
144+ byte[] in = input.array();
145+ int len = input.readableBytes();
146+ // Increase reader index.
147+ input.readerIndex(input.writerIndex());
148+
149+ if (!Snappy.isValidCompressedBuffer(in, inOffset, len))
150+ throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");
151+
152+ // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
153+ // can eliminate the overhead of allocate a new byte[].
154+ ByteBuf output = input.alloc().heapBuffer(Snappy.uncompressedLength(in, inOffset, len));
155+ try {
156+ // Calculate the correct offset.
157+ int offset = output.arrayOffset() + output.writerIndex();
158+ byte[] out = output.array();
159+ int written = Snappy.uncompress(in, inOffset, len, out, offset);
160+
161+ // Increase the writerIndex with the written bytes.
162+ output.writerIndex(output.writerIndex() + written);
163+ } catch (IOException e) {
164+ // release output buffer so we not leak and rethrow exception.
165+ output.release();
166+ throw e;
167+ }
168+ return output;
169+ }
170+}
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +28 −3
@@ -23,6 +23,7 @@
2323 import com.google.common.collect.ImmutableMap;
2424
2525 import java.nio.ByteBuffer;
26+import java.util.Collection;
2627 import java.util.Map;
2728
2829 /**
@@ -503,11 +504,22 @@
503504 * {@link QueryOptions#getDefaultIdempotence()}.
504505 * <p/>
505506 * By default, this method returns {@code null} for all statements, except for
506- * {@link BuiltStatement}s, where the value will be inferred from the query: if it updates
507- * counters, prepends/appends to a list, or uses a function call or
507+ * <ul>
508+ * <li>{@link BuiltStatement} - value will be inferred from the query: if it updates counters,
509+ * prepends/appends to a list, or uses a function call or
508510 * {@link com.datastax.driver.core.querybuilder.QueryBuilder#raw(String)} anywhere in an inserted value,
509511 * the result will be {@code false}; otherwise it will be {@code true}.
510- * In all cases, calling {@link #setIdempotent(boolean)} forces a value that overrides every other mechanism.
512+ * </li>
513+ * <li>
514+ * {@link com.datastax.driver.core.querybuilder.Batch} and {@link BatchStatement}:
515+ * <ol>
516+ * <li>If any statement in batch has isIdempotent() false - return false</li>
517+ * <li>If no statements with isIdempotent() false, but some have isIdempotent() null - return null</li>
518+ * <li>Otherwise - return true</li>
519+ * </ol>
520+ * </li>
521+ * </ul>
522+ * In all cases, calling {@link #setIdempotent(boolean)} forces a value that overrides calculated value.
511523 * <p/>
512524 * Note that when a statement is prepared ({@link Session#prepare(String)}), its idempotence flag will be propagated
513525 * to all {@link PreparedStatement}s created from it.
@@ -571,4 +583,17 @@
571583 this.outgoingPayload = payload == null ? null : ImmutableMap.copyOf(payload);
572584 return this;
573585 }
586+
587+ protected static Boolean isBatchIdempotent(Collection<? extends Statement> statements) {
588+ boolean hasNullIdempotentStatements = false;
589+ for (Statement statement : statements) {
590+ Boolean innerIdempotent = statement.isIdempotent();
591+ if (innerIdempotent == null) {
592+ hasNullIdempotentStatements = true;
593+ } else if (!innerIdempotent) {
594+ return false;
595+ }
596+ }
597+ return (hasNullIdempotentStatements) ? null : true;
598+ }
574599 }
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +2 −2
@@ -533,8 +533,8 @@
533533 * {@link TupleValue}, and the internal representation of a {@code ROWS} response),
534534 * which may appear in driver logs.</li>
535535 * </ol>
536- * If choose not to implement this method, you can return a constant string (for example
537- * "XxxCodec.format not implemented").
536+ * If you choose not to implement this method, you should not throw an exception but
537+ * instead return a constant string (for example "XxxCodec.format not implemented").
538538 *
539539 * @param value An instance of T; may be {@code null}.
540540 * @return CQL string
added driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java +80 −0
@@ -0,0 +1,80 @@
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+package com.datastax.driver.core.exceptions;
17+
18+import com.datastax.driver.core.HostDistance;
19+import com.datastax.driver.core.Statement;
20+
21+import java.net.InetAddress;
22+import java.net.InetSocketAddress;
23+
24+/**
25+ * Indicates that a connection pool has run out of available connections.
26+ * <p/>
27+ * This happens if the pool has no connections (for example if it's currently reconnecting to its host), or if all
28+ * connections have reached their maximum number of in flight queries. The query will be retried on the next host in the
29+ * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#newQueryPlan(String, Statement) query plan}.
30+ * <p/>
31+ * This exception is a symptom that the driver is experiencing a high workload. If it happens regularly on all hosts,
32+ * you should consider tuning one (or a combination of) the following pooling options:
33+ * <ul>
34+ * <li>{@link com.datastax.driver.core.PoolingOptions#setMaxRequestsPerConnection(HostDistance, int)}: maximum number of
35+ * requests per connection;</li>
36+ * <li>{@link com.datastax.driver.core.PoolingOptions#setMaxConnectionsPerHost(HostDistance, int)}: maximum number of
37+ * connections in the pool;</li>
38+ * <li>{@link com.datastax.driver.core.PoolingOptions#setMaxQueueSize(int)}: maximum number of enqueued requests before
39+ * this exception is thrown.</li>
40+ * </ul>
41+ */
42+public class BusyPoolException extends DriverException implements CoordinatorException {
43+
44+ private static final long serialVersionUID = 0;
45+
46+ private final InetSocketAddress address;
47+ private final int queueSize;
48+
49+ public BusyPoolException(InetSocketAddress address, int queueSize) {
50+ this(address, queueSize, null);
51+ }
52+
53+ private BusyPoolException(InetSocketAddress address, int queueSize, Throwable cause) {
54+ super(buildMessage(address, queueSize), cause);
55+ this.address = address;
56+ this.queueSize = queueSize;
57+ }
58+
59+ private static String buildMessage(InetSocketAddress address, int queueSize) {
60+ return String.format("[%s] Pool is busy (no available connection and the queue has reached its max size %d)",
61+ address.getAddress(),
62+ queueSize);
63+ }
64+
65+ @Override
66+ public InetAddress getHost() {
67+ return address.getAddress();
68+ }
69+
70+ @Override
71+ public InetSocketAddress getAddress() {
72+ return address;
73+ }
74+
75+ @Override
76+ public BusyPoolException copy() {
77+ return new BusyPoolException(address, queueSize, this);
78+ }
79+
80+}
added driver-core/src/main/java/com/datastax/driver/core/exceptions/FrameTooLongException.java +50 −0
@@ -0,0 +1,50 @@
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+package com.datastax.driver.core.exceptions;
17+
18+/**
19+ * Indicates that the response frame for a request exceeded
20+ * {@link com.datastax.driver.core.Frame.Decoder.DecoderForStreamIdSize#MAX_FRAME_LENGTH}
21+ * (default: 256MB, configurable via com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB
22+ * system property) and thus was not parsed.
23+ */
24+public class FrameTooLongException extends DriverException {
25+
26+ private static final long serialVersionUID = 0;
27+
28+ private final int streamId;
29+
30+ public FrameTooLongException(int streamId) {
31+ this(streamId, null);
32+ }
33+
34+ private FrameTooLongException(int streamId, Throwable cause) {
35+ super("Response frame exceeded maximum allowed length", cause);
36+ this.streamId = streamId;
37+ }
38+
39+ /**
40+ * @return The stream id associated with the frame that caused this exception.
41+ */
42+ public int getStreamId() {
43+ return streamId;
44+ }
45+
46+ @Override
47+ public FrameTooLongException copy() {
48+ return new FrameTooLongException(streamId, this);
49+ }
50+}
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +10 −5
@@ -15,10 +15,7 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18-import com.datastax.driver.core.CodecRegistry;
19-import com.datastax.driver.core.ProtocolVersion;
20-import com.datastax.driver.core.RegularStatement;
21-import com.datastax.driver.core.SimpleStatement;
18+import com.datastax.driver.core.*;
2219
2320 import java.nio.ByteBuffer;
2421 import java.util.ArrayList;
@@ -69,7 +66,7 @@
6966 builder.append(maybeAddSemicolon(bst.buildQueryString(variables, codecRegistry)));
7067
7168 } else {
72- String str = stmt.getQueryString();
69+ String str = stmt.getQueryString(codecRegistry);
7370 builder.append(str);
7471 if (!str.trim().endsWith(";"))
7572 builder.append(';');
@@ -175,6 +172,14 @@
175172 return statements.isEmpty() ? null : statements.get(0).getKeyspace();
176173 }
177174
175+ @Override
176+ public Boolean isIdempotent() {
177+ if (idempotent != null) {
178+ return idempotent;
179+ }
180+ return isBatchIdempotent(statements);
181+ }
182+
178183 /**
179184 * The options of a BATCH statement.
180185 */
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +11 −10
@@ -231,7 +231,7 @@
231231 return;
232232
233233 for (int i = 0; i < partitionKey.size(); i++) {
234- if (name.equals(partitionKey.get(i).getName())) {
234+ if (Utils.handleId(name).equals(partitionKey.get(i).getName())) {
235235 routingKeyValues.set(i, value);
236236 return;
237237 }
@@ -296,18 +296,19 @@
296296 @Override
297297 public String toString() {
298298 try {
299+ if (forceNoValues)
300+ return getQueryString();
301+ // 1) try first with all values inlined (will not work if some values require custom codecs,
302+ // or if the required codecs are registered in a different CodecRegistry instance than the default one)
303+ return maybeAddSemicolon(buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE)).toString();
304+ } catch (RuntimeException e1) {
305+ // 2) try next with bind markers for all values to avoid usage of custom codecs
299306 try {
300- if (forceNoValues)
301- return getQueryString();
302- // 1) try first with all values inlined (will not work if some values require custom codecs)
303- return maybeAddSemicolon(buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE)).toString();
304- } catch (CodecNotFoundException e) {
305- // 2) try next with bind markers for all values to avoid usage of custom codecs
306307 return maybeAddSemicolon(buildQueryString(new ArrayList<Object>(), CodecRegistry.DEFAULT_INSTANCE)).toString();
308+ } catch (RuntimeException e2) {
309+ // Ugly but we have absolutely no context to get the registry from
310+ return String.format("built query (could not generate with default codec registry: %s)", e2.getMessage());
307311 }
308- } catch (RuntimeException e) {
309- // Ugly but we have absolutely no context to get the registry from
310- return String.format("built query (could not generate with default codec registry: %s)", e.getMessage());
311312 }
312313 }
313314
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +32 −0
@@ -32,8 +32,40 @@
3232 // Static utilities private to the query builder
3333 abstract class Utils {
3434
35+ private static final Pattern alphanumeric = Pattern.compile("\\w+"); // this includes _
3536 private static final Pattern cnamePattern = Pattern.compile("\\w+(?:\\[.+\\])?");
3637
38+ /**
39+ * Deal with case sensitivity for a given element id (keyspace, table, column, etc.)
40+ *
41+ * This method is used to convert identifiers provided by the client (through methods such as getKeyspace(String)),
42+ * to the format used internally by the driver.
43+ *
44+ * We expect client-facing APIs to behave like cqlsh, that is:
45+ * - identifiers that are mixed-case or contain special characters should be quoted.
46+ * - unquoted identifiers will be lowercased: getKeyspace("Foo") will look for a keyspace named "foo"
47+ *
48+ * Copied from {@link Metadata#handleId(String)} to avoid making it public.
49+ */
50+ static String handleId(String id) {
51+ // Shouldn't really happen for this method, but no reason to fail here
52+ if (id == null)
53+ return null;
54+
55+ if (alphanumeric.matcher(id).matches())
56+ return id.toLowerCase();
57+
58+ // Check if it's enclosed in quotes. If it is, remove them and unescape internal double quotes
59+ if (!id.isEmpty() && id.charAt(0) == '"' && id.charAt(id.length() - 1) == '"')
60+ return id.substring(1, id.length() - 1).replaceAll("\"\"", "\"");
61+
62+ // Otherwise, just return the id.
63+ // Note that this is a bit at odds with the rules explained above, because the client can pass an
64+ // identifier that contains special characters, without the need to quote it.
65+ // Still it's better to be lenient here rather than throwing an exception.
66+ return id;
67+ }
68+
3769 static StringBuilder joinAndAppend(StringBuilder sb, CodecRegistry codecRegistry, String separator, List<? extends Appendeable> values, List<Object> variables) {
3870 for (int i = 0; i < values.size(); i++) {
3971 if (i > 0)
added driver-core/src/test/java/com/datastax/driver/core/AbstractBatchIdempotencyTest.java +177 −0
@@ -0,0 +1,177 @@
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+package com.datastax.driver.core;
17+
18+import org.testng.annotations.Test;
19+
20+import static com.datastax.driver.core.Assertions.assertThat;
21+
22+public abstract class AbstractBatchIdempotencyTest {
23+
24+ protected abstract TestBatch createBatch();
25+
26+ /**
27+ * Unify Batch and BatchStatement to avoid duplicating all tests
28+ */
29+ protected interface TestBatch {
30+ //Batch only accepts RegularStatement, so we use it for common interface
31+ void add(RegularStatement statement);
32+
33+ Boolean isIdempotent();
34+
35+ void setIdempotent(boolean idempotent);
36+ }
37+
38+ @Test(groups = "unit")
39+ public void isIdempotent_should_return_true_if_no_statements_added() {
40+ TestBatch batch = createBatch();
41+ assertThat(batch.isIdempotent()).isTrue();
42+ }
43+
44+ @Test(groups = "unit")
45+ public void isIdempotent_should_return_true_if_all_statements_are_idempotent() {
46+ TestBatch batch = createBatch();
47+ assertThat(batch.isIdempotent()).isTrue();
48+
49+ batch.add(statementWithIdempotency(true));
50+ assertThat(batch.isIdempotent()).isTrue();
51+
52+ batch.add(statementWithIdempotency(true));
53+ assertThat(batch.isIdempotent()).isTrue();
54+ }
55+
56+ @Test(groups = "unit")
57+ public void isIdempotent_should_return_false_if_any_statements_is_nonidempotent() {
58+ TestBatch batch = createBatch();
59+ assertThat(batch.isIdempotent()).isTrue();
60+
61+ batch.add(statementWithIdempotency(true));
62+ assertThat(batch.isIdempotent()).isTrue();
63+
64+ batch.add(statementWithIdempotency(false));
65+ assertThat(batch.isIdempotent()).isFalse();
66+
67+ batch.add(statementWithIdempotency(true));
68+ assertThat(batch.isIdempotent()).isFalse();
69+ }
70+
71+ @Test(groups = "unit")
72+ public void isIdempotent_should_return_null_if_no_nonidempotent_statements_and_some_are_nullidempotent() {
73+ TestBatch batch = createBatch();
74+ assertThat(batch.isIdempotent()).isTrue();
75+
76+ batch.add(statementWithIdempotency(true));
77+ assertThat(batch.isIdempotent()).isTrue();
78+
79+ batch.add(statementWithIdempotency(null));
80+ assertThat(batch.isIdempotent()).isNull();
81+
82+ batch.add(statementWithIdempotency(true));
83+ assertThat(batch.isIdempotent()).isNull();
84+ }
85+
86+ @Test(groups = "unit")
87+ public void isIdempotent_should_return_false_if_both_nonidempotent_and_nullidempotent_statements_present() {
88+ TestBatch batch = createBatch();
89+ assertThat(batch.isIdempotent()).isTrue();
90+
91+ batch.add(statementWithIdempotency(true));
92+ assertThat(batch.isIdempotent()).isTrue();
93+
94+ batch.add(statementWithIdempotency(null));
95+ assertThat(batch.isIdempotent()).isNull();
96+
97+ batch.add(statementWithIdempotency(false));
98+ assertThat(batch.isIdempotent()).isFalse();
99+
100+ batch.add(statementWithIdempotency(true));
101+ assertThat(batch.isIdempotent()).isFalse();
102+
103+ batch.add(statementWithIdempotency(null));
104+ assertThat(batch.isIdempotent()).isFalse();
105+
106+ batch.add(statementWithIdempotency(false));
107+ assertThat(batch.isIdempotent()).isFalse();
108+ }
109+
110+ @Test(groups = "unit")
111+ public void isIdempotent_should_return_override_flag_if_no_statements_added() {
112+ TestBatch batch = createBatch();
113+ assertThat(batch.isIdempotent()).isTrue();
114+
115+ batch.setIdempotent(false);
116+ assertThat(batch.isIdempotent()).isFalse();
117+ }
118+
119+ @Test(groups = "unit")
120+ public void isIdempotent_should_return_override_flag_if_calculated_idempotency_true() {
121+ TestBatch batch = createBatch();
122+ assertThat(batch.isIdempotent()).isTrue();
123+
124+ batch.add(statementWithIdempotency(true));
125+ assertThat(batch.isIdempotent()).isTrue();
126+
127+ batch.setIdempotent(false);
128+ assertThat(batch.isIdempotent()).isFalse();
129+ }
130+
131+ @Test(groups = "unit")
132+ public void isIdempotent_should_return_override_flag_if_calculated_idempotency_null() {
133+ TestBatch batch = createBatch();
134+ assertThat(batch.isIdempotent()).isTrue();
135+
136+ batch.add(statementWithIdempotency(null));
137+ assertThat(batch.isIdempotent()).isNull();
138+
139+ batch.setIdempotent(false);
140+ assertThat(batch.isIdempotent()).isFalse();
141+ }
142+
143+ @Test(groups = "unit")
144+ public void isIdempotent_should_return_override_flag_if_calculated_idempotency_false() {
145+ TestBatch batch = createBatch();
146+ assertThat(batch.isIdempotent()).isTrue();
147+
148+ batch.add(statementWithIdempotency(false));
149+ assertThat(batch.isIdempotent()).isFalse();
150+
151+ batch.setIdempotent(true);
152+ assertThat(batch.isIdempotent()).isTrue();
153+ }
154+
155+ @Test(groups = "unit")
156+ public void isIdempotent_should_return_override_flag_if_calculated_idempotency_equals_override_value() {
157+ TestBatch batch = createBatch();
158+ assertThat(batch.isIdempotent()).isTrue();
159+
160+ batch.add(statementWithIdempotency(false));
161+ assertThat(batch.isIdempotent()).isFalse();
162+
163+ batch.setIdempotent(false);
164+ assertThat(batch.isIdempotent()).isFalse();
165+ }
166+
167+ private RegularStatement statementWithIdempotency(Boolean idempotency) {
168+ RegularStatement statement = new SimpleStatement("fake statement");
169+ if (idempotency != null) {
170+ statement.setIdempotent(idempotency);
171+ assertThat(statement.isIdempotent()).isEqualTo(idempotency);
172+ } else {
173+ assertThat(statement.isIdempotent()).isNull();
174+ }
175+ return statement;
176+ }
177+}
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +128 −17
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.InvalidQueryException;
19+import com.datastax.driver.core.utils.CassandraVersion;
1920 import com.google.common.base.Function;
2021 import com.google.common.base.Throwables;
2122 import com.google.common.collect.Lists;
@@ -25,7 +26,9 @@
2526 import org.testng.annotations.DataProvider;
2627 import org.testng.annotations.Test;
2728
29+import java.nio.ByteBuffer;
2830 import java.util.Collection;
31+import java.util.Map;
2932 import java.util.concurrent.*;
3033
3134 import static org.assertj.core.api.Assertions.assertThat;
@@ -48,9 +51,9 @@
4851 String keyspace = (String) objects[0];
4952 execute(
5053 String.format("create keyspace %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace),
51- String.format("create table %s.foo(k int primary key, v int)", keyspace),
52- String.format("insert into %s.foo (k, v) values (1, 1)", keyspace)
53- );
54+ String.format("create table %s.foo(k int, v int, primary key (k, v))", keyspace));
55+ for (int v = 1; v <= 100; v++)
56+ execute(String.format("insert into %s.foo (k, v) values (1, %d)", keyspace, v));
5457 }
5558 }
5659
@@ -127,7 +130,6 @@
127130
128131 @Test(groups = "short")
129132 public void should_fail_when_synchronous_call_on_io_thread() throws Exception {
130- final Thread sameThread = Thread.currentThread();
131133 for (int i = 0; i < 1000; i++) {
132134 ResultSetFuture f = session().executeAsync("select release_version from system.local");
133135 ListenableFuture<Thread> f2 = Futures.transform(f, new Function<ResultSet, Thread>() {
@@ -137,26 +139,74 @@
137139 return Thread.currentThread();
138140 }
139141 });
140- try {
141- Thread executedThread = f2.get();
142- if(executedThread != sameThread) {
143- fail("Expected a failed future, callback was executed on " + executedThread);
144- } else {
145- // Callback was invoked on the same thread, which indicates that the future completed
146- // before the transform callback was registered. Try again to produce case where callback
147- // is called on io thread.
148- logger.warn("Future completed before transform callback registered, will try again.");
142+ if (isFailed(f2, IllegalStateException.class, "Detected a synchronous call on an I/O thread")) {
143+ return;
144+ }
145+ }
146+ fail("callback was not executed on io thread in 1000 attempts, something may be wrong.");
147+ }
148+
149+ @Test(groups = "short")
150+ public void should_fail_when_synchronous_call_on_io_thread_with_session_wrapper() throws Exception {
151+ final Session session = new SessionWrapper(session());
152+ for (int i = 0; i < 1000; i++) {
153+ ResultSetFuture f = session.executeAsync("select release_version from system.local");
154+ ListenableFuture<Thread> f2 = Futures.transform(f, new Function<ResultSet, Thread>() {
155+ @Override
156+ public Thread apply(ResultSet input) {
157+ session.execute("select release_version from system.local");
158+ return Thread.currentThread();
159+ }
160+ });
161+ if (isFailed(f2, IllegalStateException.class, "Detected a synchronous call on an I/O thread")) {
162+ return;
163+ }
164+ }
165+ fail("callback was not executed on io thread in 1000 attempts, something may be wrong.");
166+ }
167+
168+ @Test(groups = "short")
169+ @CassandraVersion(major = 2.0, description = "Paging is not supported until 2.0")
170+ public void should_fail_when_auto_paging_on_io_thread() throws Exception {
171+ for (int i = 0; i < 1000; i++) {
172+ Statement statement = new SimpleStatement("select v from asyncquerytest.foo where k = 1");
173+ // Ensure results will be paged (there are 100 rows in the test table)
174+ statement.setFetchSize(10);
175+ ResultSetFuture f = session().executeAsync(statement);
176+ ListenableFuture<Thread> f2 = Futures.transform(f, new Function<ResultSet, Thread>() {
177+ @Override
178+ public Thread apply(ResultSet rs) {
179+ rs.all(); // Consume the whole result set
180+ return Thread.currentThread();
149181 }
150- } catch (Exception e) {
151- assertThat(Throwables.getRootCause(e))
152- .isInstanceOf(IllegalStateException.class)
153- .hasMessageContaining("Detected a synchronous Session call");
182+ });
183+ if (isFailed(f2, IllegalStateException.class, "Detected a synchronous call on an I/O thread")) {
154184 return;
155185 }
156186 }
157187 fail("callback was not executed on io thread in 1000 attempts, something may be wrong.");
158188 }
159189
190+ private boolean isFailed(ListenableFuture<Thread> future, Class<?> expectedException, String expectedMessage) {
191+ try {
192+ Thread executedThread = future.get();
193+ if (executedThread != Thread.currentThread()) {
194+ fail("Expected a failed future, callback was executed on " + executedThread);
195+ } else {
196+ // Callback was invoked on the same thread, which indicates that the future completed
197+ // before the transform callback was registered. Try again to produce case where callback
198+ // is called on io thread.
199+ logger.warn("Future completed before transform callback registered, will try again.");
200+ }
201+ } catch (Exception e) {
202+ assertThat(Throwables.getRootCause(e))
203+ .isInstanceOf(expectedException)
204+ .hasMessageContaining(expectedMessage);
205+ return true;
206+ }
207+ return false;
208+ }
209+
160210 private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) {
161211 ListenableFuture<Session> sessionFuture = cluster().connectAsync(keyspace);
162212 ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() {
@@ -178,4 +228,65 @@
178228 assertEquals(pools.size(), 1);
179229 return pools.iterator().next();
180230 }
231+
232+ private static class SessionWrapper extends AbstractSession {
233+
234+ private final Session session;
235+
236+ public SessionWrapper(Session session) {
237+ this.session = session;
238+ }
239+
240+ @Override
241+ public ResultSet execute(Statement statement) {
242+ // test a custom call to checkNotInEventLoop()
243+ checkNotInEventLoop();
244+ return executeAsync(statement).getUninterruptibly();
245+ }
246+
247+ @Override
248+ public String getLoggedKeyspace() {
249+ return session.getLoggedKeyspace();
250+ }
251+
252+ @Override
253+ public Session init() {
254+ return session.init();
255+ }
256+
257+ @Override
258+ public ListenableFuture<Session> initAsync() {
259+ return session.initAsync();
260+ }
261+
262+ @Override
263+ public ResultSetFuture executeAsync(Statement statement) {
264+ return session.executeAsync(statement);
265+ }
266+
267+ @Override
268+ public CloseFuture closeAsync() {
269+ return session.closeAsync();
270+ }
271+
272+ @Override
273+ public boolean isClosed() {
274+ return session.isClosed();
275+ }
276+
277+ @Override
278+ public Cluster getCluster() {
279+ return session.getCluster();
280+ }
281+
282+ @Override
283+ public State getState() {
284+ return session.getState();
285+ }
286+
287+ @Override
288+ protected ListenableFuture<PreparedStatement> prepareAsync(String query, Map<String, ByteBuffer> customPayload) {
289+ return ((SessionManager) session).prepareAsync(query, customPayload);
290+ }
291+ }
181292 }
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +12 −2
@@ -24,6 +24,7 @@
2424
2525 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2626 import static com.datastax.driver.core.TestUtils.findHost;
27+import static org.assertj.core.api.Assertions.assertThat;
2728 import static org.mockito.Mockito.*;
2829
2930 /**
@@ -55,6 +56,7 @@
5556 .build();
5657 cluster.connect();
5758 verify(authProvider, atLeastOnce()).newAuthenticator(findHost(cluster, 1).getSocketAddress(), "org.apache.cassandra.auth.PasswordAuthenticator");
59+ assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()).isEqualTo(0);
5860 }
5961
6062 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
@@ -64,7 +66,11 @@
6466 .withPort(ccm().getBinaryPort())
6567 .withCredentials("bogus", "bogus")
6668 .build());
67- cluster.connect();
69+ try {
70+ cluster.connect();
71+ } finally {
72+ assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()).isEqualTo(1);
73+ }
6874 }
6975
7076 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
@@ -73,7 +79,11 @@
7379 .addContactPoints(getContactPoints())
7480 .withPort(ccm().getBinaryPort())
7581 .build());
76- cluster.connect();
82+ try {
83+ cluster.connect();
84+ } finally {
85+ assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()).isEqualTo(1);
86+ }
7787 }
7888
7989 }
added driver-core/src/test/java/com/datastax/driver/core/BatchStatementIdempotencyTest.java +44 −0
@@ -0,0 +1,44 @@
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+package com.datastax.driver.core;
17+
18+public class BatchStatementIdempotencyTest extends AbstractBatchIdempotencyTest {
19+
20+ @Override
21+ protected TestBatch createBatch() {
22+ return new TestBatchStatementWrapper();
23+ }
24+
25+ static class TestBatchStatementWrapper implements TestBatch {
26+
27+ private final BatchStatement batch = new BatchStatement();
28+
29+ @Override
30+ public void add(RegularStatement statement) {
31+ batch.add(statement);
32+ }
33+
34+ @Override
35+ public Boolean isIdempotent() {
36+ return batch.isIdempotent();
37+ }
38+
39+ @Override
40+ public void setIdempotent(boolean idempotent) {
41+ batch.setIdempotent(idempotent);
42+ }
43+ }
44+}
added driver-core/src/test/java/com/datastax/driver/core/CompressionTest.java +55 −0
@@ -0,0 +1,55 @@
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+package com.datastax.driver.core;
17+
18+import java.util.Locale;
19+
20+import static com.datastax.driver.core.SessionTest.checkExecuteResultSet;
21+import static org.assertj.core.api.Assertions.assertThat;
22+
23+public class CompressionTest extends CCMTestsSupport {
24+
25+ private static String TABLE = "test";
26+
27+ public void onTestContextInitialized() {
28+ execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE));
29+ }
30+
31+ void compressionTest(ProtocolOptions.Compression compression) {
32+ cluster().getConfiguration().getProtocolOptions().setCompression(compression);
33+ try {
34+ Session compressedSession = cluster().connect(keyspace);
35+
36+ // Simple calls to all versions of the execute/executeAsync methods
37+ String key = "execute_compressed_test_" + compression;
38+ ResultSet rs = compressedSession.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE, key, "foo", 42, 24.03f));
39+ assertThat(rs.isExhausted()).isTrue();
40+
41+ String SELECT_ALL = String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = '%s'", TABLE, key);
42+
43+ // execute
44+ checkExecuteResultSet(compressedSession.execute(SELECT_ALL), key);
45+ checkExecuteResultSet(compressedSession.execute(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key);
46+
47+ // executeAsync
48+ checkExecuteResultSet(compressedSession.executeAsync(SELECT_ALL).getUninterruptibly(), key);
49+ checkExecuteResultSet(compressedSession.executeAsync(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
50+
51+ } finally {
52+ cluster().getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.NONE);
53+ }
54+ }
55+}
modified driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java +1 −3
@@ -110,9 +110,7 @@
110110 }
111111 });
112112
113- // Wait for up to pool timeout for response. If future is not complete by then, we can assume
114- // that it is likely that the execute is hung because the connection wasn't released yet.
115- long waitTimeInMs = cluster.getConfiguration().getPoolingOptions().getPoolTimeoutMillis();
113+ long waitTimeInMs = 2000;
116114 try {
117115 ResultSet result = future.get(waitTimeInMs, TimeUnit.MILLISECONDS);
118116 assertThat(result.one().getString("n")).isEqualTo("world");
added driver-core/src/test/java/com/datastax/driver/core/DirectCompressionTest.java +47 −0
@@ -0,0 +1,47 @@
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+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.utils.CassandraVersion;
19+import org.testng.annotations.Test;
20+
21+public class DirectCompressionTest extends CompressionTest {
22+
23+ /**
24+ * Validates that a session can be established using snappy compression and executes some queries that inserts and
25+ * retrieves data using that session().
26+ *
27+ * @test_category connection:compression
28+ * @expected_result session established and queries made successfully using it.
29+ */
30+ @Test(groups = "short")
31+ public void should_function_with_snappy_compression() throws Exception {
32+ compressionTest(ProtocolOptions.Compression.SNAPPY);
33+ }
34+
35+ /**
36+ * Validates that a session can be established using lz4 compression and executes some queries that inserts and
37+ * retrieves data using that session().
38+ *
39+ * @test_category connection:compression
40+ * @expected_result session established and queries made successfully using it.
41+ */
42+ @Test(groups = "short")
43+ @CassandraVersion(major = 2.0)
44+ public void should_function_with_lz4_compression() throws Exception {
45+ compressionTest(ProtocolOptions.Compression.LZ4);
46+ }
47+}
added driver-core/src/test/java/com/datastax/driver/core/FrameLengthTest.java +121 −0
@@ -0,0 +1,121 @@
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+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.exceptions.FrameTooLongException;
19+import com.datastax.driver.core.querybuilder.Insert;
20+import com.datastax.driver.core.schemabuilder.Create;
21+import com.datastax.driver.core.schemabuilder.SchemaBuilder;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
24+import org.testng.annotations.BeforeClass;
25+import org.testng.annotations.Test;
26+
27+import java.nio.ByteBuffer;
28+import java.util.Collection;
29+import java.util.Random;
30+
31+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
32+import static org.assertj.core.api.Assertions.assertThat;
33+import static org.assertj.core.api.Fail.fail;
34+
35+@CCMConfig(numberOfNodes = 2)
36+public class FrameLengthTest extends CCMTestsSupport {
37+
38+ Logger logger = LoggerFactory.getLogger(FrameLengthTest.class);
39+
40+ private static final String tableName = "blob_table";
41+ private static final int colCount = 256;
42+ private static final int rowsPerPartitionCount = 4;
43+ private static final int partitionCount = 1;
44+ private static final int bytesPerCol = 1024;
45+
46+ @BeforeClass(groups = {"isolated"})
47+ public void beforeTestClass() throws Exception {
48+ // Set max frame size to 1MB to make it easier to manifest frame length error.
49+ System.setProperty("com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB", "1");
50+ super.beforeTestClass();
51+ }
52+
53+ @Override
54+ public void onTestContextInitialized() {
55+ logger.info("Creating table {} with {} {}-byte blob columns", tableName, colCount, bytesPerCol);
56+ Random random = new Random();
57+ // Create table
58+ Create create = SchemaBuilder.createTable(tableName).addPartitionKey("k", DataType.cint()).addClusteringColumn("c", DataType.cint());
59+ for (int i = 0; i < colCount; i++) {
60+ create.addColumn("col" + i, DataType.blob());
61+ }
62+ execute(create.getQueryString());
63+
64+ // build prepared statement.
65+ Insert insert = insertInto(tableName).value("k", bindMarker()).value("c", bindMarker());
66+ for (int i = 0; i < colCount; i++) {
67+ insert = insert.value("col" + i, bindMarker());
68+ }
69+
70+ PreparedStatement prepared = session().prepare(insert);
71+
72+ // Insert rows.
73+ logger.info("Inserting data for {} partitions.", partitionCount);
74+ for (int i = 0; i < partitionCount; i++) {
75+ logger.info("Inserting {} rows in partition {}", rowsPerPartitionCount, i);
76+ for (int r = 0; r < rowsPerPartitionCount; r++) {
77+ BoundStatement stmt = prepared.bind();
78+ stmt.setInt("k", i);
79+ stmt.setInt("c", r);
80+ for (int c = 0; c < colCount; c++) {
81+ byte[] b = new byte[bytesPerCol];
82+ random.nextBytes(b);
83+ ByteBuffer in = ByteBuffer.wrap(b);
84+ stmt.setBytes("col" + c, in);
85+ }
86+ session().execute(stmt);
87+ }
88+ }
89+ logger.info("Done loading {}", tableName);
90+ }
91+
92+ /**
93+ * Validates that if a frame is received that exceeds NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB that
94+ * the driver is able to recover, not lose host connectivity and make further queries. It
95+ * configures NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB to 1 MB to make the error easier to reproduce.
96+ *
97+ * @jira_ticket JAVA-1292
98+ * @jira_ticket JAVA-1293
99+ * @test_category connection
100+ */
101+ @Test(groups = "isolated")
102+ public void should_throw_exception_when_frame_exceeds_configured_max() {
103+ try {
104+ session().execute(select().from(tableName).where(eq("k", 0)));
105+ fail("Exception expected");
106+ } catch (FrameTooLongException ftle) {
107+ // Expected.
108+ }
109+
110+ // Both hosts should remain up.
111+ Collection<Host> hosts = session().getState().getConnectedHosts();
112+ assertThat(hosts).hasSize(2).extractingResultOf("isUp").containsOnly(true);
113+
114+ // Should be able to make a query that is less than the max frame size.
115+ // Execute multiple time to exercise all hosts.
116+ for (int i = 0; i < 10; i++) {
117+ ResultSet result = session().execute(select().from(tableName).where(eq("k", 0)).and(eq("c", 0)));
118+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
119+ }
120+ }
121+}
added driver-core/src/test/java/com/datastax/driver/core/HeapCompressionTest.java +54 −0
@@ -0,0 +1,54 @@
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+package com.datastax.driver.core;
17+
18+import com.datastax.driver.core.utils.CassandraVersion;
19+import org.testng.annotations.BeforeClass;
20+import org.testng.annotations.Test;
21+
22+public class HeapCompressionTest extends CompressionTest {
23+
24+ @BeforeClass(groups = "isolated")
25+ public void beforeTestClass() throws Exception {
26+ // Configure with noPreferDirect and noUnsafe to force heap buffers.
27+ System.setProperty("io.netty.noPreferDirect", "true");
28+ System.setProperty("io.netty.noUnsafe", "true");
29+ super.beforeTestClass();
30+ }
31+
32+ /**
33+ * Validates that snappy compression still works when using heap buffers.
34+ *
35+ * @test_category connection:compression
36+ * @expected_result session established and queries made successfully using it.
37+ */
38+ @Test(groups = "isolated")
39+ public void should_function_with_snappy_compression() throws Exception {
40+ compressionTest(ProtocolOptions.Compression.SNAPPY);
41+ }
42+
43+ /**
44+ * Validates that lz4 compression still works when using heap buffers.
45+ *
46+ * @test_category connection:compression
47+ * @expected_result session established and queries made successfully using it.
48+ */
49+ @Test(groups = "isolated")
50+ @CassandraVersion(major = 2.0)
51+ public void should_function_with_lz4_compression() throws Exception {
52+ compressionTest(ProtocolOptions.Compression.LZ4);
53+ }
54+}
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +421 −144
@@ -16,10 +16,11 @@
1616 package com.datastax.driver.core;
1717
1818 import com.codahale.metrics.Gauge;
19-import com.datastax.driver.core.exceptions.BusyConnectionException;
20-import com.datastax.driver.core.exceptions.ConnectionException;
19+import com.datastax.driver.core.exceptions.*;
2120 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
21+import com.datastax.driver.core.utils.MoreFutures;
2222 import com.google.common.base.Predicate;
23+import com.google.common.base.Throwables;
2324 import com.google.common.util.concurrent.*;
2425 import org.scassandra.cql.PrimitiveType;
2526 import org.scassandra.http.client.PrimingRequest;
@@ -27,6 +28,7 @@
2728 import org.testng.annotations.Test;
2829
2930 import java.net.InetSocketAddress;
31+import java.util.Collections;
3032 import java.util.Iterator;
3133 import java.util.List;
3234 import java.util.concurrent.*;
@@ -35,8 +37,8 @@
3537
3638 import static com.datastax.driver.core.Assertions.assertThat;
3739 import static com.datastax.driver.core.ConditionChecker.check;
40+import static com.datastax.driver.core.PoolingOptions.NEW_CONNECTION_THRESHOLD_LOCAL_KEY;
3841 import static com.google.common.collect.Lists.newArrayList;
39-import static java.util.Collections.singletonList;
4042 import static java.util.concurrent.TimeUnit.SECONDS;
4143 import static org.mockito.Mockito.*;
4244 import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
@@ -45,6 +47,9 @@
4547
4648 public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
4749
50+ static final Integer NEW_CONNECTION_THRESHOLD = PoolingOptions.DEFAULTS.get(ProtocolVersion.V1)
51+ .get(NEW_CONNECTION_THRESHOLD_LOCAL_KEY);
52+
4853 @BeforeClass(groups = {"short", "long"})
4954 public void reinitializeCluster() {
5055 // Don't use the provided cluster, each test will create its own instead.
@@ -67,136 +72,317 @@
6772 }).becomesTrue();
6873 }
6974
70- /**
71- * Sends 101 requests on pool, asserting that the connection used is in expectedConnections, except for the last request.
72- */
73- private List<MockRequest> fillConnectionToThreshold(HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
74- List<MockRequest> requests = sendRequests(100, pool, expectedConnections);
75- requests.add(MockRequest.send(pool));
76- return requests;
75+ private void assertBorrowedConnections(Iterable<MockRequest> requests, List<Connection> expectedConnections) {
76+ for (MockRequest request : requests) {
77+ assertThat(expectedConnections).contains(request.getConnection());
78+ }
79+ }
80+
81+ private void assertBorrowedConnection(Iterable<MockRequest> requests, Connection expectedConnection) {
82+ assertBorrowedConnections(requests, Collections.singletonList(expectedConnection));
7783 }
7884
7985 /**
80- * Sends count requests on pool.
86+ * Ensures that if a fixed-sized pool has filled its core connections and reached its maximum number of enqueued
87+ * requests, then borrowConnection will fail instead of creating a new connection.
88+ *
89+ * @jira_ticket JAVA-419
90+ * @test_category connection:connection_pool
91+ * @since 2.0.10, 2.1.6
8192 */
82- private List<MockRequest> sendRequests(int count, HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
83- return sendRequests(count, pool, null);
93+ @Test(groups = "short")
94+ public void fixed_size_pool_should_fill_its_core_connections_and_queue_and_then_reject() {
95+ Cluster cluster = createClusterBuilder().build();
96+ List<MockRequest> allRequests = newArrayList();
97+ try {
98+ HostConnectionPool pool = createPool(cluster, 2, 2);
99+ int maxQueueSize = 256;
100+
101+ assertThat(pool.connections.size()).isEqualTo(2);
102+ List<Connection> coreConnections = newArrayList(pool.connections);
103+ // fill connections
104+ List<MockRequest> requests = MockRequest.sendMany(2 * 128, pool);
105+ assertBorrowedConnections(requests, coreConnections);
106+ allRequests.addAll(requests);
107+ // fill queue
108+ allRequests.addAll(MockRequest.sendMany(maxQueueSize, pool, maxQueueSize));
109+
110+ // add one more request, it should be rejected because the queue is full
111+ MockRequest failedBorrow = MockRequest.send(pool, maxQueueSize);
112+ try {
113+ failedBorrow.getConnection();
114+ fail("Expected a BusyPoolException");
115+ } catch (BusyPoolException e) {/*expected*/}
116+ } finally {
117+ MockRequest.completeAll(allRequests);
118+ cluster.close();
119+ }
84120 }
85121
86122 /**
87- * Sends count requests on pool, asserting that the connection used is in expectedConnections.
123+ * Ensures that any enqueued connection borrow requests are failed when their associated connection pool closes.
124+ *
125+ * @jira_ticket JAVA-839
126+ * @test_category connection:connection_pool
127+ * @since 3.0.4, 3.1.1
88128 */
89- private List<MockRequest> sendRequests(int count, HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
129+ @Test(groups = "short")
130+ public void requests_with_enqueued_borrow_requests_should_be_failed_when_pool_closes() {
131+ Cluster cluster = createClusterBuilder().build();
90132 List<MockRequest> requests = newArrayList();
91- for (int i = 0; i < count; i++) {
92- MockRequest request = MockRequest.send(pool);
93- requests.add(request);
94- if (expectedConnections != null)
95- assertThat(expectedConnections).contains(request.connection);
96- }
97- return requests;
133+ try {
134+ HostConnectionPool pool = createPool(cluster, 2, 2);
135+ int maxQueueSize = 256;
136+
137+ assertThat(pool.connections.size()).isEqualTo(2);
138+ List<Connection> coreConnections = newArrayList(pool.connections);
139+ // fill connections
140+ requests = MockRequest.sendMany(2 * 128, pool);
141+ assertBorrowedConnections(requests, coreConnections);
142+ // fill queue
143+ List<MockRequest> queuedRequests = MockRequest.sendMany(maxQueueSize, pool, maxQueueSize);
144+
145+ // Closing the pool should fail all queued connections.
146+ pool.closeAsync();
147+
148+ for (MockRequest queuedRequest : queuedRequests) {
149+ // Future should be completed.
150+ assertThat(queuedRequest.connectionFuture.isDone()).isTrue();
151+ try {
152+ // Future should fail as result of the pool closing.
153+ queuedRequest.getConnection();
154+ fail("Expected a ConnectionException");
155+ } catch (ConnectionException e) {/*expected*/}
156+ }
157+ } finally {
158+ MockRequest.completeAll(requests);
159+ cluster.close();
160+ }
98161 }
99162
100163 /**
101- * Completes count requests by simulating a successful response.
164+ * Validates that if the keyspace tied to the Session's pool state is different than the keyspace on the connection
165+ * being used in dequeue that {@link Connection#setKeyspaceAsync(String)} is set on that connection and that
166+ * "USE keyspace" is only called once since setKeyspaceAsync should not attempt setting the keyspace if there is
167+ * already a request inflight that is doing this.
168+ *
169+ * @jira_ticket JAVA-839
170+ * @test_category connection:connection_pool
171+ * @since 3.0.4, 3.1.1
102172 */
103- private void completeRequests(int count, List<MockRequest> requests) {
104- Iterator<MockRequest> requestIt = requests.iterator();
105- for (int i = 0; i < count; i++) {
106- if (requestIt.hasNext()) {
107- MockRequest request = requestIt.next();
108- request.simulateSuccessResponse();
109- requestIt.remove();
110- } else {
111- break;
173+ @Test(groups = "short")
174+ public void should_adjust_connection_keyspace_on_dequeue_if_pool_state_is_different() throws TimeoutException, ExecutionException {
175+ Cluster cluster = createClusterBuilder().build();
176+ List<MockRequest> requests = newArrayList();
177+ try {
178+ HostConnectionPool pool = createPool(cluster, 1, 1);
179+ int maxQueueSize = 256;
180+
181+ assertThat(pool.connections.size()).isEqualTo(1);
182+ List<Connection> coreConnections = newArrayList(pool.connections);
183+ // fill connections
184+ requests = MockRequest.sendMany(128, pool);
185+ assertBorrowedConnections(requests, coreConnections);
186+ // fill queue
187+ List<MockRequest> queuedRequests = MockRequest.sendMany(maxQueueSize, pool, maxQueueSize);
188+
189+ // Wait for connections to be borrowed before changing keyspace.
190+ for (MockRequest request : requests) {
191+ Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS);
192+ }
193+ // Simulate change of keyspace on pool. Prime a delay so existing requests can complete beforehand.
194+ primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"newkeyspace\"").withThen(PrimingRequest.then().withFixedDelay(2000L)));
195+ pool.manager.poolsState.setKeyspace("newkeyspace");
196+
197+ // Complete all requests, this should cause dequeue on connection.
198+ MockRequest.completeAll(requests);
199+
200+ // Check the status on queued request's connection futures. We expect that dequeue should
201+ // be called when connection is released by previous requests completing, and that one set
202+ // keyspace attempt should be tried.
203+
204+ // Because Scassandra currently returns a 'ROWS' response for set keyspace, the attempt
205+ // will fail, and thus the enqueued connection futures will fail in the following ways:
206+ // 1. DriverInternalError for set keyspace returning 'ROWS' response
207+ // 2. TransportException for connection being closed, when this happens we stop checking these futures.
208+ // 3. Never completing because no connections are available.
209+ boolean timeoutAcceptable = false;
210+ for (MockRequest queuedRequest : queuedRequests) {
211+ try {
212+ Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS);
213+ fail("Expected an exception (because Scassandra doesn't support 'USE keyspace'");
214+ } catch (ExecutionException e) {
215+ try {
216+ throw e.getCause();
217+ } catch (DriverInternalError die) {
218+ assertThat(die.getMessage()).contains("Unexpected response while setting keyspace");
219+ // Subsequent futures may timeout because the connection is closed.
220+ timeoutAcceptable = true;
221+ } catch (TransportException ce) {
222+ /* expected, Scassandra returning a ROWS response for 'USE keyspace' should defunct and close the connection */
223+ // all remaining futures will timeout since there are no remaining connections.
224+ break;
225+ } catch (Throwable t) {
226+ fail("Unexpected cause of future failing", t);
227+ }
228+ } catch (TimeoutException te) {
229+ assertThat(timeoutAcceptable).isTrue();
230+ break;
231+ }
112232 }
233+
234+ // We should only have gotten one 'USE newkeyspace' query since Connection#setKeyspaceAsync should only do
235+ // this once if there is already a request in flight.
236+ assertThat(activityClient.retrieveQueries()).extractingResultOf("getQuery").containsOnlyOnce("USE \"newkeyspace\"");
237+ } finally {
238+ MockRequest.completeAll(requests);
239+ cluster.close();
113240 }
114241 }
115242
116243 /**
117- * Completes all requests by simulating a successful response.
244+ * Ensures that on borrowConnection if a set keyspace attempt is in progress on that connection for a different keyspace than the
245+ * pool state that the borrowConnection future returned is failed.
246+ *
247+ * @jira_ticket JAVA-839
248+ * @test_category connection:connection_pool
249+ * @since 3.0.4, 3.1.1
118250 */
119- private void completeRequests(List<MockRequest> requests) {
120- for (MockRequest request : requests) {
121- request.simulateSuccessResponse();
251+ @Test(groups = "short")
252+ public void should_fail_in_borrowConnection_when_setting_keyspace_and_another_set_keyspace_attempt_is_in_flight() throws TimeoutException {
253+ Cluster cluster = createClusterBuilder().build();
254+ try {
255+ HostConnectionPool pool = createPool(cluster, 1, 1);
256+
257+ // Respond to setting as slowks very slowly.
258+ primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"slowks\"").withThen(PrimingRequest.then().withFixedDelay(5000L)));
259+
260+ Connection connection = pool.connections.get(0);
261+
262+ connection.setKeyspaceAsync("slowks");
263+
264+ // Simulate change of keyspace on pool.
265+ pool.manager.poolsState.setKeyspace("newks");
266+
267+ MockRequest request = MockRequest.send(pool);
268+
269+ try {
270+ Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS);
271+ fail("Should have thrown exception");
272+ } catch (ExecutionException e) {
273+ assertThat(e.getCause()).isInstanceOf(DriverException.class);
274+ assertThat(e.getCause().getMessage()).contains("Aborting attempt to set keyspace to 'newks' since there is already an in flight attempt to set keyspace to 'slowks'.");
275+ }
276+ } finally {
277+ cluster.close();
122278 }
123279 }
124280
125281 /**
126- * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
127- * of creating a new connection.
282+ * Ensures that while dequeuing borrow connection requests that if a set keyspace attempt is in progress on that connection for a difference
283+ * keyspace than the pool state that the future for that borrow attempt is failed.
128284 *
129- * @jira_ticket JAVA-419
285+ * @jira_ticket JAVA-839
130286 * @test_category connection:connection_pool
131- * @since 2.0.10, 2.1.6
287+ * @since 3.0.4, 3.1.1
132288 */
133289 @Test(groups = "short")
134- public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException {
290+ public void should_fail_in_dequeue_when_setting_keyspace_and_another_set_keyspace_attempt_is_in_flight() throws ExecutionException, TimeoutException {
135291 Cluster cluster = createClusterBuilder().build();
136292 List<MockRequest> requests = newArrayList();
137293 try {
138- HostConnectionPool pool = createPool(cluster, 2, 2);
294+ // Limit requests per connection to 100 so we don't exhaust stream ids.
295+ cluster.getConfiguration().getPoolingOptions().setMaxRequestsPerConnection(HostDistance.LOCAL, 100);
296+ HostConnectionPool pool = createPool(cluster, 1, 1);
297+ int maxQueueSize = 256;
139298
140- assertThat(pool.connections.size()).isEqualTo(2);
299+ assertThat(pool.connections.size()).isEqualTo(1);
141300 List<Connection> coreConnections = newArrayList(pool.connections);
142- requests.addAll(sendRequests(256, pool, coreConnections));
301+
302+ // fill connections
303+ requests = MockRequest.sendMany(100, pool);
304+ assertBorrowedConnections(requests, coreConnections);
305+
306+ // send a request that will be queued.
307+ MockRequest queuedRequest = MockRequest.send(pool, maxQueueSize);
308+
309+ // Wait for connections to be borrowed before changing keyspace.
310+ for (MockRequest request : requests) {
311+ Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS);
312+ }
313+
314+ // Respond to setting as slowks very slowly.
315+ primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"slowks\"").withThen(PrimingRequest.then().withFixedDelay(5000L)));
316+ Connection connection = pool.connections.get(0);
317+ connection.setKeyspaceAsync("slowks");
318+
319+ // Simulate change of keyspace on pool.
320+ pool.manager.poolsState.setKeyspace("newkeyspace");
321+
322+ // Complete all requests, this should cause dequeue on connection.
323+ MockRequest.completeAll(requests);
143324
144325 try {
145- MockRequest.send(pool);
146- Assertions.fail("Expected a TimeoutException");
147- } catch (TimeoutException e) { /*expected*/}
326+ Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS);
327+ fail("Should have thrown exception");
328+ } catch (ExecutionException e) {
329+ assertThat(e.getCause()).isInstanceOf(DriverException.class);
330+ assertThat(e.getCause().getMessage()).contains("Aborting attempt to set keyspace to 'newkeyspace' since there is already an in flight attempt to set keyspace to 'slowks'.");
331+ }
332+
148333 } finally {
149- completeRequests(requests);
334+ MockRequest.completeAll(requests);
150335 cluster.close();
151336 }
152337 }
153338
154339 /**
155340 * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
156- * timeout instead of creating a new connection.
341+ * return a failed future instead of creating a new connection.
157342 *
158343 * @jira_ticket JAVA-419
159344 * @test_category connection:connection_pool
160345 * @since 2.0.10, 2.1.6
161346 */
162347 @Test(groups = "short")
163- public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
348+ public void variable_size_pool_should_fill_its_connections_and_then_reject() throws Exception {
164349 Cluster cluster = createClusterBuilder().build();
165- List<MockRequest> requests = newArrayList();
350+ List<MockRequest> allRequests = newArrayList();
166351 try {
167352 HostConnectionPool pool = createPool(cluster, 1, 2);
168353 Connection.Factory factory = spy(cluster.manager.connectionFactory);
169354 cluster.manager.connectionFactory = factory;
170355
171356 assertThat(pool.connections.size()).isEqualTo(1);
172- List<Connection> coreConnections = newArrayList(pool.connections);
357+ Connection coreConnection = pool.connections.get(0);
173358
174359 // Fill enough connections to hit the threshold.
175- requests.addAll(fillConnectionToThreshold(pool, coreConnections));
360+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
361+ assertBorrowedConnection(requests, coreConnection);
362+ allRequests.addAll(requests);
363+ allRequests.add(MockRequest.send(pool));
176364
177365 // Allow time for new connection to be spawned.
178366 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
179367 assertPoolSize(pool, 2);
180368
181369 // Borrow more and ensure the connection returned is a non-core connection.
182- for (int i = 0; i < 100; i++) {
370+ for (int i = 0; i < NEW_CONNECTION_THRESHOLD; i++) {
183371 MockRequest request = MockRequest.send(pool);
184- assertThat(coreConnections).doesNotContain(request.connection);
185- requests.add(request);
372+ assertThat(request.getConnection()).isNotEqualTo(coreConnection);
373+ allRequests.add(request);
186374 }
187375
188376 // Fill remaining connections (28 + 28) - 1
189- requests.addAll(sendRequests(55, pool));
377+ allRequests.addAll(MockRequest.sendMany(55, pool));
190378
191- boolean timedOut = false;
379+ MockRequest failedBorrow = MockRequest.send(pool);
192380 try {
193- MockRequest.send(pool);
194- } catch (TimeoutException e) {
195- timedOut = true;
196- }
197- assertThat(timedOut).isTrue();
381+ failedBorrow.getConnection();
382+ fail("Expected a BusyPoolException");
383+ } catch (BusyPoolException e) { /*expected*/}
198384 } finally {
199- completeRequests(requests);
385+ MockRequest.completeAll(allRequests);
200386 cluster.close();
201387 }
202388 }
@@ -211,7 +397,7 @@
211397 @Test(groups = "short")
212398 public void should_add_extra_connection_when_core_full() throws Exception {
213399 Cluster cluster = createClusterBuilder().build();
214- List<MockRequest> requests = newArrayList();
400+ List<MockRequest> allRequests = newArrayList();
215401 try {
216402 HostConnectionPool pool = createPool(cluster, 1, 2);
217403 Connection.Factory factory = spy(cluster.manager.connectionFactory);
@@ -219,13 +405,16 @@
219405 Connection core = pool.connections.get(0);
220406
221407 // Fill core connection + 1
222- requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
408+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
409+ assertBorrowedConnection(requests, core);
410+ allRequests.addAll(requests);
411+ allRequests.add(MockRequest.send(pool));
223412
224413 // Reaching the threshold should have triggered the creation of an extra one
225414 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
226415 assertPoolSize(pool, 2);
227416 } finally {
228- completeRequests(requests);
417+ MockRequest.completeAll(allRequests);
229418 cluster.close();
230419 }
231420 }
@@ -241,14 +430,17 @@
241430 @Test(groups = "long")
242431 public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception {
243432 Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
244- List<MockRequest> requests = newArrayList();
433+ List<MockRequest> allRequests = newArrayList();
245434 try {
246435 HostConnectionPool pool = createPool(cluster, 1, 2);
247436 Connection.Factory factory = spy(cluster.manager.connectionFactory);
248437 cluster.manager.connectionFactory = factory;
249438 Connection connection1 = pool.connections.get(0);
250439
251- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
440+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
441+ assertBorrowedConnections(requests, Collections.singletonList(connection1));
442+ allRequests.addAll(requests);
443+ allRequests.add(MockRequest.send(pool));
252444
253445 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
254446 assertPoolSize(pool, 2);
@@ -258,7 +450,7 @@
258450 assertThat(connection2.inFlight.get()).isEqualTo(0);
259451
260452 // Go back under the capacity of 1 connection
261- completeRequests(51, requests);
453+ MockRequest.completeMany(51, allRequests);
262454
263455 assertThat(connection1.inFlight.get()).isEqualTo(50);
264456 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -269,7 +461,7 @@
269461 assertThat(pool.trash).containsExactly(connection1);
270462
271463 // Now borrow enough to go just under the 1 connection threshold
272- requests.addAll(sendRequests(50, pool));
464+ allRequests.addAll(MockRequest.sendMany(50, pool));
273465
274466 assertThat(pool.connections).containsExactly(connection2);
275467 assertThat(pool.trash).containsExactly(connection1);
@@ -277,7 +469,7 @@
277469 assertThat(connection2.inFlight.get()).isEqualTo(50);
278470
279471 // Borrowing one more time should resurrect the trashed connection
280- requests.addAll(sendRequests(1, pool));
472+ allRequests.addAll(MockRequest.sendMany(1, pool));
281473 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
282474 assertPoolSize(pool, 2);
283475
@@ -286,7 +478,7 @@
286478 assertThat(connection1.inFlight.get()).isEqualTo(50);
287479 assertThat(connection2.inFlight.get()).isEqualTo(51);
288480 } finally {
289- completeRequests(requests);
481+ MockRequest.completeAll(allRequests);
290482 cluster.close();
291483 }
292484 }
@@ -302,14 +494,17 @@
302494 @Test(groups = "long")
303495 public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception {
304496 Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
305- List<MockRequest> requests = newArrayList();
497+ List<MockRequest> allRequests = newArrayList();
306498 try {
307499 HostConnectionPool pool = createPool(cluster, 1, 2);
308500 Connection.Factory factory = spy(cluster.manager.connectionFactory);
309501 cluster.manager.connectionFactory = factory;
310502 Connection connection1 = pool.connections.get(0);
311503
312- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
504+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
505+ assertBorrowedConnection(requests, connection1);
506+ allRequests.addAll(requests);
507+ allRequests.add(MockRequest.send(pool));
313508
314509 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
315510 assertPoolSize(pool, 2);
@@ -320,7 +515,7 @@
320515 assertThat(connection2.inFlight.get()).isEqualTo(0);
321516
322517 // Go back under the capacity of 1 connection
323- completeRequests(51, requests);
518+ MockRequest.completeMany(51, allRequests);
324519
325520 assertThat(connection1.inFlight.get()).isEqualTo(50);
326521 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -331,7 +526,7 @@
331526 assertThat(pool.trash).containsExactly(connection1);
332527
333528 // Return trashed connection down to 0 inFlight
334- completeRequests(50, requests);
529+ MockRequest.completeMany(50, allRequests);
335530 assertThat(connection1.inFlight.get()).isEqualTo(0);
336531
337532 // Give enough time for trashed connection to be cleaned up from the trash:
@@ -341,19 +536,22 @@
341536 assertThat(connection1.isClosed()).isTrue();
342537
343538 // Fill the live connection to go over the threshold where a second one is needed
344- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection2)));
539+ requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
540+ assertBorrowedConnection(requests, connection2);
541+ allRequests.addAll(requests);
542+ allRequests.add(MockRequest.send(pool));
345543 assertThat(connection2.inFlight.get()).isEqualTo(101);
346544 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
347545 assertPoolSize(pool, 2);
348546
349547 // Borrow again to get the new connection
350548 MockRequest request = MockRequest.send(pool);
351- requests.add(request);
352- assertThat(request.connection)
549+ allRequests.add(request);
550+ assertThat(request.getConnection())
353551 .isNotEqualTo(connection2) // should not be the full connection
354552 .isNotEqualTo(connection1); // should not be the previously trashed one
355553 } finally {
356- completeRequests(requests);
554+ MockRequest.completeAll(allRequests);
357555 cluster.close();
358556 }
359557 }
@@ -368,7 +566,7 @@
368566 @Test(groups = "long")
369567 public void should_not_close_trashed_connection_until_no_in_flight() throws Exception {
370568 Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
371- List<MockRequest> requests = newArrayList();
569+ List<MockRequest> allRequests = newArrayList();
372570
373571 try {
374572 HostConnectionPool pool = createPool(cluster, 1, 2);
@@ -377,13 +575,16 @@
377575 Connection connection1 = pool.connections.get(0);
378576
379577 // Fill core connection enough to trigger creation of another one
380- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
578+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
579+ assertBorrowedConnections(requests, Collections.singletonList(connection1));
580+ allRequests.addAll(requests);
581+ allRequests.add(MockRequest.send(pool));
381582
382583 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
383584 assertThat(pool.connections).hasSize(2);
384585
385586 // Return enough times to get back under the threshold where one connection is enough
386- completeRequests(50, requests);
587+ MockRequest.completeMany(50, allRequests);
387588
388589 // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
389590 // It still has in-flight requests so should not get closed.
@@ -393,7 +594,7 @@
393594 assertThat(connection1.isClosed()).isFalse();
394595
395596 // Consume all inFlight requests on the trashed connection.
396- completeRequests(51, requests);
597+ MockRequest.completeMany(51, allRequests);
397598
398599 // Sleep enough time for the connection to be consider idled and closed.
399600 Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
@@ -404,7 +605,7 @@
404605 assertThat(pool.connections).doesNotContain(connection1);
405606 assertThat(pool.trash).doesNotContain(connection1);
406607 } finally {
407- completeRequests(requests);
608+ MockRequest.completeAll(allRequests);
408609 cluster.close();
409610 }
410611 }
@@ -420,14 +621,17 @@
420621 @Test(groups = "short")
421622 public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception {
422623 Cluster cluster = createClusterBuilder().build();
423- List<MockRequest> requests = newArrayList();
624+ List<MockRequest> allRequests = newArrayList();
424625 try {
425626 HostConnectionPool pool = createPool(cluster, 1, 2);
426627 Connection.Factory factory = spy(cluster.manager.connectionFactory);
427628 cluster.manager.connectionFactory = factory;
428629 Connection core = pool.connections.get(0);
429630
430- requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
631+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
632+ assertBorrowedConnections(requests, Collections.singletonList(core));
633+ allRequests.addAll(requests);
634+ allRequests.add(MockRequest.send(pool));
431635
432636 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
433637 assertThat(pool.connections).hasSize(2);
@@ -437,7 +641,7 @@
437641 pool.connections.set(1, extra1);
438642
439643 // Borrow 10 times to ensure pool is utilized.
440- requests.addAll(sendRequests(10, pool));
644+ allRequests.addAll(MockRequest.sendMany(10, pool));
441645 assertThat(pool.connections).hasSize(2);
442646
443647 // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
@@ -449,7 +653,7 @@
449653 pool.returnConnection(extra1);
450654 assertThat(pool.trash).hasSize(1);
451655 } finally {
452- completeRequests(requests);
656+ MockRequest.completeAll(allRequests);
453657 cluster.close();
454658 }
455659 }
@@ -486,7 +690,6 @@
486690 }
487691 }
488692
489-
490693 /**
491694 * Ensures that if all connections on a host are closed that the host is marked
492695 * down and the control connection is notified of that fact and re-established
@@ -561,7 +764,6 @@
561764 }
562765 }
563766
564-
565767 /**
566768 * Ensures that if a connection on a host is lost that brings the number of active connections in a pool
567769 * under core connection count that up to core connections are re-established, but only after the
@@ -580,7 +782,7 @@
580782 .setConnectTimeoutMillis(readTimeout)
581783 .setReadTimeoutMillis(reconnectInterval))
582784 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
583- List<MockRequest> requests = newArrayList();
785+ List<MockRequest> allRequests = newArrayList();
584786 try {
585787 cluster.init();
586788
@@ -608,8 +810,8 @@
608810
609811 // The borrowed connection should be the open one.
610812 MockRequest request = MockRequest.send(pool);
611- requests.add(request);
612- assertThat(request.connection).isEqualTo(core1);
813+ allRequests.add(request);
814+ assertThat(request.getConnection()).isEqualTo(core1);
613815
614816 // Should not have tried to create a new core connection since reconnection time had not elapsed.
615817 verify(factory, never()).open(any(HostConnectionPool.class));
@@ -620,8 +822,8 @@
620822 // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection.
621823 blockingExecutor.reset();
622824 request = MockRequest.send(pool);
623- requests.add(request);
624- assertThat(request.connection).isEqualTo(core1);
825+ allRequests.add(request);
826+ assertThat(request.getConnection()).isEqualTo(core1);
625827
626828 // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core.
627829 blockingExecutor.blockUntilNextTaskCompleted();
@@ -638,23 +840,23 @@
638840
639841 // Try to borrow a connection, the pool should grow.
640842 blockingExecutor.reset();
641- requests.add(MockRequest.send(pool));
843+ allRequests.add(MockRequest.send(pool));
642844 blockingExecutor.blockUntilNextTaskCompleted();
643845 verify(factory).open(any(HostConnectionPool.class));
644846 reset(factory);
645847
646848 // Another core connection should be opened as result of another request to get us up to core connections.
647849 blockingExecutor.reset();
648- requests.add(MockRequest.send(pool));
850+ allRequests.add(MockRequest.send(pool));
649851 blockingExecutor.blockUntilNextTaskCompleted();
650852 verify(factory).open(any(HostConnectionPool.class));
651853 reset(factory);
652854
653855 // Sending another request should not grow the pool any more, since we are now at core connections.
654- requests.add(MockRequest.send(pool));
856+ allRequests.add(MockRequest.send(pool));
655857 verify(factory, after((reconnectInterval + readTimeout) * 2).never()).open(any(HostConnectionPool.class));
656858 } finally {
657- completeRequests(requests);
859+ MockRequest.completeAll(allRequests);
658860 cluster.close();
659861 }
660862 }
@@ -677,7 +879,7 @@
677879 .setConnectTimeoutMillis(readTimeout)
678880 .setReadTimeoutMillis(reconnectInterval))
679881 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
680- List<MockRequest> requests = newArrayList();
882+ List<MockRequest> allRequests = newArrayList();
681883 try {
682884 cluster.init();
683885
@@ -691,7 +893,7 @@
691893 List<MockRequest> core0requests = newArrayList();
692894 for (int i = 0; i < 101; i++) {
693895 MockRequest request = MockRequest.send(pool);
694- assertThat(request.connection).isEqualTo(core0);
896+ assertThat(request.getConnection()).isEqualTo(core0);
695897 core0requests.add(request);
696898 }
697899
@@ -712,13 +914,15 @@
712914
713915 // Since core0 was closed, all of it's requests should have errored.
714916 for (MockRequest request : core0requests) {
715- verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt());
917+ assertThat(request.state.get()).isEqualTo(MockRequest.State.FAILED);
716918 }
717919
718920 assertThat(cluster).host(1).hasState(Host.State.UP);
719921
720922 // Create enough inFlight requests to fill connection.
721- requests.addAll(sendRequests(100, pool, singletonList(extra1)));
923+ List<MockRequest> requests = MockRequest.sendMany(100, pool);
924+ assertBorrowedConnections(requests, Collections.singletonList(extra1));
925+ allRequests.addAll(requests);
722926 assertThat(pool.connections).hasSize(1);
723927
724928 // A new connection should never have been spawned since we didn't max out core.
@@ -726,8 +930,8 @@
726930
727931 // Borrow another connection, since we exceed max another connection should be opened.
728932 MockRequest request = MockRequest.send(pool);
729- requests.add(request);
730- assertThat(request.connection).isEqualTo(extra1);
933+ allRequests.add(request);
934+ assertThat(request.getConnection()).isEqualTo(extra1);
731935
732936 // After some time the a connection should attempt to be opened (but will fail).
733937 verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
@@ -745,8 +949,8 @@
745949
746950 // Borrow another connection, since we exceed max another connection should be opened.
747951 request = MockRequest.send(pool);
748- requests.add(request);
749- assertThat(request.connection).isEqualTo(extra1);
952+ allRequests.add(request);
953+ assertThat(request.getConnection()).isEqualTo(extra1);
750954
751955 // Wait some reasonable amount of time for connection to reestablish then check pool size.
752956 Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
@@ -755,10 +959,10 @@
755959
756960 // Borrowed connection should be the newly spawned connection since the other one has some inflight requests.
757961 request = MockRequest.send(pool);
758- requests.add(request);
759- assertThat(request.connection).isNotEqualTo(core0).isNotEqualTo(extra1);
962+ allRequests.add(request);
963+ assertThat(request.getConnection()).isNotEqualTo(core0).isNotEqualTo(extra1);
760964 } finally {
761- completeRequests(requests);
965+ MockRequest.completeAll(allRequests);
762966 cluster.close();
763967 }
764968 }
@@ -781,7 +985,7 @@
781985 .setConnectTimeoutMillis(readTimeout)
782986 .setReadTimeoutMillis(reconnectInterval))
783987 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
784- List<MockRequest> requests = newArrayList();
988+ List<MockRequest> allRequests = newArrayList();
785989 try {
786990 cluster.init();
787991
@@ -811,13 +1015,13 @@
8111015 // we need to wait for connections to be established between requests for the pool
8121016 // to spawn new connections (since it only allows one simultaneous creation).
8131017 for (int i = 5; i <= 8; i++) {
814- requests.add(MockRequest.send(pool));
1018+ allRequests.add(MockRequest.send(pool));
8151019 verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
8161020 reset(factory);
8171021 assertPoolSize(pool, i);
8181022 }
8191023 } finally {
820- completeRequests(requests);
1024+ MockRequest.completeAll(allRequests);
8211025 cluster.close();
8221026 }
8231027 }
@@ -825,15 +1029,15 @@
8251029 /**
8261030 * Ensures that if all connections fail on pool init that the host and subsequently the
8271031 * control connection is not marked down since the control connection is still active.
828- * on the pool that a TimeoutException is yielded if we are still in the reconnection window
1032+ * The test also ensures that borrow attempts on the pool fail if we are still in the reconnection window
8291033 * according to the ConvictionPolicy.
8301034 *
8311035 * @jira_ticket JAVA-544
8321036 * @test_category connection:connection_pool
8331037 * @since 2.0.11
8341038 */
835- @Test(groups = "short", expectedExceptions = TimeoutException.class)
836- public void should_throw_exception_if_convicted_and_no_connections_available() throws Exception {
1039+ @Test(groups = "short")
1040+ public void should_throw_exception_if_convicted_and_no_connections_available() {
8371041 int readTimeout = 1000;
8381042 int reconnectInterval = 1000;
8391043 Cluster cluster = this.createClusterBuilder()
@@ -862,16 +1066,19 @@
8621066 assertThat(cluster).host(1).hasState(Host.State.UP);
8631067 assertThat(cluster).hasOpenControlConnection();
8641068
865- MockRequest.send(pool);
1069+ MockRequest failedBorrow = MockRequest.send(pool);
1070+ try {
1071+ failedBorrow.getConnection();
1072+ fail("Expected a BusyPoolException");
1073+ } catch (BusyPoolException e) { /*expected*/}
8661074 } finally {
8671075 cluster.close();
8681076 }
8691077 }
8701078
871-
8721079 /**
8731080 * Ensures that if all connections fail on pool init that the host and subsequently the
874- * control connection is not marked down. The test also ensures that when making requests
1081+ * control connection is not marked down. The test also ensures that when making requests
8751082 * on the pool after the conviction period that all core connections are created.
8761083 *
8771084 * @jira_ticket JAVA-544
@@ -912,12 +1119,13 @@
9121119 Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
9131120
9141121 reset(factory);
915- MockRequest request = MockRequest.send(pool);
916- request.simulateSuccessResponse();
1122+ MockRequest request = MockRequest.send(pool, 1);
9171123
9181124 // Should create up to core connections.
9191125 verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class));
9201126 assertPoolSize(pool, 8);
1127+
1128+ request.simulateSuccessResponse();
9211129 } finally {
9221130 cluster.close();
9231131 }
@@ -946,6 +1154,9 @@
9461154 cluster.init();
9471155 assertThat(cluster).hasOpenControlConnection();
9481156
1157+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
1158+ cluster.manager.connectionFactory = factory;
1159+
9491160 HostConnectionPool pool = createPool(cluster, 0, 2);
9501161
9511162 // Pool should be empty.
@@ -955,12 +1166,14 @@
9551166 assertThat(cluster).host(1).hasState(Host.State.UP);
9561167 assertThat(cluster).hasOpenControlConnection();
9571168
958- // Send a request, this should create a connection.
959- MockRequest request = MockRequest.send(pool);
960- request.simulateSuccessResponse();
1169+ reset(factory);
1170+ MockRequest request = MockRequest.send(pool, 1);
9611171
9621172 // Should create up to core connections.
1173+ verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class));
9631174 assertThat(pool.connections).hasSize(1);
1175+
1176+ request.simulateSuccessResponse();
9641177 } finally {
9651178 cluster.close();
9661179 }
@@ -979,10 +1192,10 @@
9791192 }
9801193
9811194 /**
982- * <p>
1195+ * <p/>
9831196 * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
9841197 * insertions are being executed, the number of opened connection is monitored.
985- * <p>
1198+ * <p/>
9861199 * If at anytime, the number of opened connections is negative, this test will fail.
9871200 *
9881201 * @jira_ticket JAVA-349
@@ -1061,51 +1274,115 @@
10611274
10621275 enum State {START, COMPLETED, FAILED, TIMED_OUT}
10631276
1064- final Connection connection;
1065- private Connection.ResponseHandler responseHandler;
1277+ final ListenableFuture<Connection> connectionFuture;
1278+ private volatile Connection.ResponseHandler responseHandler;
1279+
1280+ final AtomicReference<State> state = new AtomicReference<State>(State.START);
1281+
1282+ static MockRequest send(HostConnectionPool pool) {
1283+ return send(pool, 0);
1284+ }
1285+
1286+ static MockRequest send(HostConnectionPool pool, int maxQueueSize) throws ConnectionException, BusyConnectionException {
1287+ return new MockRequest(pool, maxQueueSize);
1288+ }
1289+
1290+ private static List<MockRequest> sendMany(int count, HostConnectionPool pool) throws ConnectionException {
1291+ return sendMany(count, pool, 0);
1292+ }
1293+
1294+ private static List<MockRequest> sendMany(int count, HostConnectionPool pool, int maxQueueSize) throws ConnectionException {
1295+ List<MockRequest> requests = newArrayList();
1296+ for (int i = 0; i < count; i++) {
1297+ MockRequest request = send(pool, maxQueueSize);
1298+ requests.add(request);
1299+ }
1300+ return requests;
1301+ }
10661302
1067- private final AtomicReference<State> state = new AtomicReference<State>(State.START);
1303+ /**
1304+ * Completes count requests by simulating a successful response.
1305+ */
1306+ private static void completeMany(int count, List<MockRequest> requests) {
1307+ Iterator<MockRequest> requestIt = requests.iterator();
1308+ for (int i = 0; i < count; i++) {
1309+ if (requestIt.hasNext()) {
1310+ MockRequest request = requestIt.next();
1311+ request.simulateSuccessResponse();
1312+ requestIt.remove();
1313+ } else {
1314+ break;
1315+ }
1316+ }
1317+ }
10681318
1069- static MockRequest send(HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
1070- // Create a MockRequest and spy on it. Create a response handler and add it to the connection's dispatcher.
1071- MockRequest request = spy(new MockRequest(pool));
1072- request.responseHandler = new Connection.ResponseHandler(request.connection, -1, request);
1073- request.connection.dispatcher.add(request.responseHandler);
1074- return request;
1319+ /**
1320+ * Completes all requests by simulating a successful response.
1321+ */
1322+ private static void completeAll(List<MockRequest> requests) {
1323+ for (MockRequest request : requests) {
1324+ request.simulateSuccessResponse();
1325+ }
10751326 }
10761327
1077- private MockRequest(HostConnectionPool pool) throws ConnectionException, TimeoutException, BusyConnectionException {
1078- connection = pool.borrowConnection(500, TimeUnit.MILLISECONDS);
1328+ private MockRequest(HostConnectionPool pool, int maxQueueSize) throws ConnectionException {
1329+ this.connectionFuture = pool.borrowConnection(maxQueueSize);
1330+ Futures.addCallback(this.connectionFuture, new MoreFutures.SuccessCallback<Connection>() {
1331+ @Override
1332+ public void onSuccess(Connection connection) {
1333+ MockRequest thisRequest = MockRequest.this;
1334+ thisRequest.responseHandler = new Connection.ResponseHandler(connection, -1, thisRequest);
1335+ connection.dispatcher.add(thisRequest.responseHandler);
1336+ }
1337+ });
10791338 }
10801339
10811340 void simulateSuccessResponse() {
1082- onSet(connection, null, 0, 0);
1341+ onSet(getConnection(), null, 0, 0);
10831342 }
10841343
10851344 @SuppressWarnings("unused")
10861345 void simulateErrorResponse() {
1087- onException(connection, null, 0, 0);
1346+ onException(getConnection(), null, 0, 0);
10881347 }
10891348
10901349 @SuppressWarnings("unused")
10911350 void simulateTimeout() {
1092- if (onTimeout(connection, 0, 0))
1351+ if (onTimeout(getConnection(), 0, 0))
10931352 responseHandler.cancelHandler();
10941353 }
10951354
1355+ // Get the connection, assuming pool acquisition completed
1356+ Connection getConnection() {
1357+ try {
1358+ if (!connectionFuture.isDone()) {
1359+ throw new AssertionError("Borrow call did not complete");
1360+ }
1361+ return Uninterruptibles.getUninterruptibly(connectionFuture);
1362+ } catch (ExecutionException e) {
1363+ throw Throwables.propagate(e.getCause());
1364+ }
1365+ }
1366+
10961367 @Override
10971368 public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
1369+ assertThat(connectionFuture.isDone()).isTrue();
1370+ try {
1371+ assertThat(Uninterruptibles.getUninterruptibly(connectionFuture)).isNotNull();
1372+ } catch (ExecutionException e) {
1373+ Throwables.propagate(e.getCause());
1374+ }
10981375 if (state.compareAndSet(State.START, State.COMPLETED)) {
1099- connection.release();
11001376 connection.dispatcher.removeHandler(responseHandler, true);
1377+ connection.release();
11011378 }
11021379 }
11031380
11041381 @Override
11051382 public void onException(Connection connection, Exception exception, long latency, int retryCount) {
11061383 if (state.compareAndSet(State.START, State.FAILED)) {
1107- connection.release();
11081384 connection.dispatcher.removeHandler(responseHandler, true);
1385+ connection.release();
11091386 }
11101387 }
11111388
modified driver-core/src/test/java/com/datastax/driver/core/ParseUtilsTest.java +45 −0
@@ -43,6 +43,9 @@
4343 assertThat(ParseUtils.unquote("'foo'")).isEqualTo("foo");
4444 assertThat(ParseUtils.unquote(" 'foo' ")).isEqualTo(" 'foo' "); // considered unquoted
4545 assertThat(ParseUtils.unquote("'''foo'''")).isEqualTo("'foo'");
46+ assertThat(ParseUtils.unquote("'''")).isEqualTo("'");
47+ assertThat(ParseUtils.unquote("''foo'")).isEqualTo("'foo");
48+ assertThat(ParseUtils.unquote("'foo''")).isEqualTo("foo'");
4649 }
4750
4851 @Test(groups = "unit")
@@ -60,4 +63,46 @@
6063 assertThat(ParseUtils.isQuoted("'''foo'''")).isTrue();
6164 }
6265
66+ @Test(groups = "unit")
67+ public void testDoubleQuote() {
68+ assertThat(ParseUtils.doubleQuote(null)).isEqualTo("\"\"");
69+ assertThat(ParseUtils.doubleQuote("")).isEqualTo("\"\"");
70+ assertThat(ParseUtils.doubleQuote(" ")).isEqualTo("\" \"");
71+ assertThat(ParseUtils.doubleQuote("foo")).isEqualTo("\"foo\"");
72+ assertThat(ParseUtils.doubleQuote(" \"foo\" ")).isEqualTo("\" \"\"foo\"\" \"");
73+ }
74+
75+ @Test(groups = "unit")
76+ public void testDoubleUnquote() {
77+ assertThat(ParseUtils.unDoubleQuote(null)).isNull();
78+ assertThat(ParseUtils.unDoubleQuote("")).isEqualTo("");
79+ assertThat(ParseUtils.unDoubleQuote(" ")).isEqualTo(" ");
80+ assertThat(ParseUtils.unDoubleQuote("\"")).isEqualTo("\""); // malformed string left untouched
81+ assertThat(ParseUtils.unDoubleQuote("foo")).isEqualTo("foo");
82+ assertThat(ParseUtils.unDoubleQuote("\"\"")).isEqualTo("");
83+ assertThat(ParseUtils.unDoubleQuote("\" \"")).isEqualTo(" ");
84+ assertThat(ParseUtils.unDoubleQuote("\"foo")).isEqualTo("\"foo"); // malformed string left untouched
85+ assertThat(ParseUtils.unDoubleQuote("\"foo\"")).isEqualTo("foo");
86+ assertThat(ParseUtils.unDoubleQuote(" \"foo\" ")).isEqualTo(" \"foo\" "); // considered unquoted
87+ assertThat(ParseUtils.unDoubleQuote("\"\"\"foo\"\"\"")).isEqualTo("\"foo\"");
88+ assertThat(ParseUtils.unDoubleQuote("\"\"\"")).isEqualTo("\"");
89+ assertThat(ParseUtils.unDoubleQuote("\"\"foo\"")).isEqualTo("\"foo");
90+ assertThat(ParseUtils.unDoubleQuote("\"foo\"\"")).isEqualTo("foo\"");
91+ }
92+
93+ @Test(groups = "unit")
94+ public void testIsDoubleQuoted() {
95+ assertThat(ParseUtils.isDoubleQuoted(null)).isFalse();
96+ assertThat(ParseUtils.isDoubleQuoted("")).isFalse();
97+ assertThat(ParseUtils.isDoubleQuoted(" ")).isFalse();
98+ assertThat(ParseUtils.isDoubleQuoted("\"")).isFalse(); // malformed string considered unquoted
99+ assertThat(ParseUtils.isDoubleQuoted("foo")).isFalse();
100+ assertThat(ParseUtils.isDoubleQuoted("\"\"")).isTrue();
101+ assertThat(ParseUtils.isDoubleQuoted("\" \"")).isTrue();
102+ assertThat(ParseUtils.isDoubleQuoted("\"foo")).isFalse(); // malformed string considered unquoted
103+ assertThat(ParseUtils.isDoubleQuoted("\"foo\"")).isTrue();
104+ assertThat(ParseUtils.isDoubleQuoted(" \"foo\" ")).isFalse(); // considered unquoted
105+ assertThat(ParseUtils.isDoubleQuoted("\"\"\"foo\"\"\"")).isTrue();
106+ }
107+
63108 }
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +6 −2
@@ -106,15 +106,19 @@
106106 ccm().start(1);
107107 ccm().waitForUp(1);
108108
109- // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least once
109+ // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least twice
110110 // NB: authentication errors show up in the logs
111111 int initialCount = authProvider.count.get();
112+ long initialMetricCount = cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount();
112113 int iterations = 0, maxIterations = 12; // make sure we don't wait indefinitely
113114 do {
114115 iterations += 1;
115116 TimeUnit.SECONDS.sleep(5);
116- } while (iterations < maxIterations && authProvider.count.get() <= initialCount);
117+ } while (iterations < maxIterations && authProvider.count.get() <= initialCount + 1);
117118 assertThat(iterations).isLessThan(maxIterations);
119+ // Number of authentication errors should have increased.
120+ assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount())
121+ .isGreaterThan(initialMetricCount);
118122
119123 // Fix the credentials
120124 authProvider.setPassword("cassandra");
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +1 −52
@@ -16,7 +16,6 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.SyntaxError;
19-import com.datastax.driver.core.utils.CassandraVersion;
2019 import com.google.common.util.concurrent.ListenableFuture;
2120 import org.testng.annotations.Test;
2221
@@ -81,7 +80,7 @@
8180 checkExecuteResultSet(session().executeAsync(bs.setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
8281 }
8382
84- private static void checkExecuteResultSet(ResultSet rs, String key) {
83+ static void checkExecuteResultSet(ResultSet rs, String key) {
8584 assertThat(rs.isExhausted()).isFalse();
8685 Row row = rs.one();
8786 assertThat(rs.isExhausted()).isTrue();
@@ -104,56 +103,6 @@
104103 assertThat(rows.get(0).getLong("c")).isEqualTo(2L);
105104 }
106105
107- /**
108- * Validates that a session can be established using snappy compression and executes some queries that inserts and
109- * retrieves data using that session().
110- *
111- * @test_category connection:compression
112- * @expected_result session established and queries made successfully using it.
113- */
114- @Test(groups = "short")
115- public void should_function_with_snappy_compression() throws Exception {
116- compressionTest(ProtocolOptions.Compression.SNAPPY);
117- }
118-
119- /**
120- * Validates that a session can be established using lz4 compression and executes some queries that inserts and
121- * retrieves data using that session().
122- *
123- * @test_category connection:compression
124- * @expected_result session established and queries made successfully using it.
125- */
126- @Test(groups = "short")
127- @CassandraVersion(major = 2.0)
128- public void should_function_with_lz4_compression() throws Exception {
129- compressionTest(ProtocolOptions.Compression.LZ4);
130- }
131-
132- public void compressionTest(ProtocolOptions.Compression compression) {
133- cluster().getConfiguration().getProtocolOptions().setCompression(compression);
134- try {
135- Session compressedSession = cluster().connect(keyspace);
136-
137- // Simple calls to all versions of the execute/executeAsync methods
138- String key = "execute_compressed_test_" + compression;
139- ResultSet rs = compressedSession.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE3, key, "foo", 42, 24.03f));
140- assertThat(rs.isExhausted()).isTrue();
141-
142- String SELECT_ALL = String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = '%s'", TABLE3, key);
143-
144- // execute
145- checkExecuteResultSet(compressedSession.execute(SELECT_ALL), key);
146- checkExecuteResultSet(compressedSession.execute(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key);
147-
148- // executeAsync
149- checkExecuteResultSet(compressedSession.executeAsync(SELECT_ALL).getUninterruptibly(), key);
150- checkExecuteResultSet(compressedSession.executeAsync(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
151-
152- } finally {
153- cluster().getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.NONE);
154- }
155- }
156-
157106 /**
158107 * Checks for deadlocks when a session shutdown races with the initialization of the cluster (JAVA-418).
159108 */
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +1 −1
@@ -729,7 +729,7 @@
729729 try {
730730 socket.close();
731731 } catch (IOException e) {
732- logger.warn("Error closing socket to " + address);
732+ logger.warn("Error closing socket to " + address, e);
733733 }
734734 }
735735 return connectionSuccessful;
added driver-core/src/test/java/com/datastax/driver/core/querybuilder/BatchIdempotencyTest.java +47 −0
@@ -0,0 +1,47 @@
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+package com.datastax.driver.core.querybuilder;
17+
18+import com.datastax.driver.core.AbstractBatchIdempotencyTest;
19+import com.datastax.driver.core.RegularStatement;
20+
21+public class BatchIdempotencyTest extends AbstractBatchIdempotencyTest {
22+
23+ @Override
24+ protected AbstractBatchIdempotencyTest.TestBatch createBatch() {
25+ return new TestBatchWrapper();
26+ }
27+
28+ static class TestBatchWrapper implements TestBatch {
29+
30+ private final Batch batch = QueryBuilder.batch();
31+
32+ @Override
33+ public void add(RegularStatement statement) {
34+ batch.add(statement);
35+ }
36+
37+ @Override
38+ public Boolean isIdempotent() {
39+ return batch.isIdempotent();
40+ }
41+
42+ @Override
43+ public void setIdempotent(boolean idempotent) {
44+ batch.setIdempotent(idempotent);
45+ }
46+ }
47+}
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +64 −1
@@ -23,17 +23,22 @@
2323 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2424 import static org.testng.Assert.assertEquals;
2525 import static org.testng.Assert.assertNotNull;
26+import static org.testng.Assert.assertNull;
2627
2728 @CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing")
2829 public class QueryBuilderRoutingKeyTest extends CCMTestsSupport {
2930
3031 private static final String TABLE_TEXT = "test_text";
3132 private static final String TABLE_INT = "test_int";
33+ private static final String TABLE_CASE = "test_case";
34+ private static final String TABLE_CASE_QUOTED = "test_case_quoted";
3235
3336 @Override
3437 public void onTestContextInitialized() {
3538 execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT),
36- String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
39+ String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT),
40+ String.format("CREATE TABLE %s (theKey int PRIMARY KEY, a int, b int)", TABLE_CASE),
41+ String.format("CREATE TABLE %s (\"theKey\" int PRIMARY KEY, a int, b int, \"tHEkEY\" int)", TABLE_CASE_QUOTED));
3742 }
3843
3944 @Test(groups = "short")
@@ -58,6 +63,64 @@
5863 assertEquals(row.getInt("b"), 2);
5964 }
6065
66+ @Test(groups = "short")
67+ public void routingKeyColumnCaseSensitivityTest() throws Exception {
68+
69+ BuiltStatement query;
70+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_CASE);
71+ assertNotNull(table);
72+ ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
73+ CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
74+
75+ query = insertInto(table).values(new String[]{"theKey", "a", "b"}, new Object[]{42, 1, 2});
76+ ByteBuffer bb = ByteBuffer.allocate(4);
77+ bb.putInt(0, 42);
78+ assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb);
79+ session().execute(query);
80+
81+ query = select().from(table).where(eq("theKey", 42));
82+ assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb);
83+ Row row = session().execute(query).one();
84+ assertEquals(row.getInt("theKey"), 42);
85+ assertEquals(row.getInt("a"), 1);
86+ assertEquals(row.getInt("b"), 2);
87+
88+ query = insertInto(table).values(new String[]{"ThEkEy", "a", "b"}, new Object[]{42, 1, 2});
89+ bb = ByteBuffer.allocate(4);
90+ bb.putInt(0, 42);
91+ assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb);
92+ session().execute(query);
93+
94+ query = select().from(table).where(eq("ThEkEy", 42));
95+ assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb);
96+ row = session().execute(query).one();
97+ assertEquals(row.getInt("theKey"), 42);
98+ assertEquals(row.getInt("a"), 1);
99+ assertEquals(row.getInt("b"), 2);
100+ }
101+
102+ @Test(groups = "short")
103+ public void routingKeyColumnCaseSensitivityForQuotedIdentifiersTest() throws Exception {
104+
105+ BuiltStatement query;
106+ TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_CASE_QUOTED);
107+ assertNotNull(table);
108+ ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion();
109+ CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
110+
111+ query = insertInto(table).values(new String[]{"\"theKey\"", "a", "b", "\"tHEkEY\""}, new Object[]{42, 1, 2, 3});
112+ ByteBuffer bb = ByteBuffer.allocate(4);
113+ bb.putInt(0, 42);
114+ assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb);
115+
116+ query = insertInto(table).values(new String[]{"theKey", "a", "b", "\"tHEkEY\""}, new Object[]{42, 1, 2, 3});
117+ assertNull(query.getRoutingKey(protocolVersion, codecRegistry));
118+
119+ query = insertInto(table).values(new String[]{"theKey", "a", "b", "theKey"}, new Object[]{42, 1, 2, 3});
120+ assertNull(query.getRoutingKey(protocolVersion, codecRegistry));
121+
122+ }
123+
61124 @Test(groups = "short")
62125 public void intRoutingKeyTest() throws Exception {
63126
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +62 −9
@@ -726,16 +726,11 @@
726726 assertTrue(query.isTracing());
727727 }
728728
729- @Test(groups = "unit")
729+ @Test(groups = "unit", expectedExceptions = CodecNotFoundException.class)
730730 public void rejectUnknownValueTest() throws Exception {
731- try {
732- RegularStatement s = update("foo").with(set("a", new byte[13])).where(eq("k", 2))
733- .setForceNoValues(true);
734- s.getQueryString();
735- fail("should have failed to inline a byte[]");
736- } catch (CodecNotFoundException e) {
737- // Ok, that's what we expect
738- }
731+ RegularStatement s = update("foo").with(set("a", new byte[13])).where(eq("k", 2))
732+ .setForceNoValues(true);
733+ s.getQueryString();
739734 }
740735
741736 @Test(groups = "unit")
@@ -1102,5 +1097,63 @@
11021097 .isEqualTo("INSERT INTO users (id) VALUES (fromJson(:id));");
11031098 }
11041099
1100+ static class Foo {
1101+ int bar;
1102+
1103+ public Foo(int bar) {
1104+ this.bar = bar;
1105+ }
1106+ }
1107+
1108+ static class FooCodec extends TypeCodec<Foo> {
1109+
1110+ public FooCodec() {
1111+ super(DataType.cint(), Foo.class);
1112+ }
1113+
1114+ @Override
1115+ public ByteBuffer serialize(Foo value, ProtocolVersion protocolVersion) throws InvalidTypeException {
1116+ // not relevant for this test
1117+ return null;
1118+ }
1119+
1120+ @Override
1121+ public Foo deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
1122+ // not relevant for this test
1123+ return null;
1124+ }
1125+
1126+ @Override
1127+ public Foo parse(String value) throws InvalidTypeException {
1128+ // not relevant for this test
1129+ return null;
1130+ }
1131+
1132+ @Override
1133+ public String format(Foo foo) throws InvalidTypeException {
1134+ return Integer.toString(foo.bar);
1135+ }
1136+ }
1137+
1138+ /**
1139+ * Ensures that a statement can be printed with and without
1140+ * a required custom codec.
1141+ * The expectation is that if the codec is not registered,
1142+ * then the query string should contain bind markers for all variables;
1143+ * if however all codecs are properly registered, then
1144+ * the query string should contain all variables inlined and formatted properly.
1145+ *
1146+ * @jira_ticket JAVA-1272
1147+ */
1148+ @Test(groups = "unit")
1149+ public void should_inline_custom_codec() throws Exception {
1150+ assertThat(
1151+ insertInto("users").value("id", new Foo(42)).toString())
1152+ .isEqualTo("INSERT INTO users (id) VALUES (?);");
1153+ CodecRegistry.DEFAULT_INSTANCE.register(new FooCodec());
1154+ assertThat(
1155+ insertInto("users").value("id", new Foo(42)).toString())
1156+ .isEqualTo("INSERT INTO users (id) VALUES (42);");
1157+ }
11051158
11061159 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +17 −10
@@ -15,11 +15,7 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.ConsistencyLevel;
19-import com.datastax.driver.core.Metadata;
20-import com.datastax.driver.core.TableMetadata;
21-import com.datastax.driver.core.TypeCodec;
22-import com.datastax.driver.core.UserType;
18+import com.datastax.driver.core.*;
2319 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
2420 import com.datastax.driver.mapping.annotations.*;
2521 import com.google.common.base.Strings;
@@ -95,11 +91,18 @@
9591 ksName = Metadata.quote(loggedKeyspace);
9692 }
9793
98- EntityMapper<T> mapper = new EntityMapper<T>(entityClass, ksName, tableName, writeConsistency, readConsistency);
99- TableMetadata tableMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getTable(tableName);
94+ KeyspaceMetadata keyspaceMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName);
95+ if (keyspaceMetadata == null)
96+ throw new IllegalArgumentException(String.format("Keyspace %s does not exist", ksName));
97+
98+ AbstractTableMetadata tableMetadata = keyspaceMetadata.getTable(tableName);
99+ if (tableMetadata == null) {
100+ tableMetadata = keyspaceMetadata.getMaterializedView(tableName);
101+ if (tableMetadata == null)
102+ throw new IllegalArgumentException(String.format("Table or materialized view %s does not exist in keyspace %s", tableName, ksName));
103+ }
100104
101- if (tableMetadata == null)
102- throw new IllegalArgumentException(String.format("Table %s does not exist in keyspace %s", tableName, ksName));
105+ EntityMapper<T> mapper = new EntityMapper<T>(entityClass, ksName, tableName, writeConsistency, readConsistency);
103106
104107 List<PropertyMapper> pks = new ArrayList<PropertyMapper>();
105108 List<PropertyMapper> ccs = new ArrayList<PropertyMapper>();
@@ -169,7 +172,11 @@
169172 ksName = Metadata.quote(loggedKeyspace);
170173 }
171174
172- UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName);
175+ KeyspaceMetadata keyspaceMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName);
176+ if (keyspaceMetadata == null)
177+ throw new IllegalArgumentException(String.format("Keyspace %s does not exist", ksName));
178+
179+ UserType userType = keyspaceMetadata.getUserType(udtName);
173180 if (userType == null)
174181 throw new IllegalArgumentException(String.format("User type %s does not exist in keyspace %s", udtName, ksName));
175182
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +16 −4
@@ -79,13 +79,25 @@
7979
8080 @Override
8181 protected String formatField(T source, String fieldName) {
82- // This codec implementation is internal-use only, and its format method is never used
83- throw new UnsupportedOperationException();
82+ PropertyMapper propertyMapper = columnMappers.get(fieldName);
83+ if (propertyMapper == null)
84+ return null;
85+ Object value = propertyMapper.getValue(source);
86+ TypeCodec<Object> codec = propertyMapper.customCodec;
87+ if (codec == null)
88+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType);
89+ return codec.format(value);
8490 }
8591
8692 @Override
8793 protected T parseAndSetField(String input, T target, String fieldName) {
88- // This codec implementation is internal-use only, and its parse method is never used
89- throw new UnsupportedOperationException();
94+ PropertyMapper propertyMapper = columnMappers.get(fieldName);
95+ if (propertyMapper != null) {
96+ TypeCodec<Object> codec = propertyMapper.customCodec;
97+ if (codec == null)
98+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType);
99+ propertyMapper.setValue(target, codec.parse(input));
100+ }
101+ return target;
90102 }
91103 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +4 −1
@@ -113,7 +113,7 @@
113113 if (old != null) {
114114 return old;
115115 } else {
116- String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values());
116+ final String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values());
117117 logger.debug("Preparing query {}", queryString);
118118 SimpleStatement s = new SimpleStatement(queryString);
119119 // all queries generated by the mapper are idempotent
@@ -127,6 +127,9 @@
127127 @Override
128128 public void onFailure(Throwable t) {
129129 future.setException(t);
130+ // do not keep a failed future in the query cache
131+ preparedQueries.remove(pqk, future);
132+ logger.error("Query preparation failed: " + queryString, t);
130133 }
131134 });
132135 return future;
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperMaterializedViewTest.java +158 −6
@@ -17,10 +17,7 @@
1717
1818 import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.utils.CassandraVersion;
20-import com.datastax.driver.mapping.annotations.Accessor;
21-import com.datastax.driver.mapping.annotations.Param;
22-import com.datastax.driver.mapping.annotations.Query;
23-import com.datastax.driver.mapping.annotations.Table;
20+import com.datastax.driver.mapping.annotations.*;
2421 import org.testng.annotations.BeforeMethod;
2522 import org.testng.annotations.Test;
2623
@@ -32,7 +29,6 @@
3229 @CassandraVersion(major = 3.0)
3330 public class MapperMaterializedViewTest extends CCMTestsSupport {
3431
35-
3632 @Override
3733 public void onTestContextInitialized() {
3834 // Example schema taken from: http://www.datastax.com/dev/blog/new-in-cassandra-3-0-materialized-views
@@ -73,11 +69,28 @@
7369 );
7470 }
7571
72+
73+ private Mapper<AllTimeHigh> mapper;
74+
7675 private ScoreAccessor accessor;
7776
7877 @BeforeMethod(groups = "short")
7978 public void setUp() {
80- accessor = new MappingManager(session()).createAccessor(ScoreAccessor.class);
79+ MappingManager mappingManager = new MappingManager(session());
80+ mapper = mappingManager.mapper(AllTimeHigh.class);
81+ accessor = mappingManager.createAccessor(ScoreAccessor.class);
82+ }
83+
84+ /**
85+ * Validates that a materialized view can be mapped as a regular table.
86+ *
87+ * @test_category materialized_view, mapper
88+ * @jira_ticket JAVA-1258
89+ */
90+ @Test(groups = "short")
91+ public void should_access_mapped_materialized_view() {
92+ AllTimeHigh allTimeHigh = mapper.get("Coup", 4000, "pcmanus", 2015, 5, 1);
93+ assertThat(allTimeHigh).isNotNull();
8194 }
8295
8396 /**
@@ -159,14 +172,22 @@
159172
160173 @Table(name = "scores")
161174 public static class Score {
175+
176+ //primary key: user, game, year, month, day
177+
178+ @PartitionKey
162179 String user;
163180
181+ @ClusteringColumn(0)
164182 String game;
165183
184+ @ClusteringColumn(1)
166185 int year;
167186
187+ @ClusteringColumn(2)
168188 int month;
169189
190+ @ClusteringColumn(3)
170191 int day;
171192
172193 int score;
@@ -277,4 +298,135 @@
277298 return result;
278299 }
279300 }
301+
302+ @Table(name = "alltimehigh")
303+ public static class AllTimeHigh {
304+
305+ //primary key: game, score, user, year, month, day
306+
307+ @PartitionKey
308+ String game;
309+
310+ @ClusteringColumn(0)
311+ int score;
312+
313+ @ClusteringColumn(1)
314+ String user;
315+
316+ @ClusteringColumn(2)
317+ int year;
318+
319+ @ClusteringColumn(3)
320+ int month;
321+
322+ @ClusteringColumn(4)
323+ int day;
324+
325+ public AllTimeHigh() {
326+ }
327+
328+ public AllTimeHigh(String user, String game, int year, int month, int day, int score) {
329+ this.user = user;
330+ this.game = game;
331+ this.year = year;
332+ this.month = month;
333+ this.day = day;
334+ this.score = score;
335+ }
336+
337+ public String getUser() {
338+ return user;
339+ }
340+
341+ public void setUser(String user) {
342+ this.user = user;
343+ }
344+
345+ public String getGame() {
346+ return game;
347+ }
348+
349+ public void setGame(String game) {
350+ this.game = game;
351+ }
352+
353+ public int getYear() {
354+ return year;
355+ }
356+
357+ public void setYear(int year) {
358+ this.year = year;
359+ }
360+
361+ public int getMonth() {
362+ return month;
363+ }
364+
365+ public void setMonth(int month) {
366+ this.month = month;
367+ }
368+
369+ public int getDay() {
370+ return day;
371+ }
372+
373+ public void setDay(int day) {
374+ this.day = day;
375+ }
376+
377+ public int getScore() {
378+ return score;
379+ }
380+
381+ public void setScore(int score) {
382+ this.score = score;
383+ }
384+
385+ @Override
386+ public String toString() {
387+ return "AllTimeHigh{" +
388+ "user='" + user + '\'' +
389+ ", game='" + game + '\'' +
390+ ", year=" + year +
391+ ", month=" + month +
392+ ", day=" + day +
393+ ", score=" + score +
394+ '}';
395+ }
396+
397+ @SuppressWarnings("SimplifiableIfStatement")
398+ @Override
399+ public boolean equals(Object o) {
400+ if (this == o)
401+ return true;
402+ if (!(o instanceof Score))
403+ return false;
404+
405+ Score score1 = (Score) o;
406+
407+ if (year != score1.year)
408+ return false;
409+ if (month != score1.month)
410+ return false;
411+ if (day != score1.day)
412+ return false;
413+ if (score != score1.score)
414+ return false;
415+ if (!user.equals(score1.user))
416+ return false;
417+ return game.equals(score1.game);
418+ }
419+
420+ @Override
421+ public int hashCode() {
422+ int result = user.hashCode();
423+ result = 31 * result + game.hashCode();
424+ result = 31 * result + year;
425+ result = 31 * result + month;
426+ result = 31 * result + day;
427+ result = 31 * result + score;
428+ return result;
429+ }
430+
431+ }
280432 }
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperReconnectionTest.java +80 −0
@@ -0,0 +1,80 @@
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+package com.datastax.driver.mapping;
17+
18+import com.datastax.driver.core.CCMConfig;
19+import com.datastax.driver.core.CCMTestsSupport;
20+import com.datastax.driver.core.Cluster;
21+import com.datastax.driver.core.CreateCCM;
22+import com.datastax.driver.core.exceptions.NoHostAvailableException;
23+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
24+import org.testng.annotations.Test;
25+
26+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
27+import static com.datastax.driver.core.TestUtils.*;
28+import static com.datastax.driver.mapping.MapperTest.User;
29+import static org.testng.Assert.fail;
30+
31+@CreateCCM(PER_METHOD)
32+@CCMConfig(dirtiesContext = true)
33+public class MapperReconnectionTest extends CCMTestsSupport {
34+
35+ @Override
36+ public Cluster.Builder createClusterBuilder() {
37+ return super.createClusterBuilder().withReconnectionPolicy(new ConstantReconnectionPolicy(1000));
38+ }
39+
40+ @Override
41+ public void onTestContextInitialized() {
42+ execute("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)");
43+ }
44+
45+ /**
46+ * Ensures that when the driver looses connectivity,
47+ * if a mapper query preparation is attempted in the meanwhile,
48+ * the failed future will not be kept in cache, so that when
49+ * connectivity comes back again,
50+ * the same query preparation can be reattempted.
51+ *
52+ * @jira_ticket JAVA-1283
53+ * @test_category object_mapper
54+ */
55+ @Test(groups = "long")
56+ public void should_not_keep_failed_future_in_query_cache() throws Exception {
57+ MappingManager manager = new MappingManager(session());
58+ Mapper<User> m = manager.mapper(User.class);
59+ User u1 = new User("Paul", "paul@gmail.com");
60+ m.save(u1);
61+ ccm().stop(1);
62+ ccm().waitForDown(1);
63+ waitForDown(ipOfNode(1), cluster());
64+ try {
65+ m.get(u1.getUserId());
66+ fail("Should have thrown NoHostAvailableException");
67+ } catch (NoHostAvailableException e) {
68+ // ok
69+ }
70+ ccm().start(1);
71+ ccm().waitForUp(1);
72+ waitForUp(ipOfNode(1), cluster());
73+ try {
74+ m.get(u1.getUserId());
75+ } catch (NoHostAvailableException e) {
76+ fail("Should not have thrown NoHostAvailableException");
77+ }
78+ }
79+
80+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +46 −1
@@ -18,6 +18,7 @@
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.CodecNotFoundException;
2020 import com.datastax.driver.core.exceptions.InvalidQueryException;
21+import com.datastax.driver.core.querybuilder.BuiltStatement;
2122 import com.datastax.driver.core.utils.CassandraVersion;
2223 import com.datastax.driver.core.utils.UUIDs;
2324 import com.datastax.driver.mapping.annotations.*;
@@ -31,6 +32,7 @@
3132 import java.util.*;
3233
3334 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3436 import static org.assertj.core.api.Assertions.assertThat;
3537 import static org.assertj.core.api.Assertions.fail;
3638 import static org.testng.Assert.*;
@@ -471,7 +473,7 @@
471473 manager.mapper(User.class);
472474 fail("Expected IllegalArgumentException");
473475 } catch (IllegalArgumentException e) {
474- assertThat(e.getMessage()).isEqualTo("Table users does not exist in keyspace \"" + keyspace + "\"");
476+ assertThat(e.getMessage()).isEqualTo("Table or materialized view users does not exist in keyspace \"" + keyspace + "\"");
475477 }
476478 }
477479
@@ -728,4 +730,47 @@
728730 manager.mapper(UserWithAddressUnknownField.class);
729731 }
730732
733+ /**
734+ * Ensures that MappedUDTCodec is able to properly format UDTs when printing the query string of a BuiltStatement.
735+ *
736+ * @jira_ticket JAVA-1272
737+ * @test_category object_mapper
738+ */
739+ @Test(groups = "short")
740+ public void should_format_mapped_udt() throws Exception {
741+ MappingManager manager = new MappingManager(session());
742+ UUID uuid = UUIDs.random();
743+ BuiltStatement update =
744+ update("users")
745+ .with(set("mainaddress", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245")))
746+ .where(eq("user_id", uuid));
747+ CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry();
748+ codecRegistry.register(manager.udtCodec(Address.class));
749+ String queryString = update.getQueryString(codecRegistry);
750+ assertThat(queryString)
751+ .isEqualTo("UPDATE users SET mainaddress=? WHERE user_id=?;");
752+ update.setForceNoValues(true);
753+ queryString = update.getQueryString(codecRegistry);
754+ assertThat(queryString).isEqualTo(
755+ "UPDATE users " +
756+ "SET mainaddress={street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}} " +
757+ "WHERE user_id=" + uuid + ";");
758+ // check that the query string is valid
759+ session().execute(queryString);
760+ }
761+
762+ /**
763+ * Ensures that MappedUDTCodec is able to properly parse UDTs.
764+ *
765+ * @jira_ticket JAVA-1272
766+ * @test_category object_mapper
767+ */
768+ @Test(groups = "short")
769+ public void should_parse_mapped_udt() throws Exception {
770+ MappingManager manager = new MappingManager(session());
771+ TypeCodec<Address> codec = manager.udtCodec(Address.class);
772+ Address actual = codec.parse("{street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}}");
773+ assertThat(actual).isEqualTo(new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"));
774+ }
775+
731776 }
modified faq/README.md +58 −1
@@ -157,9 +157,66 @@
157157
158158 See [Blobs.java] in the `driver-examples` module for some examples and explanations.
159159
160-[Blobs.java]: https://github.com/datastax/java-driver/tree/3.0/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java
160+[Blobs.java]: https://github.com/datastax/java-driver/tree/3.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java
161161
162162
163163 ### How do I use the driver in an OSGi application?
164164
165165 Read our [OSGi-specific FAQ section](osgi/) to find out.
166+
167+
168+### Why am I seeing messages about `tombstone_warn_threshold` or `tombstone_fail_threshold` being exceeded in my Cassandra logs?
169+
170+Applications which use the object mapper or set `null` values in their
171+statements may observe that many tombstones are being stored in their tables
172+which subsequently may lead to poor query performance, failed queries, or
173+columns being mysteriously deleted.
174+
175+This is caused by INSERT/UPDATE statements containing `null` values for columns
176+that a user does not intend to change. Common circumstances around this come
177+from using the object mapper or writing your own persistence layer and
178+attempting to reuse the same `PreparedStatement` for inserting data, even with
179+partial updates.
180+
181+Prior to cassandra 2.2, there was no means of reusing the same
182+`PreparedStatement` for making partial updates to different columns.
183+
184+For example, given the following code:
185+
186+```java
187+PreparedStatement prepared = session.prepare("INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)");
188+BoundStatement bound = prepared.bind();
189+bound.set("email", "clint.barton@hawkeye.com");
190+bound.set("firstname", "Barney");
191+// creates a tombstone!!
192+bound.set("lastname", null);
193+```
194+
195+If one wanted to use this query to update only `firstname` this would not
196+be achievable without binding the `lastname` parameter to `null`. This would
197+have an undesired side effect of creating a tombstone for `lastname` and thus
198+to the user giving the impression that `lastname` was deleted.
199+
200+In cassandra 2.2 and later with protocol v4, bind parameters (`?`) can
201+optionally be left unset
202+([CASSANDRA-7304]):
203+
204+ ```java
205+ PreparedStatement prepared = session.prepare("INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)");
206+ BoundStatement bound = prepared.bind();
207+ bound.set("email", "clint.barton@hawkeye.com");
208+ bound.set("firstname", "Barney");
209+ // lastname is left unset.
210+ ```
211+
212+See [Parameters and Binding] for more details about unset parameters.
213+
214+Another possible root cause for this is using the object mapper and leaving
215+fields set to `null`. This also causes tombstones to be inserted unless
216+setting `saveNullFields` option to false. See [Mapper options] for more
217+details.
218+
219+[Blobs.java]: https://github.com/datastax/java-driver/tree/3.0.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java
220+[CASSANDRA-7304]: https://issues.apache.org/jira/browse/CASSANDRA-7304
221+[Parameters and Binding]: ../manual/statements/prepared/#parameters-and-binding
222+[Mapper options]: ../manual/object_mapper/using/#mapper-options
modified manual/async/README.md +0 −12
@@ -130,21 +130,9 @@
130130 issues, you should create your `Cluster` instances while bootstrapping
131131 your application, and call `init` immediately. If you need to create new
132132 instances at runtime, make sure this does not happen on an I/O thread.
133-* if a connection pool is busy, the driver will block until a connection
134- becomes available. To avoid this, set
135- [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the
136- driver will not block, just move to the next host immediately.
137-* if the session is set to a specific keyspace (either at startup or by
138- issuing a `USE` statement on a running session), the keyspace needs to
139- be propagated to any newly created connection. This is done when the
140- connection is first borrowed from the connection pool, and currently
141- blocks. To avoid any issue, only use a session with no keyspace set
142- (i.e. created by `Cluster#connect()`). This will be addressed in
143- [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893).
144133 * trying to read fields from a [query trace] will block if the trace
145134 hasn't been fetched already.
146135
147136 [ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
148137 [init]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.html#init--
149-[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int-
150138 [query trace]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryTrace.html
modified manual/load_balancing/README.md +2 −2
@@ -178,8 +178,8 @@
178178 // Set the routing key manually: serialize each partition key component to its target CQL type
179179 ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
180180 statement.setRoutingKey(
181- DataType.cint().serialize(1, protocolVersion),
182- DataType.cint().serialize(2016, protocolVersion));
181+ TypeCodec.cint().serialize(1, protocolVersion),
182+ TypeCodec.cint().serialize(2016, protocolVersion));
183183
184184 session.execute(statement);
185185 ```
modified manual/object_mapper/custom_codecs/README.md +1 −1
@@ -58,7 +58,7 @@
5858 ```java
5959 @Accessor
6060 interface UserAccessor {
61- @Query("update user set birth = :b where id = :i)
61+ @Query("update user set birth = :b where id = :i")
6262 void updateBirth(@Param("i") int id,
6363 @Param("b") MyCustomDate birth);
6464 }
modified manual/object_mapper/using/README.md +2 −2
@@ -146,13 +146,13 @@
146146 - `Mapper.getQuery(userId)`: returns a statement to select a row in the
147147 database, selected on the given `userId`, and matching the mapped
148148 object structure.
149-- `Mapper.deleteQuery(userID)`: returns a statement delete a row in the
149+- `Mapper.deleteQuery(userID)`: returns a statement to delete a row in the
150150 database given the `userId` provided. This method can also accept a
151151 mapped object instance.
152152
153153 #### Manual mapping
154154
155-`Mapper#map` provides a way to converts the results of a regular query:
155+`Mapper#map` provides a way to convert the results of a regular query:
156156
157157 ```java
158158 ResultSet results = session.execute("SELECT * FROM user");
modified manual/pooling/README.md +24 −23
@@ -180,24 +180,24 @@
180180 message.
181181
182182
183-#### Acquisition timeout
183+#### Acquisition queue
184184
185185 When the driver tries to send a request to a host, it will first try to
186186 acquire a connection from this host's pool. If the pool is busy (i.e.
187187 all connections are already handling their maximum number of in flight
188-requests), the client thread will block for a while, until a connection
189-becomes available (note that this will block even if you're using the
190-asynchronous API, like [Session.executeAsync][exec_async]).
188+requests), the acquisition attempt gets enqueued until a connection becomes
189+available again.
191190
192-The time that the driver blocks is controlled by
193-[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection
194-available after this timeout, the driver will try the next host.
191+The size of that queue is controlled by [PoolingOptions.setMaxQueueSize][smqs].
192+If the queue has already reached its limit, further attempts to acquire a
193+connection will be rejected immediately: the driver will move on and try to
194+acquire a connection from the next host's pool. The limit can be set to 0 to
195+disable queueing entirely.
195196
196-For some applications, blocking is not acceptable, and it is preferable
197-to fail fast if the request cannot be fulfilled. If that's your case,
198-set the pool timeout to 0. If all hosts are busy, you will get a
199-[NoHostAvailableException][nhae] (if you look at the exception's details, you
200-will see a `java.util.concurrent.TimeoutException` for each host).
197+If all hosts are busy with a full queue, the request will fail with a
198+[NoHostAvailableException][nhae]. If you inspect the map returns by this
199+exception's [getErrors] method, you will see a [BusyPoolException] for
200+each host.
201201
202202
203203 ### Monitoring and tuning the pool
@@ -278,14 +278,15 @@
278278 [newConnectionThreshold][nct] so that enough connections are added by
279279 the time you reach the bottleneck.
280280
281-[result_set_future]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html
282-[pooling_options]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html
283-[lbp]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
284-[nct]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int-
285-[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int-
286-[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int-
287-[rtm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis--
288-[exec_async]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement-
289-[ptm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int-
290-[nhae]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
291-[get_state]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState--
281+[result_set_future]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html
282+[pooling_options]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html
283+[lbp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
284+[nct]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int-
285+[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int-
286+[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int-
287+[rtm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis--
288+[smqs]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxQueueSize-int-
289+[nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
290+[getErrors]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors--
291+[get_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState--
292+[BusyPoolException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/BusyPoolException.html
modified manual/shaded_jar/README.md +7 −7
@@ -56,16 +56,16 @@
5656
5757 ### Limitations
5858
59-When using the shaded jar, it is not possible to configure the Netty layer.
59+When using the shaded jar, it is not possible to configure the Netty layer.
6060
61-Extending [NettyOptions] is not an option because `NettyOptions` API
62-exposes Netty classes, and as such it should only be extended
63-by clients using the non-shaded version of driver.
64-Attempting to extend `NettyOptions` with shaded Netty classes is not supported,
65-and in particular for OSGi applications,
61+Extending [NettyOptions] is not an option because `NettyOptions` API
62+exposes Netty classes, and as such it should only be extended
63+by clients using the non-shaded version of driver.
64+Attempting to extend `NettyOptions` with shaded Netty classes is not supported,
65+and in particular for OSGi applications,
6666 it is likely that such a configuration would lead to compile and/or runtime errors.
6767
68-Also, with shaded Netty classes, it is not possible to benefit
68+Also, with shaded Netty classes, it is not possible to benefit
6969 from [Netty native transports].
7070
7171 It is therefore normal to see the following log line when the driver starts and
modified pom.xml +8 −0
@@ -140,6 +140,10 @@
140140 <artifactId>maven-surefire-plugin</artifactId>
141141 <version>2.16</version>
142142 <configuration>
143+ <property>
144+ <name>usedefaultlisteners</name>
145+ <value>false</value> <!-- disable default listeners as some of the html reports do a lot of File I/O -->
146+ </property>
143147 <skip>true</skip>
144148 <forkCount>1</forkCount>
145149 <reuseForks>false</reuseForks>
@@ -377,6 +381,10 @@
377381 <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes>
378382 </classpathDependencyExcludes>
379383 <properties>
384+ <property>
385+ <name>usedefaultlisteners</name>
386+ <value>false</value> <!-- disable default listeners as some of the html reports do a lot of File I/O -->
387+ </property>
380388 <property>
381389 <!-- Don't skip tests after a @Before method throws a SkipException -->
382390 <name>configfailurepolicy</name>
modified upgrade_guide/README.md +16 −0
@@ -35,6 +35,22 @@
3535 3.2.0.
3636
3737
38+### 3.0.4
39+
40+The connection pool is now fully non-blocking ([JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893)),
41+which greatly improves asynchronous programming:
42+
43+* `Session.executeAsync` won't ever block the user thread anymore;
44+* you can now safely run async queries on a session connected to a keyspace.
45+
46+This new implementation brings a couple of changes:
47+
48+* pool saturation is no longer handled by a timeout, but instead by a bounded queue. As a consequence,
49+ `PoolingOptions.setPoolTimeoutMillis` has been deprecated, and replaced by `setMaxQueueSize`;
50+* a saturated pool will now throw `BusyPoolException` instead of `TimeoutException` (note that this exception is not
51+ rethrown directly to the client, but wrapped in `NoHostAvailableException.getErrors()`).
52+
53+
3854 ### 3.0.0
3955
4056 This version brings parity with Cassandra 2.2 and 3.0.
added upgrade_guide/migrating_from_astyanax/.nav +3 −0
@@ -0,0 +1,3 @@
1+language_level_changes
2+configuration
3+queries_and_results
No newline at the end of the file
added upgrade_guide/migrating_from_astyanax/README.md +10 −0
@@ -0,0 +1,10 @@
1+# Migrating from Astyanax
2+
3+This section is a guide for users previously using *Astyanax* and looking for
4+migrating to the *DataStax Java driver*.
5+
6+See the child pages for more information:
7+
8+* [Changes at the language level](language_level_changes/)
9+* [Migrating Astyanax configurations to DataStax Java driver configurations](configuration/)
10+* [Querying and retrieving results comparisons.](queries_and_results/)
added upgrade_guide/migrating_from_astyanax/configuration/README.md +252 −0
@@ -0,0 +1,252 @@
1+# Configuration
2+
3+## How Configuring the Java driver works
4+
5+The two basic components in the Java driver are the `Cluster` and the `Session`.
6+The `Cluster` is the object to create first, and on to which all global configurations
7+apply. Connecting to the `Cluster` creates a `Session`. Queries are executed
8+through the `Session`.
9+
10+The `Cluster` object then is to be viewed as the equivalent of the `AstyanaxContext`
11+object. "Starting" an `AstyanaxContext` object typically returns a `Keyspace`
12+object, the `Keyspace` object is the equivalent of the *Java driver*’s `Session`.
13+
14+Configuring a `Cluster` works with the *Builder* pattern. The `Builder` takes all
15+the configurations into account before building the `Cluster`.
16+
17+Following are some examples of the most important configurations that were
18+possible with *Astyanax* and how to translate them into *DataStax Java driver*
19+configurations. Please note that the Java driver has been optimized to handle most use
20+cases at best and even though the following sections show how to tune some various
21+options, the driver should provide the best performances with the default configurations
22+and these options should not be changed unless there is a good reason to.
23+
24+## Connection pools
25+
26+Configuration of connection pools in *Astyanax* are made through the
27+`ConnectionPoolConfigurationImpl`. This object gathers important configurations
28+that the *Java driver* has categorized in multiple *Option* and *Policy* kinds.
29+
30+### Connections pools internals
31+Everything concerning the internal pools of connections to the *Cassandra nodes*
32+will be gathered in the Java driver in the [`PoolingOptions`](../../../manual/pooling):
33+
34+*Astyanax*:
35+
36+```java
37+ConnectionPoolConfigurationImpl cpool =
38+ new ConnectionPoolConfigurationImpl("myConnectionPool")
39+ .setInitConnsPerHost(2)
40+ .setMaxConnsPerHost(3)
41+```
42+
43+*Java driver*:
44+
45+```java
46+PoolingOptions poolingOptions =
47+ new PoolingOptions()
48+ .setConnectionsPerHost(HostDistance.LOCAL, 2, 3)
49+```
50+The first number is the initial number of connections, the second is the maximum number
51+of connections the driver is allowed to create for each host.
52+
53+Note that the *Java driver* allows multiple simultaneous requests on one single
54+connection, as it is based upon the [*Native protocol*](../../../manual/native_protocol),
55+an asynchronous binary protocol that can handle up to 32768 simultaneous requests on a
56+single connection. The Java driver is able to manage and distribute simultaneous requests
57+by itself even under high contention, and changing the default `PoolingOptions` is not
58+necessary most of the time except for very [specific use cases](../../../manual/pooling/#tuning-protocol-v3-for-very-high-throughputs).
59+
60+### Timeouts
61+
62+Timeouts concerning requests, or connections will be part of the `SocketOptions`.
63+
64+*Astyanax*:
65+
66+```java
67+ConnectionPoolConfigurationImpl cpool =
68+ new ConnectionPoolConfigurationImpl("myConnectionPool")
69+ .setSocketTimeout(3000)
70+ .setConnectTimeout(3000)
71+```
72+
73+*Java Driver:*
74+
75+```java
76+SocketOptions so =
77+ new SocketOptions()
78+ .setReadTimeoutMillis(3000)
79+ .setConnectTimeoutMillis(3000);
80+```
81+
82+Changing the client timeout options might have more impacts than expected, **please make
83+sure to properly document before changing these options.**
84+
85+## Load Balancing
86+Both *Astyanax* and the *Java driver* connect to multiple nodes of the *Cassandra*
87+cluster. Distributing requests through all the nodes plays an important role in
88+the good operation of the `Cluster` and for best performances. With *Astyanax*,
89+requests (or “operations”) can be sent directly to replicas that have a copy of
90+the data targeted by the *“Row key”* specified in the operation. Since the *Thrift* API is
91+low-level, it forces the user to provide *Row keys*, known as the `TokenAware`
92+connection pool type. This setting is also present in the *Java driver*, however
93+the configuration is different and provides more options to tweak.
94+
95+Load balancing in the *Java driver* is a *Policy*, it is a class that will be
96+plugged in the *Java driver*’s code and the Driver will call its methods when it
97+needs to. The *Java driver* comes with a preset of specific load balancing policies.
98+Here’s an equivalent code:
99+
100+*Astyanax*:
101+
102+```java
103+final ConnectionPoolType poolType = ConnectionPoolType.TOKEN_AWARE;
104+final NodeDiscoveryType discType = NodeDiscoveryType.RING_DESCRIBE;
105+ConnectionPoolConfigurationImpl cpool =
106+ new ConnectionPoolConfigurationImpl("myConnectionPool")
107+ .setLocalDatacenter("myDC")
108+AstyanaxConfigurationImpl aconf =
109+ new AstyanaxConfigurationImpl()
110+ .setConnectionPoolType(poolType)
111+ .setDiscoveryType(discType)
112+```
113+
114+*Java driver*:
115+
116+```java
117+LoadBalancingPolicy lbp = new TokenAwarePolicy(
118+ DCAwareRoundRobinPolicy.builder()
119+ .withLocalDc("myDC")
120+ .build()
121+);
122+```
123+
124+*By default* the *Java driver* will instantiate the exact Load balancing policy
125+shown above, with the `LocalDC` being the DC of the first host the driver connects
126+to. So to get the same behaviour than the *TokenAware* pool type of *Astyanax*,
127+users shouldn’t need to specify a load balancing policy since the default one
128+should cover it.
129+
130+Important: Note that since *CQL* is an abstraction of the Cassandra’s architecture, a simple
131+query needs to have the *Row key* specified explicitly on a `Statement` in order
132+to benefit from the *TokenAware* routing (the *Row key* in the *Java driver* is
133+referenced as *Routing Key*), unlike the *Astyanax* driver.
134+Some differences occur related to the different kinds of `Statements` the *Java
135+driver* provides. Please see [this link](../../../manual/load_balancing/#token-aware-policy)
136+for specific information.
137+
138+Custom load balancing policies can easily be implemented by users, and supplied to
139+the *Java driver* for specific use cases. All information necessary is available
140+in the [Load balaning policies docs](../../../manual/load_balancing).
141+
142+## Consistency levels
143+Consistency levels can be set per-statement, or globally through the `QueryOptions`.
144+
145+*Astyanax*:
146+
147+```java
148+AstyanaxConfigurationImpl aconf =
149+ new AstyanaxConfigurationImpl()
150+ .setDefaultReadConsistencyLevel(ConsistencyLevel.CL*ALL)
151+ .setDefaultWriteConsistencyLevel(ConsistencyLevel.CL*ALL)
152+```
153+
154+*Java driver*:
155+
156+```java
157+QueryOptions qo = new QueryOptions().setConsistencyLevel(ConsistencyLevel.ALL);
158+```
159+
160+Since the *Java driver* only executes *CQL* statements, which can be either reads
161+or writes to *Cassandra*, it is not possible to globally configure the
162+Consistency Level for only reads or only writes. To do so, since the Consistency
163+Level can be set per-statement, you can either set it on every statement, or use
164+`PreparedStatements` (if queries are to be repeated with different values): in
165+this case, setting the CL on the `PreparedStatement`, causes the `BoundStatements` to
166+inherit the CL from the prepared statements they were prepared from. More
167+informations about how `Statement`s work in the *Java driver* are detailed
168+in the [“Queries and Results” section](../queries_and_results/).
169+
170+
171+## Authentication
172+
173+Authentication settings are managed by the `AuthProvider` class in the *Java driver*.
174+It can be highly customizable, but also comes with default simple implementations:
175+
176+*Astyanax*:
177+
178+```java
179+AuthenticationCredentials authCreds = new SimpleAuthenticationCredentials("username", "password");
180+ConnectionPoolConfigurationImpl cpool =
181+ new ConnectionPoolConfigurationImpl("myConnectionPool")
182+ .setAuthenticationCredentials(authCreds)
183+```
184+
185+*Java driver*:
186+
187+```java
188+AuthProvider authProvider = new PlainTextAuthProvider("username", "password");
189+```
190+
191+The class `AuthProvider` can be easily implemented to suit the user’s needs,
192+documentation about the classes needed is [available there](../../../manual/auth/).
193+
194+## Hosts and ports
195+
196+Setting the “seeds” or first hosts to connect to can be done directly on the
197+Cluster configuration Builder:
198+
199+*Astyanax*:
200+
201+```java
202+ConnectionPoolConfigurationImpl cpool =
203+ new ConnectionPoolConfigurationImpl("myConnectionPool")
204+ .setSeeds("127.0.0.1")
205+ .setPort(9160)
206+```
207+
208+*Java driver*:
209+
210+```java
211+Cluster cluster = Cluster.builder()
212+ .addContactPoint("127.0.0.1")
213+ .withPort(9042)
214+```
215+
216+The *Java driver* by default connects to port *9042*, hence you can supply only
217+host names with the `addContactPoints(String...)` method. Note that the contact
218+points are only the entry points to the `Cluster` for the *Automatic discovery
219+phase*.
220+
221+## Building the Cluster
222+With all options previously presented, one may configure and create the
223+`Cluster` object this way:
224+
225+*Java driver*:
226+
227+```java
228+Cluster cluster = Cluster.builder()
229+ .addContactPoint("127.0.0.1")
230+ .withAuthProvider(authProvider)
231+ .withLoadBalancingPolicy(lbp)
232+ .withSocketOptions(so)
233+ .withPoolingOptions(poolingOptions)
234+ .withQueryOptions(qo)
235+ .build();
236+Session session = cluster.connect();
237+```
238+
239+## Best Practices
240+
241+A few best practices are summed up in [this blog post](http://www.datastax.com/dev/blog/4-simple-rules-when-using-the-datastax-drivers-for-cassandra).
242+
243+Concerning connection pools, the Java driver’s default settings should allow
244+most of the users to get the best out of the driver in terms of throughput,
245+they have been thoroughly tested and tweaked to accommodate the users’ needs.
246+If one still wishes to change those, first [Monitoring the pools](../../../manual/pooling/#monitoring-and-tuning-the-pool) is
247+advised, then a [deep dive in the Pools management mechanism](../../../manual/pooling/) should
248+provide enough insight.
249+
250+A lot more options are available in the different `XxxxOption`s classes, policies are
251+also highly customizable since the base Java driver's implementations can easily be
252+extended and implement user-specific actions.
added upgrade_guide/migrating_from_astyanax/language_level_changes/README.md +75 −0
@@ -0,0 +1,75 @@
1+# Language change : from Thrift to CQL
2+The data model changes when using *CQL* (Cassandra Query Language).
3+*CQL* is providing an abstraction of the low-level data stored in *Cassandra*, in
4+opposition to *Thrift* that aims to expose the low-level data structure directly.
5+[But note that this changes with Cassandra 3’s new storage engine.](http://www.datastax.com/2015/12/storage-engine-30)
6+
7+*Thrift* exposes *Keyspaces*, and these *Keyspaces* contain *Column Families*. A
8+*ColumnFamily* contains *Rows* in which each *Row* has a list of an arbitrary number
9+of column-values. With *CQL*, the data is **tabular**, *ColumnFamily* gets viewed
10+as a *Table*, the **Table Rows** get a **fixed and finite number of named columns**.
11+*Thrift*’s columns inside the *Rows* get distributed in a tabular way through the
12+_Table Rows_. See the following figure:
13+
14+```ditaa
15+ Thrift
16+ /- -\
17+ | |
18+ | /------------\ /---------------+---------------+---------------+---------+ |
19+ | | cRED | |cFA0 1 | 2 | 3 | | |
20+ | | 1 | ----------> +---------------+---------------+---------------+ ... | +--> One Thrift
21+ | | | |c1AB 'a' | 'b' | 'c' | | | ROW
22+ | \------------/ \---------------+---------------+---------------+---------+ |
23+ | |
24+One Thrift | -/
25+COLUMNFAMILY |
26+ |
27+ | /------------\ /---------------+---------------+---------+
28+ | | | | 1 | 2 | |
29+ | | 2 | ----------> +---------------+---------------+ ... |
30+ | | | | 'a' | 'b' | |
31+ | \------------/ \---------------+---------------+---------+
32+ |
33+ \-
34+
35+
36+ -----------------------------------------------------------------------
37+
38+
39+ CQL
40+
41+ /-
42+ |
43+ | /--------------------+---------------------------------+-----------------------------\
44+ | | key | column1 | value |
45+ | +--------------------+---------------------------------+-----------------------------+
46+ | | cRED 1 | cFA0 1 | c1AB 'a' |
47+ | +--------------------+---------------------------------+-----------------------------+ -\
48+ | | cRED 1 | 2 | 'b' | +--> One CQL
49+ One CQL | +--------------------+---------------------------------+-----------------------------+ -/ ROW
50+ TABLE | | cRED 1 | 3 | 'c' |
51+ | +--------------------+---------------------------------+-----------------------------+
52+ | | cRED ... | ... | ... |
53+ | +--------------------+---------------------------------+-----------------------------+
54+ | | 2 | 1 | 'a' |
55+ | +--------------------+---------------------------------+-----------------------------+
56+ | | 2 | 2 | 'b' |
57+ | +--------------------+---------------------------------+-----------------------------+
58+ | | ... | ... | ... |
59+ | +--------------------+---------------------------------+-----------------------------+
60+ \-
61+```
62+
63+Some of the columns of a *CQL Table* have a special role that is specifically
64+related to the *Cassandra* architecture. Indeed, the *Row key* of the *Thrift Row*,
65+becomes the *Partition Key* in the *CQL Table*, and can be composed of 1 or multiple
66+*CQL columns* (the key column in Figure 1). The *“Column”* part of the Column-value
67+component in a *Thrift Row*, becomes the *Clustering Column* in *CQL*, and can
68+also be composed of multiple columns (in the figure, column1 is the only column
69+composing the *Clustering Column*, but there can be others if the Thrift's ColumnComparator
70+is a CompositeType).
71+
72+Here is the basic architectural concept of *CQL*, a detailed explanation and *CQL*
73+examples can be found in this article : [http://www.planetcassandra.org/making-the-change-from-thrift-to-cql/](http://www.planetcassandra.org/making-the-change-from-thrift-to-cql/).
74+Understanding the *CQL* abstraction plays a key role in developing performing
75+and scaling applications.
added upgrade_guide/migrating_from_astyanax/queries_and_results/README.md +106 −0
@@ -0,0 +1,106 @@
1+# Queries and Results
2+There are many resources such as [this post][planetCCqlLink] or [this post][dsBlogCqlLink] to learn
3+how to transform previous Thrift operations to CQL queries.
4+
5+The *Java driver* executes CQL queries through the `Session`.
6+The queries can either be simple *CQL* Strings or represented in the form of
7+`Statement`s. The driver offers 4 kinds of statements, `SimpleStatement`,
8+`Prepared/BoundStatement`, `BuiltStatement`, and `BatchStatement`. All necessary
9+information can be [found here](../../../manual/statements/) about the nature of the different
10+`Statement`s.
11+
12+As explained in [the running section](../../../manual/#running-queries),
13+results of a *CQL* query will be in the form of *Rows* from *Tables*, composed
14+of fixed set of columns, each with a type and a name. The driver exposes the
15+set of *Rows* returned from a query as a ResultSet, thus containing *Rows* on
16+which `getXXX()` can be called. Here are simple examples of translation from
17+*Astyanax* to *Java driver* in querying and retrieving query results.
18+
19+## Single column
20+
21+*Astyanax*:
22+
23+```java
24+ColumnFamily<String, String> CF_STANDARD1 = new ColumnFamily<String, String>("cf1", StringSerializer.get(), StringSerializer.get(). StringSerializer.get());
25+
26+Column<String> result = keyspace.prepareQuery(CF_STANDARD1)
27+ .getKey("1")
28+ .getColumn("3")
29+ .execute().getResult();
30+String value = result.getStringValue();
31+```
32+
33+*Java driver*:
34+
35+```
36+Row row = session.execute("SELECT value FROM table1 WHERE key = '1' AND column1 = '3'").one();
37+String value = row.getString("value");
38+```
39+
40+## All columns
41+
42+*Astyanax*:
43+
44+```java
45+ColumnList<String> columns;
46+int pagesize = 10;
47+RowQuery<String, String> query = keyspace
48+ .prepareQuery(CF_STANDARD1)
49+ .getKey("1")
50+ .autoPaginate(true)
51+ .withColumnRange(new RangeBuilder().setLimit(pagesize).build());
52+
53+while (!(columns = query.execute().getResult()).isEmpty()) {
54+ for (Column<String> c : columns) {
55+ String value = c.getStringValue();
56+ }
57+}
58+```
59+
60+*Java driver*:
61+
62+```java
63+ResultSet rs = session.execute("SELECT value FROM table1 WHERE key = '1'");
64+for (Row row : rs) {
65+ String value = row.getString("value");
66+}
67+```
68+
69+## Column range
70+
71+*Astyanax*:
72+
73+```java
74+ColumnList<String> result;
75+result = keyspace.prepareQuery(CF_STANDARD1)
76+ .getKey("1")
77+ .withColumnRange(new RangeBuilder().setStart("3").setEnd("5").setMaxSize(100).build())
78+ .execute().getResult();
79+
80+Iterator<Column<String>> it = result.iterator();
81+while (it.hasNext()) {
82+ Column<String> col = it.next();
83+ String value = col.getStringValue();
84+}
85+```
86+
87+*Java driver*:
88+
89+```java
90+ResultSet rs = session.execute("SELECT value FROM table1 WHERE key = '1'" +
91+ " AND column1 > '3'" +
92+ " AND column1 < '5'");
93+for (Row row : rs) {
94+ String value = row.getString("value");
95+}
96+```
97+
98+## Async
99+The *Java driver* provides native support for asynchronous programming since it
100+is built on top of an [asynchronous protocol](../../../manual/native_protocol/),
101+please see [this page](../../../manual/async/) for best practices regarding asynchronous programming
102+with the *Java driver*.
103+
104+
105+[planetCCqlLink]: http://www.planetcassandra.org/making-the-change-from-thrift-to-cql/
106+[dsBlogCqlLink]: http://www.datastax.com/dev/blog/thrift-to-cql3
No newline at the end of the file