Elffuss BraidHub

kikocis/java-driver public

Upgrade Netty to 4.0.26 (JAVA-622).

Includes patch to coalesce frames before flushing them (JAVA-562),
submitted by Ariel Weisberg.
Changeset5e4320ed301955f9b0ac41d9af8adc6d9b5150d876c5750d9999f2c12fae40cf
Authorolim7t <omichallat+github@gmail.com> · 2014-11-11 17:19 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-03-30 15:59 +02:00
Parentsfa3b8ab03aa1

Browse the files at this changeset

16 files changed

modified driver-core/CHANGELOG.rst +3 −0
@@ -22,6 +22,9 @@
2222 - [new feature] Add getObject to BoundStatement and Row (JAVA-584)
2323 - [improvement] Improve connection pool resizing algorithm (JAVA-419)
2424 - [bug] Fix race condition between pool expansion and shutdown (JAVA-599)
25+- [improvement] Upgrade Netty to 4.0.26 (JAVA-622)
26+- [improvement] Coalesce frames before flushing them to the connection
27+ (JAVA-562)
2528
2629 Merged from 2.0.9_fixes branch:
2730
modified driver-core/pom.xml +22 −6
@@ -29,7 +29,7 @@
2929 <dependencies>
3030 <dependency>
3131 <groupId>io.netty</groupId>
32- <artifactId>netty</artifactId>
32+ <artifactId>netty-handler</artifactId>
3333 <version>${netty.version}</version>
3434 </dependency>
3535
@@ -62,6 +62,13 @@
6262 <optional>true</optional>
6363 </dependency>
6464
65+ <dependency>
66+ <groupId>io.netty</groupId>
67+ <artifactId>netty-transport-native-epoll</artifactId>
68+ <version>${netty.version}</version>
69+ <optional>true</optional>
70+ </dependency>
71+
6572 <!-- End of compression libraries -->
6673
6774 <dependency>
@@ -162,7 +169,7 @@
162169 <configuration>
163170 <manifestLocation>${project.build.directory}/META-INF-shaded</manifestLocation>
164171 <instructions>
165- <Import-Package><![CDATA[com.google.common.*;version="[14.0,19)",!org.jboss.netty.*,*]]></Import-Package>
172+ <Import-Package><![CDATA[com.google.common.*;version="[14.0,19)",!io.netty.*,*]]></Import-Package>
166173 <Private-Package>com.datastax.shaded.*</Private-Package>
167174 </instructions>
168175 </configuration>
@@ -180,12 +187,12 @@
180187 <shadedArtifactAttached>true</shadedArtifactAttached>
181188 <artifactSet>
182189 <includes>
183- <include>io.netty:netty</include>
190+ <include>io.netty:*</include>
184191 </includes>
185192 </artifactSet>
186193 <relocations>
187194 <relocation>
188- <pattern>org.jboss.netty</pattern>
195+ <pattern>io.netty</pattern>
189196 <shadedPattern>com.datastax.shaded.netty</shadedPattern>
190197 </relocation>
191198 </relocations>
@@ -193,8 +200,17 @@
193200 <transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
194201 <resources>
195202 <resource>META-INF/MANIFEST.MF</resource>
196- <resource>META-INF/maven/io.netty/netty/pom.properties</resource>
197- <resource>META-INF/maven/io.netty/netty/pom.xml</resource>
203+ <resource>META-INF/io.netty.versions.properties</resource>
204+ <resource>META-INF/maven/io.netty/netty-buffer/pom.properties</resource>
205+ <resource>META-INF/maven/io.netty/netty-buffer/pom.xml</resource>
206+ <resource>META-INF/maven/io.netty/netty-codec/pom.properties</resource>
207+ <resource>META-INF/maven/io.netty/netty-codec/pom.xml</resource>
208+ <resource>META-INF/maven/io.netty/netty-common/pom.properties</resource>
209+ <resource>META-INF/maven/io.netty/netty-common/pom.xml</resource>
210+ <resource>META-INF/maven/io.netty/netty-handler/pom.properties</resource>
211+ <resource>META-INF/maven/io.netty/netty-handler/pom.xml</resource>
212+ <resource>META-INF/maven/io.netty/netty-transport/pom.properties</resource>
213+ <resource>META-INF/maven/io.netty/netty-transport/pom.xml</resource>
198214 </resources>
199215 </transformer>
200216 <!-- Pick up the alternate manifest that was generated by the alternate execution of the bundle plugin -->
modified driver-core/src/main/java/com/datastax/driver/core/CBUtil.java +36 −32
@@ -22,19 +22,19 @@
2222 import java.nio.charset.CharacterCodingException;
2323 import java.util.*;
2424
25-import org.jboss.netty.buffer.ChannelBuffer;
26-import org.jboss.netty.util.CharsetUtil;
25+import io.netty.buffer.ByteBuf;
26+import io.netty.util.CharsetUtil;
2727
2828 import com.datastax.driver.core.exceptions.DriverInternalError;
2929
3030 /**
31- * ChannelBuffer utility methods.
31+ * ByteBuf utility methods.
3232 */
33-abstract class CBUtil {
33+abstract class CBUtil { // TODO rename
3434
3535 private CBUtil() {}
3636
37- private static String readString(ChannelBuffer cb, int length) {
37+ private static String readString(ByteBuf cb, int length) {
3838 try {
3939 String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8);
4040 cb.readerIndex(cb.readerIndex() + length);
@@ -48,7 +48,7 @@
4848 }
4949 }
5050
51- public static String readString(ChannelBuffer cb) {
51+ public static String readString(ByteBuf cb) {
5252 try {
5353 int length = cb.readUnsignedShort();
5454 return readString(cb, length);
@@ -57,7 +57,7 @@
5757 }
5858 }
5959
60- public static void writeString(String str, ChannelBuffer cb) {
60+ public static void writeString(String str, ByteBuf cb) {
6161 byte[] bytes = str.getBytes(CharsetUtil.UTF_8);
6262 cb.writeShort(bytes.length);
6363 cb.writeBytes(bytes);
@@ -82,7 +82,7 @@
8282 return utflen;
8383 }
8484
85- public static String readLongString(ChannelBuffer cb) {
85+ public static String readLongString(ByteBuf cb) {
8686 try {
8787 int length = cb.readInt();
8888 return readString(cb, length);
@@ -91,7 +91,7 @@
9191 }
9292 }
9393
94- public static void writeLongString(String str, ChannelBuffer cb) {
94+ public static void writeLongString(String str, ByteBuf cb) {
9595 byte[] bytes = str.getBytes(CharsetUtil.UTF_8);
9696 cb.writeInt(bytes.length);
9797 cb.writeBytes(bytes);
@@ -101,7 +101,7 @@
101101 return 4 + str.getBytes(CharsetUtil.UTF_8).length;
102102 }
103103
104- public static byte[] readBytes(ChannelBuffer cb) {
104+ public static byte[] readBytes(ByteBuf cb) {
105105 try {
106106 int length = cb.readUnsignedShort();
107107 byte[] bytes = new byte[length];
@@ -112,7 +112,7 @@
112112 }
113113 }
114114
115- public static void writeBytes(byte[] bytes, ChannelBuffer cb) {
115+ public static void writeBytes(byte[] bytes, ByteBuf cb) {
116116 cb.writeShort(bytes.length);
117117 cb.writeBytes(bytes);
118118 }
@@ -121,11 +121,11 @@
121121 return 2 + bytes.length;
122122 }
123123
124- public static ConsistencyLevel readConsistencyLevel(ChannelBuffer cb) {
124+ public static ConsistencyLevel readConsistencyLevel(ByteBuf cb) {
125125 return ConsistencyLevel.fromCode(cb.readUnsignedShort());
126126 }
127127
128- public static void writeConsistencyLevel(ConsistencyLevel consistency, ChannelBuffer cb) {
128+ public static void writeConsistencyLevel(ConsistencyLevel consistency, ByteBuf cb) {
129129 cb.writeShort(consistency.code);
130130 }
131131
@@ -133,7 +133,7 @@
133133 return 2;
134134 }
135135
136- public static <T extends Enum<T>> T readEnumValue(Class<T> enumType, ChannelBuffer cb) {
136+ public static <T extends Enum<T>> T readEnumValue(Class<T> enumType, ByteBuf cb) {
137137 String value = CBUtil.readString(cb);
138138 try {
139139 return Enum.valueOf(enumType, value.toUpperCase());
@@ -142,7 +142,7 @@
142142 }
143143 }
144144
145- public static <T extends Enum<T>> void writeEnumValue(T enumValue, ChannelBuffer cb) {
145+ public static <T extends Enum<T>> void writeEnumValue(T enumValue, ByteBuf cb) {
146146 writeString(enumValue.toString(), cb);
147147 }
148148
@@ -150,13 +150,13 @@
150150 return sizeOfString(enumValue.toString());
151151 }
152152
153- public static UUID readUUID(ChannelBuffer cb) {
153+ public static UUID readUUID(ByteBuf cb) {
154154 long msb = cb.readLong();
155155 long lsb = cb.readLong();
156156 return new UUID(msb, lsb);
157157 }
158158
159- public static void writeUUID(UUID uuid, ChannelBuffer cb) {
159+ public static void writeUUID(UUID uuid, ByteBuf cb) {
160160 cb.writeLong(uuid.getMostSignificantBits());
161161 cb.writeLong(uuid.getLeastSignificantBits());
162162 }
@@ -165,7 +165,7 @@
165165 return 16;
166166 }
167167
168- public static List<String> readStringList(ChannelBuffer cb) {
168+ public static List<String> readStringList(ByteBuf cb) {
169169 int length = cb.readUnsignedShort();
170170 List<String> l = new ArrayList<String>(length);
171171 for (int i = 0; i < length; i++)
@@ -173,7 +173,7 @@
173173 return l;
174174 }
175175
176- public static void writeStringList(List<String> l, ChannelBuffer cb) {
176+ public static void writeStringList(List<String> l, ByteBuf cb) {
177177 cb.writeShort(l.size());
178178 for (String str : l)
179179 writeString(str, cb);
@@ -186,7 +186,7 @@
186186 return size;
187187 }
188188
189- public static Map<String, String> readStringMap(ChannelBuffer cb) {
189+ public static Map<String, String> readStringMap(ByteBuf cb) {
190190 int length = cb.readUnsignedShort();
191191 Map<String, String> m = new HashMap<String, String>(length);
192192 for (int i = 0; i < length; i++) {
@@ -197,7 +197,7 @@
197197 return m;
198198 }
199199
200- public static void writeStringMap(Map<String, String> m, ChannelBuffer cb) {
200+ public static void writeStringMap(Map<String, String> m, ByteBuf cb) {
201201 cb.writeShort(m.size());
202202 for (Map.Entry<String, String> entry : m.entrySet()) {
203203 writeString(entry.getKey(), cb);
@@ -214,7 +214,7 @@
214214 return size;
215215 }
216216
217- public static Map<String, List<String>> readStringToStringListMap(ChannelBuffer cb) {
217+ public static Map<String, List<String>> readStringToStringListMap(ByteBuf cb) {
218218 int length = cb.readUnsignedShort();
219219 Map<String, List<String>> m = new HashMap<String, List<String>>(length);
220220 for (int i = 0; i < length; i++) {
@@ -225,7 +225,7 @@
225225 return m;
226226 }
227227
228- public static void writeStringToStringListMap(Map<String, List<String>> m, ChannelBuffer cb) {
228+ public static void writeStringToStringListMap(Map<String, List<String>> m, ByteBuf cb) {
229229 cb.writeShort(m.size());
230230 for (Map.Entry<String, List<String>> entry : m.entrySet()) {
231231 writeString(entry.getKey(), cb);
@@ -242,12 +242,16 @@
242242 return size;
243243 }
244244
245- public static ByteBuffer readValue(ChannelBuffer cb) {
245+ public static ByteBuffer readValue(ByteBuf cb) {
246246 int length = cb.readInt();
247- return length < 0 ? null : cb.readSlice(length).toByteBuffer();
247+ if (length < 0)
248+ return null;
249+ ByteBuf slice = cb.readSlice(length);
250+
251+ return ByteBuffer.wrap(readRawBytes(slice));
248252 }
249253
250- public static void writeValue(byte[] bytes, ChannelBuffer cb) {
254+ public static void writeValue(byte[] bytes, ByteBuf cb) {
251255 if (bytes == null) {
252256 cb.writeInt(-1);
253257 return;
@@ -257,7 +261,7 @@
257261 cb.writeBytes(bytes);
258262 }
259263
260- public static void writeValue(ByteBuffer bytes, ChannelBuffer cb) {
264+ public static void writeValue(ByteBuffer bytes, ByteBuf cb) {
261265 if (bytes == null) {
262266 cb.writeInt(-1);
263267 return;
@@ -275,7 +279,7 @@
275279 return 4 + (bytes == null ? 0 : bytes.remaining());
276280 }
277281
278- public static List<ByteBuffer> readValueList(ChannelBuffer cb) {
282+ public static List<ByteBuffer> readValueList(ByteBuf cb) {
279283 int size = cb.readUnsignedShort();
280284 if (size == 0)
281285 return Collections.<ByteBuffer>emptyList();
@@ -286,7 +290,7 @@
286290 return l;
287291 }
288292
289- public static void writeValueList(List<ByteBuffer> values, ChannelBuffer cb) {
293+ public static void writeValueList(List<ByteBuffer> values, ByteBuf cb) {
290294 cb.writeShort(values.size());
291295 for (ByteBuffer value : values)
292296 CBUtil.writeValue(value, cb);
@@ -299,7 +303,7 @@
299303 return size;
300304 }
301305
302- public static InetSocketAddress readInet(ChannelBuffer cb) {
306+ public static InetSocketAddress readInet(ByteBuf cb) {
303307 int addrSize = cb.readByte();
304308 byte[] address = new byte[addrSize];
305309 cb.readBytes(address);
@@ -311,7 +315,7 @@
311315 }
312316 }
313317
314- public static void writeInet(InetSocketAddress inet, ChannelBuffer cb) {
318+ public static void writeInet(InetSocketAddress inet, ByteBuf cb) {
315319 byte[] address = inet.getAddress().getAddress();
316320
317321 cb.writeByte(address.length);
@@ -328,7 +332,7 @@
328332 * Reads *all* readable bytes from {@code cb} and return them.
329333 * If {@code cb} is backed by an array, this will return the underlying array directly, without copy.
330334 */
331- public static byte[] readRawBytes(ChannelBuffer cb) {
335+ public static byte[] readRawBytes(ByteBuf cb) {
332336 if (cb.hasArray() && cb.readableBytes() == cb.array().length) {
333337 // Move the readerIndex just so we consistently consume the input
334338 cb.readerIndex(cb.writerIndex());
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +225 −97
@@ -15,32 +15,42 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import javax.net.ssl.SSLEngine;
1918 import java.net.InetSocketAddress;
19+import java.util.HashSet;
2020 import java.util.Iterator;
21+import java.util.List;
22+import java.util.Queue;
2123 import java.util.concurrent.*;
2224 import java.util.concurrent.atomic.AtomicBoolean;
2325 import java.util.concurrent.atomic.AtomicInteger;
2426 import java.util.concurrent.atomic.AtomicReference;
2527
28+import com.google.common.collect.Lists;
2629 import com.google.common.util.concurrent.AbstractFuture;
2730 import com.google.common.util.concurrent.ThreadFactoryBuilder;
2831 import com.google.common.util.concurrent.Uninterruptibles;
29-import org.jboss.netty.bootstrap.ClientBootstrap;
30-import org.jboss.netty.channel.*;
31-import org.jboss.netty.channel.group.ChannelGroup;
32-import org.jboss.netty.channel.group.DefaultChannelGroup;
33-import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
34-import org.jboss.netty.handler.ssl.SslHandler;
35-import org.jboss.netty.handler.timeout.IdleStateAwareChannelUpstreamHandler;
36-import org.jboss.netty.handler.timeout.IdleStateEvent;
37-import org.jboss.netty.handler.timeout.IdleStateHandler;
38-import org.jboss.netty.util.HashedWheelTimer;
39-import org.jboss.netty.util.Timeout;
40-import org.jboss.netty.util.TimerTask;
32+import io.netty.bootstrap.Bootstrap;
33+import io.netty.channel.*;
34+import io.netty.channel.epoll.EpollEventLoopGroup;
35+import io.netty.channel.epoll.EpollSocketChannel;
36+import io.netty.channel.group.ChannelGroup;
37+import io.netty.channel.group.DefaultChannelGroup;
38+import io.netty.channel.nio.NioEventLoopGroup;
39+import io.netty.channel.socket.SocketChannel;
40+import io.netty.channel.socket.nio.NioSocketChannel;
41+import io.netty.handler.ssl.SslHandler;
42+import io.netty.handler.timeout.IdleStateEvent;
43+import io.netty.handler.timeout.IdleStateHandler;
44+import io.netty.util.HashedWheelTimer;
45+import io.netty.util.Timeout;
46+import io.netty.util.TimerTask;
47+import io.netty.util.concurrent.GlobalEventExecutor;
48+import javax.net.ssl.SSLEngine;
4149 import org.slf4j.Logger;
4250 import org.slf4j.LoggerFactory;
4351
52+import static io.netty.handler.timeout.IdleState.ALL_IDLE;
53+
4454 import com.datastax.driver.core.exceptions.AuthenticationException;
4555 import com.datastax.driver.core.exceptions.DriverInternalError;
4656
@@ -56,6 +66,9 @@
5666 private static final Logger logger = LoggerFactory.getLogger(Connection.class);
5767 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
5868
69+ private static final boolean DISABLE_COALESCING = SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false);
70+ private static final boolean FORCE_NIO = SystemProperties.getBoolean("com.datastax.driver.FORCE_NIO", false);
71+
5972 public final InetSocketAddress address;
6073 private final String name;
6174
@@ -89,24 +102,26 @@
89102 this.name = name;
90103
91104 try {
92- ClientBootstrap bootstrap = factory.newBootstrap();
105+ Bootstrap bootstrap = factory.newBootstrap();
93106 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
94107 int protocolVersion = factory.protocolVersion == 1 ? 1 : 2;
95- bootstrap.setPipelineFactory(new PipelineFactory(this, protocolVersion, protocolOptions.getCompression().compressor, protocolOptions.getSSLOptions(),
96- factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(), factory.timer));
108+ bootstrap.handler(
109+ new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor, protocolOptions.getSSLOptions(),
110+ factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds()));
97111
98112 ChannelFuture future = bootstrap.connect(address);
99113
100114 writer.incrementAndGet();
101115 try {
102116 // Wait until the connection attempt succeeds or fails.
103- this.channel = future.awaitUninterruptibly().getChannel();
117+ this.channel = future.awaitUninterruptibly().channel();
104118 this.factory.allChannels.add(this.channel);
105119 if (!future.isSuccess()) {
106120 if (logger.isDebugEnabled())
107- logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.getCause())));
108- throw defunct(new TransportException(address, "Cannot connect", future.getCause()));
121+ logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.cause())));
122+ throw defunct(new TransportException(address, "Cannot connect", future.cause()));
109123 }
124+ channel.closeFuture().addListener(new ChannelCloseListener());
110125 } finally {
111126 writer.decrementAndGet();
112127 }
@@ -400,8 +415,12 @@
400415
401416 logger.trace("{} writing request {}", this, request);
402417 writer.incrementAndGet();
403- channel.write(request).addListener(writeHandler(request, handler));
404418
419+ if (DISABLE_COALESCING) {
420+ channel.writeAndFlush(request).addListener(writeHandler(request, handler));
421+ } else {
422+ flush(new FlushItem(channel, request, writeHandler(request, handler)));
423+ }
405424 if (startTimeout)
406425 handler.startTimeout();
407426
@@ -422,10 +441,10 @@
422441 dispatcher.removeHandler(handler, true);
423442
424443 final ConnectionException ce;
425- if (writeFuture.getCause() instanceof java.nio.channels.ClosedChannelException) {
444+ if (writeFuture.cause() instanceof java.nio.channels.ClosedChannelException) {
426445 ce = new TransportException(address, "Error writing: Closed channel");
427446 } else {
428- ce = new TransportException(address, "Error writing", writeFuture.getCause());
447+ ce = new TransportException(address, "Error writing", writeFuture.cause());
429448 }
430449 final long latency = System.nanoTime() - handler.startTime;
431450 // This handler is executed while holding the writeLock of the channel.
@@ -519,12 +538,33 @@
519538
520539 public static class Factory {
521540
522- private final ExecutorService bossExecutor = Executors.newCachedThreadPool();
523- private final ExecutorService workerExecutor = Executors.newCachedThreadPool();
541+ private static final Class<? extends EventLoopGroup> EVENT_LOOP_GROUP_CLASS;
542+ private static final Class<? extends Channel> CHANNEL_CLASS;
543+ static {
544+ boolean useEpoll;
545+ try {
546+ Class.forName("io.netty.channel.epoll.EpollEventLoopGroup");
547+ if (FORCE_NIO) {
548+ logger.info("Found Netty's native epoll transport in the classpath, "
549+ + "but NIO was forced through the FORCE_NIO system property");
550+ useEpoll = false;
551+ } else {
552+ logger.info("Found Netty's native epoll transport in the classpath, using it");
553+ useEpoll = true;
554+ }
555+ } catch (ClassNotFoundException e) {
556+ logger.info("Did not find Netty's native epoll transport in the classpath, defaulting to NIO");
557+ useEpoll = false;
558+ }
559+ EVENT_LOOP_GROUP_CLASS = useEpoll ? EpollEventLoopGroup.class : NioEventLoopGroup.class;
560+ CHANNEL_CLASS = useEpoll ? EpollSocketChannel.class : NioSocketChannel.class;
561+ }
562+
524563 public final HashedWheelTimer timer = new HashedWheelTimer(new ThreadFactoryBuilder().setNameFormat("Timeouter-%d").build());
525564
526- private final ChannelFactory channelFactory = new NioClientSocketChannelFactory(bossExecutor, workerExecutor);
527- private final ChannelGroup allChannels = new DefaultChannelGroup();
565+ private final EventLoopGroup eventLoopGroup;
566+
567+ private final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
528568
529569 private final ConcurrentMap<Host, AtomicInteger> idGenerators = new ConcurrentHashMap<Host, AtomicInteger>();
530570 public final DefaultResponseHandler defaultHandler;
@@ -544,6 +584,14 @@
544584 this.configuration = configuration;
545585 this.authProvider = configuration.getProtocolOptions().getAuthProvider();
546586 this.protocolVersion = configuration.getProtocolOptions().initialProtocolVersion;
587+
588+ try {
589+ eventLoopGroup = EVENT_LOOP_GROUP_CLASS.newInstance();
590+ } catch (Exception e) {
591+ throw new AssertionError("Could not create an instance of "
592+ + EVENT_LOOP_GROUP_CLASS.getName()
593+ + ", this should not happen");
594+ }
547595 }
548596
549597 public int getPort() {
@@ -599,30 +647,32 @@
599647 return configuration.getSocketOptions().getReadTimeoutMillis();
600648 }
601649
602- private ClientBootstrap newBootstrap() {
603- ClientBootstrap b = new ClientBootstrap(channelFactory);
650+ private Bootstrap newBootstrap() {
651+ Bootstrap b = new Bootstrap();
652+ b.group(eventLoopGroup)
653+ .channel(CHANNEL_CLASS);
604654
605655 SocketOptions options = configuration.getSocketOptions();
606656
607- b.setOption("connectTimeoutMillis", options.getConnectTimeoutMillis());
657+ b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeoutMillis());
608658 Boolean keepAlive = options.getKeepAlive();
609659 if (keepAlive != null)
610- b.setOption("keepAlive", keepAlive);
660+ b.option(ChannelOption.SO_KEEPALIVE, keepAlive);
611661 Boolean reuseAddress = options.getReuseAddress();
612662 if (reuseAddress != null)
613- b.setOption("reuseAddress", reuseAddress);
663+ b.option(ChannelOption.SO_REUSEADDR, reuseAddress);
614664 Integer soLinger = options.getSoLinger();
615665 if (soLinger != null)
616- b.setOption("soLinger", soLinger);
666+ b.option(ChannelOption.SO_LINGER, soLinger);
617667 Boolean tcpNoDelay = options.getTcpNoDelay();
618668 if (tcpNoDelay != null)
619- b.setOption("tcpNoDelay", tcpNoDelay);
669+ b.option(ChannelOption.TCP_NODELAY, tcpNoDelay);
620670 Integer receiveBufferSize = options.getReceiveBufferSize();
621671 if (receiveBufferSize != null)
622- b.setOption("receiveBufferSize", receiveBufferSize);
672+ b.option(ChannelOption.SO_RCVBUF, receiveBufferSize);
623673 Integer sendBufferSize = options.getSendBufferSize();
624674 if (sendBufferSize != null)
625- b.setOption("sendBufferSize", sendBufferSize);
675+ b.option(ChannelOption.SO_SNDBUF, sendBufferSize);
626676
627677 return b;
628678 }
@@ -635,14 +685,98 @@
635685 // we're not on an I/O thread or anything, so just call await.
636686 allChannels.close().awaitUninterruptibly();
637687
638- // This will call shutdownNow on the boss and worker executor. Since this is called
639- // only once all connection have been individually closed, it's fine.
640- channelFactory.releaseExternalResources();
688+ // This will shut down I/O threads. Since this is called only once all connection have
689+ // been individually closed, it's fine.
690+ eventLoopGroup.shutdownGracefully().syncUninterruptibly();
641691 timer.stop();
642692 }
643693 }
644694
645- private class Dispatcher extends IdleStateAwareChannelUpstreamHandler {
695+ private static final class Flusher implements Runnable {
696+ final EventLoop eventLoop;
697+ final Queue<FlushItem> queued = new ConcurrentLinkedQueue<FlushItem>();
698+ final AtomicBoolean running = new AtomicBoolean(false);
699+ final HashSet<Channel> channels = new HashSet<Channel>();
700+ final List<FlushItem> flushed = Lists.newArrayListWithExpectedSize(50);
701+ int runsSinceFlush = 0;
702+ int runsWithNoWork = 0;
703+
704+ private Flusher(EventLoop eventLoop) {
705+ this.eventLoop = eventLoop;
706+ }
707+
708+ void start() {
709+ if (!running.get() && running.compareAndSet(false, true)) {
710+ this.eventLoop.execute(this);
711+ }
712+ }
713+
714+ @Override
715+ public void run() {
716+
717+ boolean doneWork = false;
718+ FlushItem flush;
719+ while (null != (flush = queued.poll())) {
720+ channels.add(flush.channel);
721+ flush.channel.write(flush.request).addListener(flush.listener);
722+ flushed.add(flush);
723+ doneWork = true;
724+ }
725+
726+ runsSinceFlush++;
727+
728+ if (!doneWork || runsSinceFlush > 2 || flushed.size() > 50) {
729+ for (Channel channel : channels)
730+ channel.flush();
731+
732+ channels.clear();
733+ flushed.clear();
734+ runsSinceFlush = 0;
735+ }
736+
737+ if (doneWork) {
738+ runsWithNoWork = 0;
739+ } else {
740+ // either reschedule or cancel
741+ if (++runsWithNoWork > 5) {
742+ running.set(false);
743+ if (queued.isEmpty() || !running.compareAndSet(false, true))
744+ return;
745+ }
746+ }
747+
748+ eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
749+ }
750+ }
751+
752+ private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new ConcurrentHashMap<EventLoop, Flusher>();
753+
754+ private static class FlushItem {
755+ final Channel channel;
756+ final Object request;
757+ final ChannelFutureListener listener;
758+
759+ private FlushItem(Channel channel, Object request, ChannelFutureListener listener) {
760+ this.channel = channel;
761+ this.request = request;
762+ this.listener = listener;
763+ }
764+ }
765+
766+ private void flush(FlushItem item) {
767+ EventLoop loop = item.channel.eventLoop();
768+ Flusher flusher = flusherLookup.get(loop);
769+ if (flusher == null) {
770+ Flusher alt = flusherLookup.putIfAbsent(loop, flusher = new Flusher(loop));
771+ if (alt != null)
772+ flusher = alt;
773+ }
774+
775+ flusher.queued.add(item);
776+ flusher.start();
777+ }
778+
779+ private class Dispatcher extends SimpleChannelInboundHandler<Message.Response> {
646780
647781 public final StreamIdGenerator streamIdHandler = new StreamIdGenerator();
648782 private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>();
@@ -679,54 +813,49 @@
679813 }
680814
681815 @Override
682- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
683- if (!(e.getMessage() instanceof Message.Response)) {
684- String msg = asDebugString(e.getMessage());
685- logger.error("{} Received unexpected message: {}", Connection.this, msg);
686- defunct(new TransportException(address, "Unexpected message received: " + msg));
687- } else {
688- Message.Response response = (Message.Response)e.getMessage();
689- int streamId = response.getStreamId();
816+ protected void channelRead0(ChannelHandlerContext ctx, Message.Response response) throws Exception {
817+ int streamId = response.getStreamId();
690818
691- logger.trace("{} received: {}", Connection.this, e.getMessage());
819+ logger.trace("{} received: {}", Connection.this, asDebugString(response));
692820
693- if (streamId < 0) {
694- factory.defaultHandler.handle(response);
695- return;
696- }
821+ if (streamId < 0) {
822+ factory.defaultHandler.handle(response);
823+ return;
824+ }
697825
698- ResponseHandler handler = pending.remove(streamId);
699- streamIdHandler.release(streamId);
700- if (handler == null) {
701- /**
702- * During normal operation, we should not receive responses for which we don't have a handler. There is
703- * two cases however where this can happen:
704- * 1) The connection has been defuncted due to some internal error and we've raced between removing the
705- * handler and actually closing the connection; since the original error has been logged, we're fine
706- * ignoring this completely.
707- * 2) This request has timed out. In that case, we've already switched to another host (or errored out
708- * to the user). So log it for debugging purpose, but it's fine ignoring otherwise.
709- */
710- streamIdHandler.unmark(streamId);
711- if (logger.isDebugEnabled())
712- logger.debug("{} Response received on stream {} but no handler set anymore (either the request has "
713- + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
714- return;
715- }
716- handler.cancelTimeout();
717- handler.callback.onSet(Connection.this, response, System.nanoTime() - handler.startTime, handler.retryCount);
718-
719- // If we happen to be closed and we're the last outstanding request, we need to terminate the connection
720- // (note: this is racy as the signaling can be called more than once, but that's not a problem)
721- if (isClosed())
722- tryTerminate(false);
826+ ResponseHandler handler = pending.remove(streamId);
827+ streamIdHandler.release(streamId);
828+ if (handler == null) {
829+ /**
830+ * During normal operation, we should not receive responses for which we don't have a handler. There is
831+ * two cases however where this can happen:
832+ * 1) The connection has been defuncted due to some internal error and we've raced between removing the
833+ * handler and actually closing the connection; since the original error has been logged, we're fine
834+ * ignoring this completely.
835+ * 2) This request has timed out. In that case, we've already switched to another host (or errored out
836+ * to the user). So log it for debugging purpose, but it's fine ignoring otherwise.
837+ */
838+ streamIdHandler.unmark(streamId);
839+ if (logger.isDebugEnabled())
840+ logger.debug("{} Response received on stream {} but no handler set anymore (either the request has "
841+ + "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
842+ return;
723843 }
844+ handler.cancelTimeout();
845+ handler.callback.onSet(Connection.this, response, System.nanoTime() - handler.startTime, handler.retryCount);
846+
847+ // If we happen to be closed and we're the last outstanding request, we need to terminate the connection
848+ // (note: this is racy as the signaling can be called more than once, but that's not a problem)
849+ if (isClosed())
850+ tryTerminate(false);
724851 }
725852
726853 @Override
727- public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
728- logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
729- write(HEARTBEAT_CALLBACK);
854+ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
855+ if (evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) {
856+ logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
857+ write(HEARTBEAT_CALLBACK);
858+ }
730859 }
731860
732861 // Make sure we don't print huge responses in debug/error logs.
@@ -742,15 +871,15 @@
742871 }
743872
744873 @Override
745- public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
874+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
746875 if (logger.isDebugEnabled())
747- logger.debug(String.format("%s connection error", Connection.this), e.getCause());
876+ logger.debug(String.format("%s connection error", Connection.this), cause);
748877
749878 // Ignore exception while writing, this will be handled by write() directly
750879 if (writer.get() > 0)
751880 return;
752881
753- defunct(new TransportException(address, String.format("Unexpected exception triggered (%s)", e.getCause()), e.getCause()));
882+ defunct(new TransportException(address, String.format("Unexpected exception triggered (%s)", cause), cause));
754883 }
755884
756885 public void errorOutAllHandler(ConnectionException ce) {
@@ -763,13 +892,15 @@
763892 iter.remove();
764893 }
765894 }
895+ }
766896
897+ private class ChannelCloseListener implements ChannelFutureListener {
767898 @Override
768- public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
899+ public void operationComplete(ChannelFuture future) throws Exception {
769900 // If we've closed the channel client side then we don't really want to defunct the connection, but
770901 // if there is remaining thread waiting on us, we still want to wake them up
771902 if (!isInitialized || isClosed()) {
772- errorOutAllHandler(new TransportException(address, "Channel has been closed"));
903+ dispatcher.errorOutAllHandler(new TransportException(address, "Channel has been closed"));
773904 // we still want to force so that the future completes
774905 Connection.this.closeAsync().force();
775906 } else
@@ -837,9 +968,9 @@
837968 future.addListener(new ChannelFutureListener() {
838969 public void operationComplete(ChannelFuture future) {
839970 factory.allChannels.remove(channel);
840- if (future.getCause() != null) {
841- logger.warn("Error closing channel", future.getCause());
842- ConnectionCloseFuture.this.setException(future.getCause());
971+ if (future.cause() != null) {
972+ logger.warn("Error closing channel", future.cause());
973+ ConnectionCloseFuture.this.setException(future.cause());
843974 } else
844975 ConnectionCloseFuture.this.set(null);
845976 }
@@ -972,7 +1103,7 @@
9721103 public void handle(Message.Response response);
9731104 }
9741105
975- private static class PipelineFactory implements ChannelPipelineFactory {
1106+ private static class Initializer extends ChannelInitializer<SocketChannel> {
9761107 // Stateless handlers
9771108 private static final Message.ProtocolDecoder messageDecoder = new Message.ProtocolDecoder();
9781109 private static final Message.ProtocolEncoder messageEncoderV1 = new Message.ProtocolEncoder(1);
@@ -985,28 +1116,27 @@
9851116 private final SSLOptions sslOptions;
9861117 private final ChannelHandler idleStateHandler;
9871118
988- public PipelineFactory(Connection connection, int protocolVersion, FrameCompressor compressor, SSLOptions sslOptions, int heartBeatIntervalSeconds, HashedWheelTimer timer) {
1119+ public Initializer(Connection connection, int protocolVersion, FrameCompressor compressor, SSLOptions sslOptions, int heartBeatIntervalSeconds) {
9891120 this.connection = connection;
9901121 this.protocolVersion = protocolVersion;
9911122 this.compressor = compressor;
9921123 this.sslOptions = sslOptions;
993- this.idleStateHandler = new IdleStateHandler(timer, 0, 0, heartBeatIntervalSeconds);
1124+ this.idleStateHandler = new IdleStateHandler(0, 0, heartBeatIntervalSeconds);
9941125 }
9951126
9961127 @Override
997- public ChannelPipeline getPipeline() throws Exception {
998- ChannelPipeline pipeline = Channels.pipeline();
1128+ protected void initChannel(SocketChannel channel) throws Exception {
1129+ ChannelPipeline pipeline = channel.pipeline();
9991130
10001131 if (sslOptions != null) {
10011132 SSLEngine engine = sslOptions.context.createSSLEngine();
10021133 engine.setUseClientMode(true);
10031134 engine.setEnabledCipherSuites(sslOptions.cipherSuites);
10041135 SslHandler handler = new SslHandler(engine);
1005- handler.setCloseOnSSLException(true);
10061136 pipeline.addLast("ssl", handler);
10071137 }
10081138
1009- //pipeline.addLast("debug", new LoggingHandler(InternalLogLevel.INFO));
1139+// pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO));
10101140
10111141 pipeline.addLast("frameDecoder", new Frame.Decoder());
10121142 pipeline.addLast("frameEncoder", frameEncoder);
@@ -1022,8 +1152,6 @@
10221152 pipeline.addLast("idleStateHandler", idleStateHandler);
10231153
10241154 pipeline.addLast("dispatcher", connection.dispatcher);
1025-
1026- return pipeline;
10271155 }
10281156 }
10291157 }
modified driver-core/src/main/java/com/datastax/driver/core/DataType.java +2 −2
@@ -24,7 +24,7 @@
2424 import com.google.common.base.Objects;
2525 import com.google.common.collect.ImmutableList;
2626 import com.google.common.collect.ImmutableSet;
27-import org.jboss.netty.buffer.ChannelBuffer;
27+import io.netty.buffer.ByteBuf;
2828
2929 import com.datastax.driver.core.exceptions.DriverInternalError;
3030 import com.datastax.driver.core.exceptions.InvalidTypeException;
@@ -171,7 +171,7 @@
171171 this.codec = codec;
172172 }
173173
174- static DataType decode(ChannelBuffer buffer) {
174+ static DataType decode(ByteBuf buffer) {
175175 Name name = Name.fromProtocolId(buffer.readUnsignedShort());
176176 switch (name) {
177177 case CUSTOM:
modified driver-core/src/main/java/com/datastax/driver/core/Frame.java +37 −48
@@ -15,25 +15,20 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.io.IOException;
1918 import java.util.EnumSet;
19+import java.util.List;
2020
21-import org.jboss.netty.buffer.ChannelBuffer;
22-import org.jboss.netty.buffer.ChannelBuffers;
23-import org.jboss.netty.channel.Channel;
24-import org.jboss.netty.channel.ChannelHandlerContext;
25-import org.jboss.netty.handler.codec.frame.CorruptedFrameException;
26-import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
27-import org.jboss.netty.handler.codec.frame.TooLongFrameException;
28-import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
29-import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
21+import io.netty.buffer.ByteBuf;
22+import io.netty.channel.ChannelHandler;
23+import io.netty.channel.ChannelHandlerContext;
24+import io.netty.handler.codec.*;
3025
3126 import com.datastax.driver.core.exceptions.DriverInternalError;
3227
3328 class Frame {
3429
3530 public final Header header;
36- public final ChannelBuffer body;
31+ public final ByteBuf body;
3732
3833 /**
3934 * On-wire frame.
@@ -46,12 +41,12 @@
4641 * | length |
4742 * +---------+---------+---------+---------+
4843 */
49- private Frame(Header header, ChannelBuffer body) {
44+ private Frame(Header header, ByteBuf body) {
5045 this.header = header;
5146 this.body = body;
5247 }
5348
54- private static Frame create(ChannelBuffer fullFrame) {
49+ private static Frame create(ByteBuf fullFrame) {
5550 assert fullFrame.readableBytes() >= Header.LENGTH : String.format("Frame too short (%d bytes)", fullFrame.readableBytes());
5651
5752 int version = fullFrame.readByte();
@@ -68,7 +63,7 @@
6863 return new Frame(header, fullFrame);
6964 }
7065
71- public static Frame create(int version, int opcode, int streamId, EnumSet<Header.Flag> flags, ChannelBuffer body) {
66+ public static Frame create(int version, int opcode, int streamId, EnumSet<Header.Flag> flags, ByteBuf body) {
7267 Header header = new Header(version, flags, streamId, opcode);
7368 return new Frame(header, body);
7469 }
@@ -118,7 +113,7 @@
118113 }
119114 }
120115
121- public Frame with(ChannelBuffer newBody) {
116+ public Frame with(ByteBuf newBody) {
122117 return new Frame(header, newBody);
123118 }
124119
@@ -131,7 +126,7 @@
131126 }
132127
133128 @Override
134- protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
129+ protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
135130 try {
136131 if (buffer.readableBytes() == 0)
137132 return null;
@@ -140,11 +135,12 @@
140135 if (buffer.readableBytes() >= 4)
141136 Message.Response.Type.fromOpcode(buffer.getByte(3));
142137
143- ChannelBuffer frame = (ChannelBuffer) super.decode(ctx, channel, buffer);
138+ ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);
144139 if (frame == null) {
145140 return null;
146141 }
147-
142+ // Do not deallocate `frame` just yet, because it is stored as Frame.body and will be used
143+ // in Message.ProtocolDecoder (we deallocate it there).
148144 return Frame.create(frame);
149145 } catch (CorruptedFrameException e) {
150146 throw new DriverInternalError(e.getMessage());
@@ -154,25 +150,25 @@
154150 }
155151 }
156152
157- public static class Encoder extends OneToOneEncoder {
158-
159- public Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws IOException {
160- assert msg instanceof Frame : "Expecting frame, got " + msg;
161-
162- Frame frame = (Frame)msg;
153+ @ChannelHandler.Sharable
154+ public static class Encoder extends MessageToMessageEncoder<Frame> {
163155
164- ChannelBuffer header = ChannelBuffers.buffer(Frame.Header.LENGTH);
156+ @Override
157+ protected void encode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
158+ ByteBuf header = ctx.alloc().ioBuffer(Frame.Header.LENGTH);
165159 // We don't bother with the direction, we only send requests.
166160 header.writeByte(frame.header.version);
167161 header.writeByte(Header.Flag.serialize(frame.header.flags));
168162 header.writeByte(frame.header.streamId);
169163 header.writeByte(frame.header.opcode);
170164 header.writeInt(frame.body.readableBytes());
171- return ChannelBuffers.wrappedBuffer(header, frame.body);
165+
166+ out.add(header);
167+ out.add(frame.body);
172168 }
173169 }
174170
175- public static class Decompressor extends OneToOneDecoder {
171+ public static class Decompressor extends MessageToMessageDecoder<Frame> {
176172
177173 private final FrameCompressor compressor;
178174
@@ -181,19 +177,15 @@
181177 this.compressor = compressor;
182178 }
183179
184- public Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws IOException {
185-
186- assert msg instanceof Frame : "Expecting frame, got " + msg;
187-
188- Frame frame = (Frame)msg;
189-
190- return frame.header.flags.contains(Header.Flag.COMPRESSED)
191- ? compressor.decompress(frame)
192- : frame;
180+ @Override
181+ protected void decode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
182+ out.add(frame.header.flags.contains(Header.Flag.COMPRESSED)
183+ ? compressor.decompress(frame)
184+ : frame);
193185 }
194186 }
195187
196- public static class Compressor extends OneToOneEncoder {
188+ public static class Compressor extends MessageToMessageEncoder<Frame> {
197189
198190 private final FrameCompressor compressor;
199191
@@ -202,18 +194,15 @@
202194 this.compressor = compressor;
203195 }
204196
205- public Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws IOException {
206-
207- assert msg instanceof Frame : "Expecting frame, got " + msg;
208-
209- Frame frame = (Frame)msg;
210-
197+ @Override
198+ protected void encode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
211199 // Never compress STARTUP messages
212- if (frame.header.opcode == Message.Request.Type.STARTUP.opcode)
213- return frame;
214-
215- frame.header.flags.add(Header.Flag.COMPRESSED);
216- return compressor.compress(frame);
200+ if (frame.header.opcode == Message.Request.Type.STARTUP.opcode) {
201+ out.add(frame);
202+ } else {
203+ frame.header.flags.add(Header.Flag.COMPRESSED);
204+ out.add(compressor.compress(frame));
205+ }
217206 }
218207 }
219208 }
modified driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java +5 −5
@@ -17,8 +17,8 @@
1717
1818 import java.io.IOException;
1919
20+import io.netty.buffer.Unpooled;
2021 import net.jpountz.lz4.LZ4Factory;
21-import org.jboss.netty.buffer.ChannelBuffers;
2222 import org.slf4j.Logger;
2323 import org.slf4j.LoggerFactory;
2424 import org.xerial.snappy.Snappy;
@@ -60,7 +60,7 @@
6060 byte[] output = new byte[Snappy.maxCompressedLength(input.length)];
6161
6262 int written = Snappy.compress(input, 0, input.length, output, 0);
63- return frame.with(ChannelBuffers.wrappedBuffer(output, 0, written));
63+ return frame.with(Unpooled.wrappedBuffer(output, 0, written));
6464 }
6565
6666 public Frame decompress(Frame frame) throws IOException {
@@ -71,7 +71,7 @@
7171
7272 byte[] output = new byte[Snappy.uncompressedLength(input)];
7373 int size = Snappy.uncompress(input, 0, input.length, output, 0);
74- return frame.with(ChannelBuffers.wrappedBuffer(output, 0, size));
74+ return frame.with(Unpooled.wrappedBuffer(output, 0, size));
7575 }
7676 }
7777
@@ -115,7 +115,7 @@
115115
116116 try {
117117 int written = compressor.compress(input, 0, input.length, output, INTEGER_BYTES, maxCompressedLength);
118- return frame.with(ChannelBuffers.wrappedBuffer(output, 0, INTEGER_BYTES + written));
118+ return frame.with(Unpooled.wrappedBuffer(output, 0, INTEGER_BYTES + written));
119119 } catch (Exception e) {
120120 throw new IOException(e);
121121 }
@@ -136,7 +136,7 @@
136136 if (read != input.length - INTEGER_BYTES)
137137 throw new IOException("Compressed lengths mismatch");
138138
139- return frame.with(ChannelBuffers.wrappedBuffer(output));
139+ return frame.with(Unpooled.wrappedBuffer(output));
140140 } catch (Exception e) {
141141 throw new IOException(e);
142142 }
modified driver-core/src/main/java/com/datastax/driver/core/Message.java +24 −23
@@ -16,14 +16,14 @@
1616 package com.datastax.driver.core;
1717
1818 import java.util.EnumSet;
19+import java.util.List;
1920 import java.util.UUID;
2021
21-import org.jboss.netty.buffer.ChannelBuffer;
22-import org.jboss.netty.buffer.ChannelBuffers;
23-import org.jboss.netty.channel.Channel;
24-import org.jboss.netty.channel.ChannelHandlerContext;
25-import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
26-import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
22+import io.netty.buffer.ByteBuf;
23+import io.netty.channel.ChannelHandler;
24+import io.netty.channel.ChannelHandlerContext;
25+import io.netty.handler.codec.MessageToMessageDecoder;
26+import io.netty.handler.codec.MessageToMessageEncoder;
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
2929
@@ -37,12 +37,12 @@
3737 protected static final Logger logger = LoggerFactory.getLogger(Message.class);
3838
3939 public interface Coder<R extends Request> {
40- public void encode(R request, ChannelBuffer dest);
40+ public void encode(R request, ByteBuf dest);
4141 public int encodedSize(R request);
4242 }
4343
4444 public interface Decoder<R extends Response> {
45- public R decode(ChannelBuffer body);
45+ public R decode(ByteBuf body);
4646 }
4747
4848 private volatile int streamId;
@@ -170,21 +170,25 @@
170170 }
171171 }
172172
173- public static class ProtocolDecoder extends OneToOneDecoder {
173+ @ChannelHandler.Sharable
174+ public static class ProtocolDecoder extends MessageToMessageDecoder<Frame> {
174175
175- public Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) {
176- assert msg instanceof Frame : "Expecting frame, got " + msg;
177-
178- Frame frame = (Frame)msg;
176+ @Override
177+ protected void decode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
179178 boolean isTracing = frame.header.flags.contains(Frame.Header.Flag.TRACING);
180179 UUID tracingId = isTracing ? CBUtil.readUUID(frame.body) : null;
181180
182181 Response response = Response.Type.fromOpcode(frame.header.opcode).decoder(frame.header.version).decode(frame.body);
183- return response.setTracingId(tracingId).setStreamId(frame.header.streamId);
182+ frame.body.release();
183+
184+ response.setTracingId(tracingId).setStreamId(frame.header.streamId);
185+
186+ out.add(response);
184187 }
185188 }
186189
187- public static class ProtocolEncoder extends OneToOneEncoder {
190+ @ChannelHandler.Sharable
191+ public static class ProtocolEncoder extends MessageToMessageEncoder<Request> {
188192
189193 private final int protocolVersion;
190194
@@ -192,21 +196,18 @@
192196 this.protocolVersion = version;
193197 }
194198
195- @SuppressWarnings("unchecked")
196- public Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) {
197- assert msg instanceof Request : "Expecting request, got " + msg;
198-
199- Request request = (Request)msg;
200-
199+ @Override
200+ protected void encode(ChannelHandlerContext ctx, Request request, List<Object> out) throws Exception {
201201 EnumSet<Frame.Header.Flag> flags = EnumSet.noneOf(Frame.Header.Flag.class);
202202 if (request.isTracingRequested())
203203 flags.add(Frame.Header.Flag.TRACING);
204204
205+ @SuppressWarnings("unchecked")
205206 Coder<Request> coder = (Coder<Request>)request.type.coder(protocolVersion);
206- ChannelBuffer body = ChannelBuffers.buffer(coder.encodedSize(request));
207+ ByteBuf body = ctx.alloc().buffer(coder.encodedSize(request));
207208 coder.encode(request, body);
208209
209- return Frame.create(protocolVersion, request.type.opcode, request.getStreamId(), flags, body);
210+ out.add(Frame.create(protocolVersion, request.type.opcode, request.getStreamId(), flags, body));
210211 }
211212 }
212213 }
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolEvent.java +16 −16
@@ -17,7 +17,7 @@
1717
1818 import java.net.InetSocketAddress;
1919
20-import org.jboss.netty.buffer.ChannelBuffer;
20+import io.netty.buffer.ByteBuf;
2121
2222 class ProtocolEvent {
2323
@@ -29,14 +29,14 @@
2929 this.type = type;
3030 }
3131
32- public static ProtocolEvent deserialize(ChannelBuffer cb) {
33- switch (CBUtil.readEnumValue(Type.class, cb)) {
32+ public static ProtocolEvent deserialize(ByteBuf bb) {
33+ switch (CBUtil.readEnumValue(Type.class, bb)) {
3434 case TOPOLOGY_CHANGE:
35- return TopologyChange.deserializeEvent(cb);
35+ return TopologyChange.deserializeEvent(bb);
3636 case STATUS_CHANGE:
37- return StatusChange.deserializeEvent(cb);
37+ return StatusChange.deserializeEvent(bb);
3838 case SCHEMA_CHANGE:
39- return SchemaChange.deserializeEvent(cb);
39+ return SchemaChange.deserializeEvent(bb);
4040 }
4141 throw new AssertionError();
4242 }
@@ -54,9 +54,9 @@
5454 }
5555
5656 // Assumes the type has already been deserialized
57- private static TopologyChange deserializeEvent(ChannelBuffer cb) {
58- Change change = CBUtil.readEnumValue(Change.class, cb);
59- InetSocketAddress node = CBUtil.readInet(cb);
57+ private static TopologyChange deserializeEvent(ByteBuf bb) {
58+ Change change = CBUtil.readEnumValue(Change.class, bb);
59+ InetSocketAddress node = CBUtil.readInet(bb);
6060 return new TopologyChange(change, node);
6161 }
6262
@@ -80,9 +80,9 @@
8080 }
8181
8282 // Assumes the type has already been deserialized
83- private static StatusChange deserializeEvent(ChannelBuffer cb) {
84- Status status = CBUtil.readEnumValue(Status.class, cb);
85- InetSocketAddress node = CBUtil.readInet(cb);
83+ private static StatusChange deserializeEvent(ByteBuf bb) {
84+ Status status = CBUtil.readEnumValue(Status.class, bb);
85+ InetSocketAddress node = CBUtil.readInet(bb);
8686 return new StatusChange(status, node);
8787 }
8888
@@ -108,10 +108,10 @@
108108 }
109109
110110 // Assumes the type has already been deserialized
111- private static SchemaChange deserializeEvent(ChannelBuffer cb) {
112- Change change = CBUtil.readEnumValue(Change.class, cb);
113- String keyspace = CBUtil.readString(cb);
114- String table = CBUtil.readString(cb);
111+ private static SchemaChange deserializeEvent(ByteBuf bb) {
112+ Change change = CBUtil.readEnumValue(Change.class, bb);
113+ String keyspace = CBUtil.readString(bb);
114+ String table = CBUtil.readString(bb);
115115 return new SchemaChange(change, keyspace, table);
116116 }
117117
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +13 −13
@@ -22,7 +22,7 @@
2222 import java.util.Map;
2323
2424 import com.google.common.collect.ImmutableMap;
25-import org.jboss.netty.buffer.ChannelBuffer;
25+import io.netty.buffer.ByteBuf;
2626
2727 class Requests {
2828
@@ -35,7 +35,7 @@
3535 public static final String COMPRESSION_OPTION = "COMPRESSION";
3636
3737 public static final Message.Coder<Startup> coder = new Message.Coder<Startup>() {
38- public void encode(Startup msg, ChannelBuffer dest) {
38+ public void encode(Startup msg, ByteBuf dest) {
3939 CBUtil.writeStringMap(msg.options, dest);
4040 }
4141
@@ -67,7 +67,7 @@
6767
6868 public static final Message.Coder<Credentials> coder = new Message.Coder<Credentials>() {
6969
70- public void encode(Credentials msg, ChannelBuffer dest) {
70+ public void encode(Credentials msg, ByteBuf dest) {
7171 CBUtil.writeStringMap(msg.credentials, dest);
7272 }
7373
@@ -88,7 +88,7 @@
8888
8989 public static final Message.Coder<Options> coder = new Message.Coder<Options>()
9090 {
91- public void encode(Options msg, ChannelBuffer dest) {}
91+ public void encode(Options msg, ByteBuf dest) {}
9292
9393 public int encodedSize(Options msg) {
9494 return 0;
@@ -108,7 +108,7 @@
108108 public static class Query extends Message.Request {
109109
110110 public static final Message.Coder<Query> coderV1 = new Message.Coder<Query>() {
111- public void encode(Query msg, ChannelBuffer dest) {
111+ public void encode(Query msg, ByteBuf dest) {
112112 CBUtil.writeLongString(msg.query, dest);
113113 CBUtil.writeConsistencyLevel(msg.options.consistency, dest);
114114 }
@@ -120,7 +120,7 @@
120120 };
121121
122122 public static final Message.Coder<Query> coderV2 = new Message.Coder<Query>() {
123- public void encode(Query msg, ChannelBuffer dest) {
123+ public void encode(Query msg, ByteBuf dest) {
124124 CBUtil.writeLongString(msg.query, dest);
125125 msg.options.encode(dest);
126126 }
@@ -153,7 +153,7 @@
153153 public static class Execute extends Message.Request {
154154
155155 public static final Message.Coder<Execute> coderV1 = new Message.Coder<Execute>() {
156- public void encode(Execute msg, ChannelBuffer dest) {
156+ public void encode(Execute msg, ByteBuf dest) {
157157 CBUtil.writeBytes(msg.statementId.bytes, dest);
158158 CBUtil.writeValueList(msg.options.values, dest);
159159 CBUtil.writeConsistencyLevel(msg.options.consistency, dest);
@@ -167,7 +167,7 @@
167167 };
168168
169169 public static final Message.Coder<Execute> coderV2 = new Message.Coder<Execute>() {
170- public void encode(Execute msg, ChannelBuffer dest) {
170+ public void encode(Execute msg, ByteBuf dest) {
171171 CBUtil.writeBytes(msg.statementId.bytes, dest);
172172 msg.options.encode(dest);
173173 }
@@ -264,7 +264,7 @@
264264 flags.add(Flag.SERIAL_CONSISTENCY);
265265 }
266266
267- public void encode(ChannelBuffer dest) {
267+ public void encode(ByteBuf dest) {
268268 CBUtil.writeConsistencyLevel(consistency, dest);
269269
270270 dest.writeByte((byte)Flag.serialize(flags));
@@ -302,7 +302,7 @@
302302 public static class Batch extends Message.Request {
303303
304304 public static final Message.Coder<Batch> coder = new Message.Coder<Batch>() {
305- public void encode(Batch msg, ChannelBuffer dest) {
305+ public void encode(Batch msg, ByteBuf dest) {
306306 int queries = msg.queryOrIdList.size();
307307 assert queries <= 0xFFFF;
308308
@@ -377,7 +377,7 @@
377377
378378 public static final Message.Coder<Prepare> coder = new Message.Coder<Prepare>() {
379379
380- public void encode(Prepare msg, ChannelBuffer dest) {
380+ public void encode(Prepare msg, ByteBuf dest) {
381381 CBUtil.writeLongString(msg.query, dest);
382382 }
383383
@@ -402,7 +402,7 @@
402402 public static class Register extends Message.Request {
403403
404404 public static final Message.Coder<Register> coder = new Message.Coder<Register>() {
405- public void encode(Register msg, ChannelBuffer dest) {
405+ public void encode(Register msg, ByteBuf dest) {
406406 dest.writeShort(msg.eventTypes.size());
407407 for (ProtocolEvent.Type type : msg.eventTypes)
408408 CBUtil.writeEnumValue(type, dest);
@@ -433,7 +433,7 @@
433433
434434 public static final Message.Coder<AuthResponse> coder = new Message.Coder<AuthResponse>() {
435435
436- public void encode(AuthResponse response, ChannelBuffer dest) {
436+ public void encode(AuthResponse response, ByteBuf dest) {
437437 CBUtil.writeValue(response.token, dest);
438438 }
439439
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +17 −18
@@ -18,9 +18,8 @@
1818 import java.net.InetSocketAddress;
1919 import java.nio.ByteBuffer;
2020 import java.util.*;
21-import java.util.concurrent.LinkedBlockingQueue;
2221
23-import org.jboss.netty.buffer.ChannelBuffer;
22+import io.netty.buffer.ByteBuf;
2423
2524 import com.datastax.driver.core.exceptions.*;
2625 import com.datastax.driver.core.utils.Bytes;
@@ -33,7 +32,7 @@
3332
3433 public static final Message.Decoder<Error> decoder = new Message.Decoder<Error>() {
3534 @Override
36- public Error decode(ChannelBuffer body) {
35+ public Error decode(ByteBuf body) {
3736 ExceptionCode code = ExceptionCode.fromValue(body.readInt());
3837 String msg = CBUtil.readString(body);
3938 Object infos = null;
@@ -111,7 +110,7 @@
111110 public static class Ready extends Message.Response {
112111
113112 public static final Message.Decoder<Ready> decoder = new Message.Decoder<Ready>() {
114- public Ready decode(ChannelBuffer body) {
113+ public Ready decode(ByteBuf body) {
115114 // TODO: Would it be cool to return a singleton? Check we don't need to
116115 // set the streamId or something
117116 return new Ready();
@@ -131,7 +130,7 @@
131130 public static class Authenticate extends Message.Response {
132131
133132 public static final Message.Decoder<Authenticate> decoder = new Message.Decoder<Authenticate>() {
134- public Authenticate decode(ChannelBuffer body) {
133+ public Authenticate decode(ByteBuf body) {
135134 String authenticator = CBUtil.readString(body);
136135 return new Authenticate(authenticator);
137136 }
@@ -153,7 +152,7 @@
153152 public static class Supported extends Message.Response {
154153
155154 public static final Message.Decoder<Supported> decoder = new Message.Decoder<Supported>() {
156- public Supported decode(ChannelBuffer body) {
155+ public Supported decode(ByteBuf body) {
157156 return new Supported(CBUtil.readStringToStringListMap(body));
158157 }
159158 };
@@ -189,14 +188,14 @@
189188 public static abstract class Result extends Message.Response {
190189
191190 public static final Message.Decoder<Result> decoderV1 = new Message.Decoder<Result>() {
192- public Result decode(ChannelBuffer body) {
191+ public Result decode(ByteBuf body) {
193192 Kind kind = Kind.fromId(body.readInt());
194193 return kind.subDecoderV1.decode(body);
195194 }
196195 };
197196
198197 public static final Message.Decoder<Result> decoderV2 = new Message.Decoder<Result>() {
199- public Result decode(ChannelBuffer body) {
198+ public Result decode(ByteBuf body) {
200199 Kind kind = Kind.fromId(body.readInt());
201200 return kind.subDecoderV2.decode(body);
202201 }
@@ -255,7 +254,7 @@
255254 }
256255
257256 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
258- public Result decode(ChannelBuffer body) {
257+ public Result decode(ByteBuf body) {
259258 return new Void();
260259 }
261260 };
@@ -275,7 +274,7 @@
275274 }
276275
277276 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
278- public Result decode(ChannelBuffer body) {
277+ public Result decode(ByteBuf body) {
279278 return new SetKeyspace(CBUtil.readString(body));
280279 }
281280 };
@@ -327,7 +326,7 @@
327326 this.pagingState = pagingState;
328327 }
329328
330- public static Metadata decode(ChannelBuffer body) {
329+ public static Metadata decode(ByteBuf body) {
331330
332331 // flags & column count
333332 EnumSet<Flag> flags = Flag.deserialize(body.readInt());
@@ -381,7 +380,7 @@
381380 }
382381
383382 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
384- public Result decode(ChannelBuffer body) {
383+ public Result decode(ByteBuf body) {
385384
386385 Metadata metadata = Metadata.decode(body);
387386
@@ -436,7 +435,7 @@
436435 public static class Prepared extends Result {
437436
438437 public static final Message.Decoder<Result> subcodecV1 = new Message.Decoder<Result>() {
439- public Result decode(ChannelBuffer body) {
438+ public Result decode(ByteBuf body) {
440439 MD5Digest id = MD5Digest.wrap(CBUtil.readBytes(body));
441440 Rows.Metadata metadata = Rows.Metadata.decode(body);
442441 return new Prepared(id, metadata, Rows.Metadata.EMPTY);
@@ -444,7 +443,7 @@
444443 };
445444
446445 public static final Message.Decoder<Result> subcodecV2 = new Message.Decoder<Result>() {
447- public Result decode(ChannelBuffer body) {
446+ public Result decode(ByteBuf body) {
448447 MD5Digest id = MD5Digest.wrap(CBUtil.readBytes(body));
449448 Rows.Metadata metadata = Rows.Metadata.decode(body);
450449 Rows.Metadata resultMetadata = Rows.Metadata.decode(body);
@@ -478,7 +477,7 @@
478477 public final String columnFamily;
479478
480479 public static final Message.Decoder<Result> subcodec = new Message.Decoder<Result>() {
481- public Result decode(ChannelBuffer body)
480+ public Result decode(ByteBuf body)
482481 {
483482 Change change = CBUtil.readEnumValue(Change.class, body);
484483 String keyspace = CBUtil.readString(body);
@@ -504,7 +503,7 @@
504503 public static class Event extends Message.Response {
505504
506505 public static final Message.Decoder<Event> decoder = new Message.Decoder<Event>() {
507- public Event decode(ChannelBuffer body) {
506+ public Event decode(ByteBuf body) {
508507 return new Event(ProtocolEvent.deserialize(body));
509508 }
510509 };
@@ -525,7 +524,7 @@
525524 public static class AuthChallenge extends Message.Response {
526525
527526 public static final Message.Decoder<AuthChallenge> decoder = new Message.Decoder<AuthChallenge>() {
528- public AuthChallenge decode(ChannelBuffer body) {
527+ public AuthChallenge decode(ByteBuf body) {
529528 ByteBuffer b = CBUtil.readValue(body);
530529 if (b == null)
531530 return new AuthChallenge(null);
@@ -547,7 +546,7 @@
547546 public static class AuthSuccess extends Message.Response {
548547
549548 public static final Message.Decoder<AuthSuccess> decoder = new Message.Decoder<AuthSuccess>() {
550- public AuthSuccess decode(ChannelBuffer body) {
549+ public AuthSuccess decode(ByteBuf body) {
551550 ByteBuffer b = CBUtil.readValue(body);
552551 if (b == null)
553552 return new AuthSuccess(null);
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +106 −1
@@ -45,7 +45,7 @@
4545 private volatile Boolean keepAlive;
4646 private volatile Boolean reuseAddress;
4747 private volatile Integer soLinger;
48- private volatile Boolean tcpNoDelay;
48+ private volatile Boolean tcpNoDelay = Boolean.TRUE;
4949 private volatile Integer receiveBufferSize;
5050 private volatile Integer sendBufferSize;
5151
@@ -131,55 +131,160 @@
131131 return this;
132132 }
133133
134+ /**
135+ * Returns whether TCP keepalive is enabled.
136+ *
137+ * @return the value of the option, or {@code null} if it is not set.
138+ * @see #setKeepAlive(boolean)
139+ */
134140 public Boolean getKeepAlive() {
135141 return keepAlive;
136142 }
137143
144+ /**
145+ * Sets whether to enable TCP keepalive.
146+ * <p>
147+ * By default, this option is not set by the driver. The actual value will be the default
148+ * from the underlying Netty transport (Java NIO or native epoll).
149+ *
150+ * @param keepAlive whether to enable or disable the option.
151+ * @return this {@code SocketOptions}.
152+ *
153+ * @see java.net.SocketOptions#TCP_NODELAY
154+ */
138155 public SocketOptions setKeepAlive(boolean keepAlive) {
139156 this.keepAlive = keepAlive;
140157 return this;
141158 }
142159
160+ /**
161+ * Returns whether reuse-address is enabled.
162+ *
163+ * @return the value of the option, or {@code null} if it is not set.
164+ * @see #setReuseAddress(boolean)
165+ */
143166 public Boolean getReuseAddress() {
144167 return reuseAddress;
145168 }
146169
170+ /**
171+ * Sets whether to enable reuse-address.
172+ * <p>
173+ * By default, this option is not set by the driver. The actual value will be the default
174+ * from the underlying Netty transport (Java NIO or native epoll).
175+ *
176+ * @param reuseAddress whether to enable or disable the option.
177+ * @return this {@code SocketOptions}.
178+ *
179+ * @see java.net.SocketOptions#SO_REUSEADDR
180+ */
147181 public SocketOptions setReuseAddress(boolean reuseAddress) {
148182 this.reuseAddress = reuseAddress;
149183 return this;
150184 }
151185
186+ /**
187+ * Returns the linger-on-close timeout.
188+ *
189+ * @return the value of the option, or {@code null} if it is not set.
190+ *
191+ * @see #setSoLinger(int)
192+ */
152193 public Integer getSoLinger() {
153194 return soLinger;
154195 }
155196
197+ /**
198+ * Sets the linger-on-close timeout.
199+ * <p>
200+ * By default, this option is not set by the driver. The actual value will be the default
201+ * from the underlying Netty transport (Java NIO or native epoll).
202+
203+ * @param soLinger the new value.
204+ * @return this {@code SocketOptions}.
205+ *
206+ * @see java.net.SocketOptions#SO_LINGER
207+ */
156208 public SocketOptions setSoLinger(int soLinger) {
157209 this.soLinger = soLinger;
158210 return this;
159211 }
160212
213+ /**
214+ * Returns whether Nagle's algorithm is disabled.
215+ *
216+ * @return the value of the option ({@code true} means Nagle is disabled), or {@code null} if it is not set.
217+ *
218+ * @see #setTcpNoDelay(boolean)
219+ */
161220 public Boolean getTcpNoDelay() {
162221 return tcpNoDelay;
163222 }
164223
224+ /**
225+ * Sets whether to disable Nagle's algorithm.
226+ * <p>
227+ * By default, this option is set to {@code true} (Nagle disabled).
228+ *
229+ * @param tcpNoDelay whether to enable or disable the option.
230+ * @return this {@code SocketOptions}.
231+ *
232+ * @see java.net.SocketOptions#TCP_NODELAY
233+ */
165234 public SocketOptions setTcpNoDelay(boolean tcpNoDelay) {
166235 this.tcpNoDelay = tcpNoDelay;
167236 return this;
168237 }
169238
239+ /**
240+ * Returns the hint to the size of the underlying buffers for incoming network I/O.
241+ *
242+ * @return the value of the option, or {@code null} if it is not set.
243+ *
244+ * @see #setReceiveBufferSize(int)
245+ */
170246 public Integer getReceiveBufferSize() {
171247 return receiveBufferSize;
172248 }
173249
250+ /**
251+ * Sets a hint to the size of the underlying buffers for incoming network I/O.
252+ * <p>
253+ * By default, this option is not set by the driver. The actual value will be the default
254+ * from the underlying Netty transport (Java NIO or native epoll).
255+ *
256+ * @param receiveBufferSize the new value.
257+ * @return this {@code SocketOptions}.
258+ *
259+ * @see java.net.SocketOptions#SO_RCVBUF
260+ */
174261 public SocketOptions setReceiveBufferSize(int receiveBufferSize) {
175262 this.receiveBufferSize = receiveBufferSize;
176263 return this;
177264 }
178265
266+ /**
267+ * Returns the hint to the size of the underlying buffers for outgoing network I/O.
268+ *
269+ * @return the value of the option, or {@code null} if it is not set.
270+ *
271+ * @see #setSendBufferSize(int)
272+ */
179273 public Integer getSendBufferSize() {
180274 return sendBufferSize;
181275 }
182276
277+ /**
278+ * Sets a hint to the size of the underlying buffers for outgoing network I/O.
279+ * <p>
280+ * By default, this option is not set by the driver. The actual value will be the default
281+ * from the underlying Netty transport (Java NIO or native epoll).
282+ *
283+ * @param sendBufferSize the new value.
284+ * @return this {@code SocketOptions}.
285+ *
286+ * @see java.net.SocketOptions#SO_SNDBUF
287+ */
183288 public SocketOptions setSendBufferSize(int sendBufferSize) {
184289 this.sendBufferSize = sendBufferSize;
185290 return this;
modified driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java +16 −0
@@ -26,4 +26,20 @@
2626 return defaultValue;
2727 }
2828 }
29+
30+ static boolean getBoolean(String key, boolean defaultValue) {
31+ String stringValue = System.getProperty(key);
32+ if (stringValue == null) {
33+ logger.debug("{} is undefined, using default value {}", key, defaultValue);
34+ return defaultValue;
35+ }
36+ try {
37+ boolean value = Boolean.parseBoolean(stringValue);
38+ logger.warn("{} is defined, using value {}", key, value);
39+ return value;
40+ } catch (NumberFormatException e) {
41+ logger.warn("{} is defined but could not parse value {}, using default value {}", key, stringValue, defaultValue);
42+ return defaultValue;
43+ }
44+ }
2945 }
modified driver-examples/osgi/README.rst +1 −1
@@ -12,7 +12,7 @@
1212
1313 To build the bundle and run tests execute the following maven task::
1414
15- mvn test -P short
15+ mvn integration-test -P short
1616
1717 The short profile needs to be activated since the tests run under
1818 this group.
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceIT.java +19 −7
@@ -57,8 +57,20 @@
5757 return mavenBundle("com.google.guava", "guava", "14.0.1");
5858 }
5959
60- private MavenArtifactProvisionOption nettyBundle() {
61- return mavenBundle("io.netty", "netty", "3.9.0.Final");
60+ private CompositeOption nettyBundles() {
61+ final String nettyVersion = "4.0.26.Final";
62+ return new CompositeOption() {
63+
64+ @Override public Option[] getOptions() {
65+ return options(
66+ mavenBundle("io.netty", "netty-buffer", nettyVersion),
67+ mavenBundle("io.netty", "netty-codec", nettyVersion),
68+ mavenBundle("io.netty", "netty-common", nettyVersion),
69+ mavenBundle("io.netty", "netty-handler", nettyVersion),
70+ mavenBundle("io.netty", "netty-transport", nettyVersion)
71+ );
72+ }
73+ };
6274 }
6375
6476 private CompositeOption defaultOptions() {
@@ -92,7 +104,7 @@
92104 return options(
93105 driverBundle(),
94106 guavaBundle(),
95- nettyBundle(),
107+ nettyBundles(),
96108 defaultOptions()
97109 );
98110 }
@@ -101,7 +113,7 @@
101113 public Option[] guava15Config() {
102114 return options(
103115 driverBundle(),
104- nettyBundle(),
116+ nettyBundles(),
105117 guavaBundle().version("15.0"),
106118 defaultOptions()
107119 );
@@ -111,7 +123,7 @@
111123 public Option[] guava16Config() {
112124 return options(
113125 driverBundle(),
114- nettyBundle(),
126+ nettyBundles(),
115127 guavaBundle().version("16.0.1"),
116128 defaultOptions()
117129 );
@@ -121,7 +133,7 @@
121133 public Option[] guava17Config() {
122134 return options(
123135 driverBundle(),
124- nettyBundle(),
136+ nettyBundles(),
125137 guavaBundle().version("17.0"),
126138 defaultOptions()
127139 );
@@ -131,7 +143,7 @@
131143 public Option[] guava18Config() {
132144 return options(
133145 driverBundle(),
134- nettyBundle(),
146+ nettyBundles(),
135147 guavaBundle().version("18.0"),
136148 defaultOptions()
137149 );
modified pom.xml +1 −1
@@ -46,7 +46,7 @@
4646 Check with the spark-cassandra-connector team before upgrading this.
4747 -->
4848 <guava.version>14.0.1</guava.version>
49- <netty.version>3.9.0.Final</netty.version>
49+ <netty.version>4.0.26.Final</netty.version>
5050 <metrics.version>3.0.2</metrics.version>
5151 <snappy.version>1.0.5</snappy.version>
5252 <lz4.version>1.2.0</lz4.version>