Elffuss BraidHub

kikocis/java-driver public

Use interfaces for most main object to faciliate testing/mocking

JAVA-195 #fixes
Changesetaf8838cdacbad2dea109d9ea59dfa00a0eccbdc0af8194c378e1965a239752a7
AuthorSylvain Lebresne <sylvain@datastax.com> · 2013-12-11 10:51 +01:00
CommitterSylvain Lebresne <sylvain@datastax.com> · 2013-12-11 15:40 +01:00
Parents62f5643cc71a

Browse the files at this changeset

18 files changed

added driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +130 −0
@@ -0,0 +1,130 @@
1+/*
2+ * Copyright (C) 2012 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.nio.ByteBuffer;
19+import java.util.*;
20+
21+import org.apache.cassandra.transport.messages.ResultMessage;
22+
23+import org.slf4j.Logger;
24+import org.slf4j.LoggerFactory;
25+
26+/**
27+ * Default implementation of a result set, backed by an ArrayDeque of ArrayList.
28+ */
29+class ArrayBackedResultSet implements ResultSet {
30+
31+ private static final Logger logger = LoggerFactory.getLogger(ResultSet.class);
32+
33+ private static final Queue<List<ByteBuffer>> EMPTY_QUEUE = new ArrayDeque<List<ByteBuffer>>(0);
34+
35+ private final ColumnDefinitions metadata;
36+ private final Queue<List<ByteBuffer>> rows;
37+ private final ExecutionInfo info;
38+
39+ private ArrayBackedResultSet(ColumnDefinitions metadata, Queue<List<ByteBuffer>> rows, ExecutionInfo info) {
40+ this.metadata = metadata;
41+ this.rows = rows;
42+ this.info = info;
43+ }
44+
45+ static ResultSet fromMessage(ResultMessage msg, SessionManager session, ExecutionInfo info) {
46+
47+ UUID tracingId = msg.getTracingId();
48+ info = tracingId == null || info == null ? info : info.withTrace(new QueryTrace(tracingId, session));
49+
50+ switch (msg.kind) {
51+ case VOID:
52+ return empty(info);
53+ case ROWS:
54+ ResultMessage.Rows r = (ResultMessage.Rows)msg;
55+ ColumnDefinitions.Definition[] defs = new ColumnDefinitions.Definition[r.result.metadata.names.size()];
56+ for (int i = 0; i < defs.length; i++)
57+ defs[i] = ColumnDefinitions.Definition.fromTransportSpecification(r.result.metadata.names.get(i));
58+
59+ return new ArrayBackedResultSet(new ColumnDefinitions(defs), new ArrayDeque<List<ByteBuffer>>(r.result.rows), info);
60+ case SET_KEYSPACE:
61+ case SCHEMA_CHANGE:
62+ return empty(info);
63+ case PREPARED:
64+ throw new RuntimeException("Prepared statement received when a ResultSet was expected");
65+ default:
66+ logger.error("Received unknow result type '{}'; returning empty result set", msg.kind);
67+ return empty(info);
68+ }
69+ }
70+
71+ private static ResultSet empty(ExecutionInfo info) {
72+ return new ArrayBackedResultSet(ColumnDefinitions.EMPTY, EMPTY_QUEUE, info);
73+ }
74+
75+ public ColumnDefinitions getColumnDefinitions() {
76+ return metadata;
77+ }
78+
79+ public boolean isExhausted() {
80+ return rows.isEmpty();
81+ }
82+
83+ public Row one() {
84+ return ArrayBackedRow.fromData(metadata, rows.poll());
85+ }
86+
87+ public List<Row> all() {
88+ if (isExhausted())
89+ return Collections.emptyList();
90+
91+ List<Row> result = new ArrayList<Row>(rows.size());
92+ for (Row row : this)
93+ result.add(row);
94+ return result;
95+ }
96+
97+ @Override
98+ public Iterator<Row> iterator() {
99+ return new Iterator<Row>() {
100+
101+ @Override
102+ public boolean hasNext() {
103+ return !rows.isEmpty();
104+ }
105+
106+ @Override
107+ public Row next() {
108+ return ArrayBackedRow.fromData(metadata, rows.poll());
109+ }
110+
111+ @Override
112+ public void remove() {
113+ throw new UnsupportedOperationException();
114+ }
115+ };
116+ }
117+
118+ public ExecutionInfo getExecutionInfo() {
119+ return info;
120+ }
121+
122+ @Override
123+ public String toString() {
124+ StringBuilder sb = new StringBuilder();
125+ sb.append("ResultSet[ exhausted: ").append(isExhausted());
126+ sb.append(", ").append(metadata).append("]");
127+ return sb.toString();
128+ }
129+}
130+
added driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java +325 −0
@@ -0,0 +1,325 @@
1+/*
2+ * Copyright (C) 2012 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.math.BigDecimal;
19+import java.math.BigInteger;
20+import java.net.InetAddress;
21+import java.nio.ByteBuffer;
22+import java.util.*;
23+
24+import org.apache.cassandra.db.marshal.*;
25+
26+import com.datastax.driver.core.exceptions.InvalidTypeException;
27+
28+/**
29+ * Implementation of a Row backed by an ArrayList.
30+ */
31+class ArrayBackedRow implements Row {
32+
33+ private final ColumnDefinitions metadata;
34+ private final List<ByteBuffer> data;
35+
36+ private ArrayBackedRow(ColumnDefinitions metadata, List<ByteBuffer> data) {
37+ this.metadata = metadata;
38+ this.data = data;
39+ }
40+
41+ static Row fromData(ColumnDefinitions metadata, List<ByteBuffer> data) {
42+ if (data == null)
43+ return null;
44+
45+ return new ArrayBackedRow(metadata, data);
46+ }
47+
48+ public ColumnDefinitions getColumnDefinitions() {
49+ return metadata;
50+ }
51+
52+ public boolean isNull(int i) {
53+ metadata.checkBounds(i);
54+ return data.get(i) == null;
55+ }
56+
57+ public boolean isNull(String name) {
58+ return isNull(metadata.getIdx(name));
59+ }
60+
61+ public boolean getBool(int i) {
62+ metadata.checkType(i, DataType.Name.BOOLEAN);
63+
64+ ByteBuffer value = data.get(i);
65+ if (value == null || value.remaining() == 0)
66+ return false;
67+
68+ return BooleanType.instance.compose(value);
69+ }
70+
71+ public boolean getBool(String name) {
72+ return getBool(metadata.getIdx(name));
73+ }
74+
75+ public int getInt(int i) {
76+ metadata.checkType(i, DataType.Name.INT);
77+
78+ ByteBuffer value = data.get(i);
79+ if (value == null || value.remaining() == 0)
80+ return 0;
81+
82+ return Int32Type.instance.compose(value);
83+ }
84+
85+ public int getInt(String name) {
86+ return getInt(metadata.getIdx(name));
87+ }
88+
89+ public long getLong(int i) {
90+ metadata.checkType(i, DataType.Name.BIGINT, DataType.Name.COUNTER);
91+
92+ ByteBuffer value = data.get(i);
93+ if (value == null || value.remaining() == 0)
94+ return 0L;
95+
96+ return LongType.instance.compose(value);
97+ }
98+
99+ public long getLong(String name) {
100+ return getLong(metadata.getIdx(name));
101+ }
102+
103+ public Date getDate(int i) {
104+ metadata.checkType(i, DataType.Name.TIMESTAMP);
105+
106+ ByteBuffer value = data.get(i);
107+ if (value == null || value.remaining() == 0)
108+ return null;
109+
110+ return DateType.instance.compose(value);
111+ }
112+
113+ public Date getDate(String name) {
114+ return getDate(metadata.getIdx(name));
115+ }
116+
117+ public float getFloat(int i) {
118+ metadata.checkType(i, DataType.Name.FLOAT);
119+
120+ ByteBuffer value = data.get(i);
121+ if (value == null || value.remaining() == 0)
122+ return 0.0f;
123+
124+ return FloatType.instance.compose(value);
125+ }
126+
127+ public float getFloat(String name) {
128+ return getFloat(metadata.getIdx(name));
129+ }
130+
131+ public double getDouble(int i) {
132+ metadata.checkType(i, DataType.Name.DOUBLE);
133+
134+ ByteBuffer value = data.get(i);
135+ if (value == null || value.remaining() == 0)
136+ return 0.0;
137+
138+ return DoubleType.instance.compose(value);
139+ }
140+
141+ public double getDouble(String name) {
142+ return getDouble(metadata.getIdx(name));
143+ }
144+
145+ public ByteBuffer getBytesUnsafe(int i) {
146+ metadata.checkBounds(i);
147+
148+ ByteBuffer value = data.get(i);
149+ if (value == null)
150+ return null;
151+
152+ return value.duplicate();
153+ }
154+
155+ public ByteBuffer getBytesUnsafe(String name) {
156+ return getBytesUnsafe(metadata.getIdx(name));
157+ }
158+
159+ public ByteBuffer getBytes(int i) {
160+ metadata.checkType(i, DataType.Name.BLOB);
161+ return getBytesUnsafe(i);
162+ }
163+
164+ public ByteBuffer getBytes(String name) {
165+ return getBytes(metadata.getIdx(name));
166+ }
167+
168+ public String getString(int i) {
169+ DataType.Name type = metadata.checkType(i, DataType.Name.VARCHAR,
170+ DataType.Name.TEXT,
171+ DataType.Name.ASCII);
172+
173+ ByteBuffer value = data.get(i);
174+ if (value == null)
175+ return null;
176+
177+ return type == DataType.Name.ASCII
178+ ? AsciiType.instance.compose(value)
179+ : UTF8Type.instance.compose(value);
180+ }
181+
182+ public String getString(String name) {
183+ return getString(metadata.getIdx(name));
184+ }
185+
186+ public BigInteger getVarint(int i) {
187+ metadata.checkType(i, DataType.Name.VARINT);
188+
189+ ByteBuffer value = data.get(i);
190+ if (value == null || value.remaining() == 0)
191+ return null;
192+
193+ return IntegerType.instance.compose(value);
194+ }
195+
196+ public BigInteger getVarint(String name) {
197+ return getVarint(metadata.getIdx(name));
198+ }
199+
200+ public BigDecimal getDecimal(int i) {
201+ metadata.checkType(i, DataType.Name.DECIMAL);
202+
203+ ByteBuffer value = data.get(i);
204+ if (value == null || value.remaining() == 0)
205+ return null;
206+
207+ return DecimalType.instance.compose(value);
208+ }
209+
210+ public BigDecimal getDecimal(String name) {
211+ return getDecimal(metadata.getIdx(name));
212+ }
213+
214+ public UUID getUUID(int i) {
215+ DataType.Name type = metadata.checkType(i, DataType.Name.UUID, DataType.Name.TIMEUUID);
216+
217+ ByteBuffer value = data.get(i);
218+ if (value == null || value.remaining() == 0)
219+ return null;
220+
221+ return type == DataType.Name.UUID
222+ ? UUIDType.instance.compose(value)
223+ : TimeUUIDType.instance.compose(value);
224+ }
225+
226+ public UUID getUUID(String name) {
227+ return getUUID(metadata.getIdx(name));
228+ }
229+
230+ public InetAddress getInet(int i) {
231+ metadata.checkType(i, DataType.Name.INET);
232+
233+ ByteBuffer value = data.get(i);
234+ if (value == null || value.remaining() == 0)
235+ return null;
236+
237+ return InetAddressType.instance.compose(value);
238+ }
239+
240+ public InetAddress getInet(String name) {
241+ return getInet(metadata.getIdx(name));
242+ }
243+
244+ @SuppressWarnings("unchecked")
245+ public <T> List<T> getList(int i, Class<T> elementsClass) {
246+ DataType type = metadata.getType(i);
247+ if (type.getName() != DataType.Name.LIST)
248+ throw new InvalidTypeException(String.format("Column %s is not of list type", metadata.getName(i)));
249+
250+ Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
251+ if (!elementsClass.isAssignableFrom(expectedClass))
252+ throw new InvalidTypeException(String.format("Column %s is a list of %s (CQL type %s), cannot be retrieve as a list of %s", metadata.getName(i), expectedClass, type, elementsClass));
253+
254+ ByteBuffer value = data.get(i);
255+ if (value == null)
256+ return Collections.<T>emptyList();
257+
258+ // TODO: we could avoid the getCodec call if we kept a reference to the original message.
259+ return Collections.unmodifiableList(Codec.<List<T>>getCodec(type).compose(value));
260+ }
261+
262+ public <T> List<T> getList(String name, Class<T> elementsClass) {
263+ return getList(metadata.getIdx(name), elementsClass);
264+ }
265+
266+ @SuppressWarnings("unchecked")
267+ public <T> Set<T> getSet(int i, Class<T> elementsClass) {
268+ DataType type = metadata.getType(i);
269+ if (type.getName() != DataType.Name.SET)
270+ throw new InvalidTypeException(String.format("Column %s is not of set type", metadata.getName(i)));
271+
272+ Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
273+ if (!elementsClass.isAssignableFrom(expectedClass))
274+ throw new InvalidTypeException(String.format("Column %s is a set of %s (CQL type %s), cannot be retrieve as a set of %s", metadata.getName(i), expectedClass, type, elementsClass));
275+
276+ ByteBuffer value = data.get(i);
277+ if (value == null)
278+ return Collections.<T>emptySet();
279+
280+ return Collections.unmodifiableSet(Codec.<Set<T>>getCodec(type).compose(value));
281+ }
282+
283+ public <T> Set<T> getSet(String name, Class<T> elementsClass) {
284+ return getSet(metadata.getIdx(name), elementsClass);
285+ }
286+
287+ @SuppressWarnings("unchecked")
288+ public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) {
289+ DataType type = metadata.getType(i);
290+ if (type.getName() != DataType.Name.MAP)
291+ throw new InvalidTypeException(String.format("Column %s is not of map type", metadata.getName(i)));
292+
293+ Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType;
294+ Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType;
295+ if (!keysClass.isAssignableFrom(expectedKeysClass) || !valuesClass.isAssignableFrom(expectedValuesClass))
296+ throw new InvalidTypeException(String.format("Column %s is a map of %s->%s (CQL type %s), cannot be retrieve as a map of %s->%s", metadata.getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass));
297+
298+ ByteBuffer value = data.get(i);
299+ if (value == null)
300+ return Collections.<K, V>emptyMap();
301+
302+ return Collections.unmodifiableMap(Codec.<Map<K, V>>getCodec(type).compose(value));
303+ }
304+
305+ public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass) {
306+ return getMap(metadata.getIdx(name), keysClass, valuesClass);
307+ }
308+
309+ @Override
310+ public String toString() {
311+ StringBuilder sb = new StringBuilder();
312+ sb.append("Row[");
313+ for (int i = 0; i < metadata.size(); i++) {
314+ if (i != 0)
315+ sb.append(", ");
316+ ByteBuffer bb = data.get(i);
317+ if (bb == null)
318+ sb.append("NULL");
319+ else
320+ sb.append(Codec.getCodec(metadata.getType(i)).getString(bb));
321+ }
322+ sb.append("]");
323+ return sb.toString();
324+ }
325+}
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +4 −1
@@ -50,9 +50,12 @@
5050 /**
5151 * Creates a new {@code BoundStatement} from the provided prepared
5252 * statement.
53- *
5453 * @param statement the prepared statement from which to create a {@code BoundStatement}.
54+ *
55+ * @deprecated this constructor is now deprecated an will removed (made private) in
56+ * version 2 of the driver. Instead, you are encouraged to use {@link PreparedStatement#bind()}.
5557 */
58+ @Deprecated
5659 public BoundStatement(PreparedStatement statement) {
5760 this.statement = statement;
5861 this.values = new ByteBuffer[statement.getVariables().size()];
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +41 −27
@@ -72,11 +72,25 @@
7272
7373 final Manager manager;
7474
75- // Note: we don't want to make init part of Configuration. In 2.0, the default is not init
76- // so there is not point in breaking Configuration API for that. However, as a workaround
77- // until upgrade, we still want to allow optional lazy initialization of the control
78- // connection (see #JAVA-161)
79- private Cluster(List<InetAddress> contactPoints, Configuration configuration, boolean init) {
75+ /**
76+ * Constructs a new Cluster instance.
77+ * <p>
78+ * This constructor is mainly exposed so Cluster can be sub-classed as a mean to make testing/mocking
79+ * easier or to "intecept" it's method call. Most users shouldn't extend this class however and
80+ * should prefer either using the {@link #builder} or calling {@link #buildFrom} with a custom
81+ * Initializer.
82+ *
83+ * @param contactPoints the list of contact points to use for the new cluster.
84+ * @param configuration the configuration for the new cluster.
85+ * @param init whether or not initialization should be perform by this constructor. Passing
86+ * {@code false} is equivalent to using {@link Builder#withDeferredInitialization} on a
87+ * {@code Cluster.Builder}.
88+ */
89+ protected Cluster(List<InetAddress> contactPoints, Configuration configuration, boolean init) {
90+ // Note: we don't want to make init part of Configuration. In 2.0, the default is not init
91+ // so there is not point in breaking Configuration API for that. However, as a workaround
92+ // until upgrade, we still want to allow optional lazy initialization of the control
93+ // connection (see #JAVA-161)
8094 this.manager = new Manager(contactPoints, configuration);
8195 if (init)
8296 this.manager.init();
@@ -142,8 +156,8 @@
142156 * {@code keyspace}.
143157 */
144158 public Session connect(String keyspace) {
145- Session session = connect();
146- session.manager.setKeyspace(keyspace);
159+ SessionManager session = (SessionManager)connect();
160+ session.setKeyspace(keyspace);
147161 return session;
148162 }
149163
@@ -724,7 +738,7 @@
724738
725739 // Initial contacts point
726740 final List<InetAddress> contactPoints;
727- final Set<Session> sessions = new CopyOnWriteArraySet<Session>();
741+ final Set<SessionManager> sessions = new CopyOnWriteArraySet<SessionManager>();
728742
729743 final Metadata metadata;
730744 final Configuration configuration;
@@ -817,7 +831,7 @@
817831 private Session newSession() {
818832 init();
819833
820- Session session = new Session(Cluster.this, metadata.allHosts());
834+ SessionManager session = new SessionManager(Cluster.this, metadata.allHosts());
821835 sessions.add(session);
822836 return session;
823837 }
@@ -889,14 +903,14 @@
889903 // new pool have been created. This is harmless if there is no prior pool since RequestHandler
890904 // will ignore the node, but we do want to make sure there is no prior pool so we don't
891905 // query from a pool we will shutdown right away.
892- for (Session s : sessions)
893- s.manager.removePool(host);
906+ for (SessionManager s : sessions)
907+ s.removePool(host);
894908 loadBalancingPolicy().onUp(host);
895909 controlConnection.onUp(host);
896910
897911 List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
898- for (Session s : sessions)
899- futures.add(s.manager.addOrRenewPool(host, false));
912+ for (SessionManager s : sessions)
913+ futures.add(s.addOrRenewPool(host, false));
900914
901915 // Only mark the node up once all session have re-added their pool (if the loadbalancing
902916 // policy says it should), so that Host.isUp() don't return true before we're reconnected
@@ -917,8 +931,8 @@
917931
918932 // Now, check if there isn't pools to create/remove following the addition.
919933 // We do that now only so that it's not called before we've set the node up.
920- for (Session s : sessions)
921- s.manager.updateCreatedPools();
934+ for (SessionManager s : sessions)
935+ s.updateCreatedPools();
922936 }
923937
924938 public void onFailure(Throwable t) {
@@ -953,8 +967,8 @@
953967
954968 loadBalancingPolicy().onDown(host);
955969 controlConnection.onDown(host);
956- for (Session s : sessions)
957- s.manager.onDown(host);
970+ for (SessionManager s : sessions)
971+ s.onDown(host);
958972
959973 // Contrarily to other actions of that method, there is no reason to notify listeners
960974 // unless the host was UP at the beginning of this function since even if a onUp fail
@@ -1012,8 +1026,8 @@
10121026 controlConnection.onAdd(host);
10131027
10141028 List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1015- for (Session s : sessions)
1016- futures.add(s.manager.addOrRenewPool(host, true));
1029+ for (SessionManager s : sessions)
1030+ futures.add(s.addOrRenewPool(host, true));
10171031
10181032 // Only mark the node up once all session have added their pool (if the loadbalancing
10191033 // policy says it should), so that Host.isUp() don't return true before we're reconnected
@@ -1034,8 +1048,8 @@
10341048
10351049 // Now, check if there isn't pools to create/remove following the addition.
10361050 // We do that now only so that it's not called before we've set the node up.
1037- for (Session s : sessions)
1038- s.manager.updateCreatedPools();
1051+ for (SessionManager s : sessions)
1052+ s.updateCreatedPools();
10391053 }
10401054
10411055 public void onFailure(Throwable t) {
@@ -1056,8 +1070,8 @@
10561070 logger.trace("Removing host {}", host);
10571071 loadBalancingPolicy().onRemove(host);
10581072 controlConnection.onRemove(host);
1059- for (Session s : sessions)
1060- s.manager.onRemove(host);
1073+ for (SessionManager s : sessions)
1074+ s.onRemove(host);
10611075
10621076 for (Host.StateListener listener : listeners)
10631077 listener.onRemove(host);
@@ -1090,8 +1104,8 @@
10901104 }
10911105
10921106 public void ensurePoolsSizing() {
1093- for (Session session : sessions) {
1094- for (HostConnectionPool pool : session.manager.pools.values())
1107+ for (SessionManager session : sessions) {
1108+ for (HostConnectionPool pool : session.pools.values())
10951109 pool.ensureCoreConnections();
10961110 }
10971111 }
@@ -1102,8 +1116,8 @@
11021116 if (preparedQueries.putIfAbsent(stmt.id, stmt) != null)
11031117 logger.warn("Re-preparing already prepared query {}. Please note that preparing the same query more than once is "
11041118 + "generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.", stmt.getQueryString());
1105- for (Session s : sessions)
1106- s.manager.prepare(stmt.getQueryString(), toExclude);
1119+ for (SessionManager s : sessions)
1120+ s.prepare(stmt.getQueryString(), toExclude);
11071121 }
11081122
11091123 private void prepareAllQueries(Host host) throws InterruptedException {
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +16 −16
@@ -251,16 +251,16 @@
251251 whereClause += " AND columnfamily_name = '" + table + "'";
252252 }
253253
254- ResultSetFuture ksFuture = table == null
255- ? new ResultSetFuture(null, new QueryMessage(SELECT_KEYSPACES + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL))
256- : null;
257- ResultSetFuture cfFuture = new ResultSetFuture(null, new QueryMessage(SELECT_COLUMN_FAMILIES + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
258- ResultSetFuture colsFuture = new ResultSetFuture(null, new QueryMessage(SELECT_COLUMNS + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
254+ DefaultResultSetFuture ksFuture = table == null
255+ ? new DefaultResultSetFuture(null, new QueryMessage(SELECT_KEYSPACES + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL))
256+ : null;
257+ DefaultResultSetFuture cfFuture = new DefaultResultSetFuture(null, new QueryMessage(SELECT_COLUMN_FAMILIES + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
258+ DefaultResultSetFuture colsFuture = new DefaultResultSetFuture(null, new QueryMessage(SELECT_COLUMNS + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
259259
260260 if (ksFuture != null)
261- connection.write(ksFuture.callback);
262- connection.write(cfFuture.callback);
263- connection.write(colsFuture.callback);
261+ connection.write(ksFuture);
262+ connection.write(cfFuture);
263+ connection.write(colsFuture);
264264
265265 cluster.metadata.rebuildSchema(keyspace, table, ksFuture == null ? null : ksFuture.get(), cfFuture.get(), colsFuture.get());
266266 }
@@ -306,10 +306,10 @@
306306 private void refreshNodeListAndTokenMap(Connection connection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
307307 // Make sure we're up to date on nodes and tokens
308308
309- ResultSetFuture peersFuture = new ResultSetFuture(null, new QueryMessage(SELECT_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
310- ResultSetFuture localFuture = new ResultSetFuture(null, new QueryMessage(SELECT_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
311- connection.write(peersFuture.callback);
312- connection.write(localFuture.callback);
309+ DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, new QueryMessage(SELECT_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
310+ DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new QueryMessage(SELECT_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
311+ connection.write(peersFuture);
312+ connection.write(localFuture);
313313
314314 String partitioner = null;
315315 Map<Host, Collection<String>> tokenMap = new HashMap<Host, Collection<String>>();
@@ -394,10 +394,10 @@
394394 long elapsed = 0;
395395 while (elapsed < MAX_SCHEMA_AGREEMENT_WAIT_MS) {
396396
397- ResultSetFuture peersFuture = new ResultSetFuture(null, new QueryMessage(SELECT_SCHEMA_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
398- ResultSetFuture localFuture = new ResultSetFuture(null, new QueryMessage(SELECT_SCHEMA_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
399- connection.write(peersFuture.callback);
400- connection.write(localFuture.callback);
397+ DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, new QueryMessage(SELECT_SCHEMA_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
398+ DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new QueryMessage(SELECT_SCHEMA_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL));
399+ connection.write(peersFuture);
400+ connection.write(localFuture);
401401
402402 Set<UUID> versions = new HashSet<UUID>();
403403
added driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +228 −0
@@ -0,0 +1,228 @@
1+/*
2+ * Copyright (C) 2012 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.concurrent.ExecutionException;
19+import java.util.concurrent.TimeoutException;
20+import java.util.concurrent.TimeUnit;
21+
22+import com.google.common.util.concurrent.Uninterruptibles;
23+
24+import org.apache.cassandra.transport.Message;
25+import org.apache.cassandra.transport.messages.ErrorMessage;
26+import org.apache.cassandra.transport.messages.ResultMessage;
27+
28+import com.datastax.driver.core.exceptions.*;
29+
30+import org.slf4j.Logger;
31+import org.slf4j.LoggerFactory;
32+
33+/**
34+ * Internal implementation of ResultSetFuture.
35+ */
36+class DefaultResultSetFuture extends SimpleFuture<ResultSet> implements ResultSetFuture, RequestHandler.Callback {
37+
38+ private static final Logger logger = LoggerFactory.getLogger(ResultSetFuture.class);
39+
40+ private final SessionManager session;
41+ private final Message.Request request;
42+ private volatile RequestHandler handler;
43+
44+ DefaultResultSetFuture(SessionManager session, Message.Request request) {
45+ this.session = session;
46+ this.request = request;
47+ }
48+
49+ @Override
50+ public void register(RequestHandler handler) {
51+ this.handler = handler;
52+ }
53+
54+ @Override
55+ public Message.Request request() {
56+ return request;
57+ }
58+
59+ @Override
60+ public void onSet(Connection connection, Message.Response response, ExecutionInfo info, long latency) {
61+ try {
62+ switch (response.type) {
63+ case RESULT:
64+ ResultMessage rm = (ResultMessage)response;
65+ switch (rm.kind) {
66+ case SET_KEYSPACE:
67+ // propagate the keyspace change to other connections
68+ session.poolsState.setKeyspace(((ResultMessage.SetKeyspace)rm).keyspace);
69+ set(ArrayBackedResultSet.fromMessage(rm, session, info));
70+ break;
71+ case SCHEMA_CHANGE:
72+ ResultMessage.SchemaChange scc = (ResultMessage.SchemaChange)rm;
73+ ResultSet rs = ArrayBackedResultSet.fromMessage(rm, session, info);
74+ switch (scc.change) {
75+ case CREATED:
76+ if (scc.columnFamily.isEmpty()) {
77+ session.cluster.manager.refreshSchema(connection, DefaultResultSetFuture.this, rs, null, null);
78+ } else {
79+ session.cluster.manager.refreshSchema(connection, DefaultResultSetFuture.this, rs, scc.keyspace, null);
80+ }
81+ break;
82+ case DROPPED:
83+ if (scc.columnFamily.isEmpty()) {
84+ // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...)
85+ // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements.
86+ // We'll add it back if CASSANDRA-5358 changes that behavior
87+ //if (scc.keyspace.equals(session.poolsState.keyspace))
88+ // session.poolsState.setKeyspace(null);
89+ session.cluster.manager.refreshSchema(connection, DefaultResultSetFuture.this, rs, null, null);
90+ } else {
91+ session.cluster.manager.refreshSchema(connection, DefaultResultSetFuture.this, rs, scc.keyspace, null);
92+ }
93+ break;
94+ case UPDATED:
95+ if (scc.columnFamily.isEmpty()) {
96+ session.cluster.manager.refreshSchema(connection, DefaultResultSetFuture.this, rs, scc.keyspace, null);
97+ } else {
98+ session.cluster.manager.refreshSchema(connection, DefaultResultSetFuture.this, rs, scc.keyspace, scc.columnFamily);
99+ }
100+ break;
101+ default:
102+ logger.info("Ignoring unknown schema change result");
103+ break;
104+ }
105+ break;
106+ default:
107+ set(ArrayBackedResultSet.fromMessage(rm, session, info));
108+ break;
109+ }
110+ break;
111+ case ERROR:
112+ setException(convertException(((ErrorMessage)response).error));
113+ break;
114+ default:
115+ // This mean we have probably have a bad node, so defunct the connection
116+ connection.defunct(new ConnectionException(connection.address, String.format("Got unexpected %s response", response.type)));
117+ setException(new DriverInternalError(String.format("Got unexpected %s response from %s", response.type, connection.address)));
118+ break;
119+ }
120+ } catch (RuntimeException e) {
121+ // If we get a bug here, the client will not get it, so better forwarding the error
122+ setException(new DriverInternalError("Unexpected error while processing response from " + connection.address, e));
123+ }
124+ }
125+
126+ @Override
127+ public void onSet(Connection connection, Message.Response response, long latency) {
128+ // This is only called for internal calls (i.e, when the callback is not wrapped in ResponseHandler),
129+ // so don't bother with ExecutionInfo.
130+ onSet(connection, response, null, latency);
131+ }
132+
133+ @Override
134+ public void onException(Connection connection, Exception exception, long latency) {
135+ setException(exception);
136+ }
137+
138+ @Override
139+ public void onTimeout(Connection connection, long latency) {
140+ // This is only called for internal calls (i.e, when the callback is not wrapped in ResponseHandler).
141+ // So just set an exception for the final result, which should be handled correctly by said internal call.
142+ setException(new ConnectionException(connection.address, "Operation Timeouted"));
143+ }
144+
145+ public ResultSet getUninterruptibly() {
146+ try {
147+ return Uninterruptibles.getUninterruptibly(this);
148+ } catch (ExecutionException e) {
149+ extractCauseFromExecutionException(e);
150+ throw new AssertionError();
151+ }
152+ }
153+
154+ public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException {
155+ try {
156+ return Uninterruptibles.getUninterruptibly(this, timeout, unit);
157+ } catch (ExecutionException e) {
158+ extractCauseFromExecutionException(e);
159+ throw new AssertionError();
160+ }
161+ }
162+
163+ @Override
164+ public boolean cancel(boolean mayInterruptIfRunning) {
165+ if (!super.cancel(mayInterruptIfRunning))
166+ return false;
167+
168+ handler.cancel();
169+ return true;
170+ }
171+
172+ static void extractCauseFromExecutionException(ExecutionException e) {
173+ // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
174+ // created on the I/O thread receiving the response. Which means that the stacktrace associated
175+ // with said cause will make no mention of the current thread. This is painful for say, finding
176+ // out which execute() statement actually raised the exception. So instead, we re-create the
177+ // exception.
178+ if (e.getCause() instanceof DriverException)
179+ throw ((DriverException)e.getCause()).copy();
180+ else
181+ throw new DriverInternalError("Unexpected exception thrown", e.getCause());
182+ }
183+
184+ static void extractCause(Throwable cause) {
185+ // Same as above
186+ if (cause instanceof DriverException)
187+ throw ((DriverException)cause).copy();
188+ throw new DriverInternalError("Unexpected exception thrown", cause);
189+ }
190+
191+ static Exception convertException(org.apache.cassandra.exceptions.TransportException te) {
192+ switch (te.code()) {
193+ case SERVER_ERROR:
194+ return new DriverInternalError("An unexpected error occured server side: " + te.getMessage());
195+ case PROTOCOL_ERROR:
196+ return new DriverInternalError("An unexpected protocol error occured. This is a bug in this library, please report: " + te.getMessage());
197+ case UNAVAILABLE:
198+ org.apache.cassandra.exceptions.UnavailableException ue = (org.apache.cassandra.exceptions.UnavailableException)te;
199+ return new UnavailableException(ConsistencyLevel.from(ue.consistency), ue.required, ue.alive);
200+ case OVERLOADED:
201+ return new DriverInternalError("Queried host was overloaded; this shouldn't happen, another node should have been tried");
202+ case IS_BOOTSTRAPPING:
203+ return new DriverInternalError("Queried host was boostrapping; this shouldn't happen, another node should have been tried");
204+ case TRUNCATE_ERROR:
205+ return new TruncateException(te.getMessage());
206+ case WRITE_TIMEOUT:
207+ org.apache.cassandra.exceptions.WriteTimeoutException wte = (org.apache.cassandra.exceptions.WriteTimeoutException)te;
208+ return new WriteTimeoutException(ConsistencyLevel.from(wte.consistency), WriteType.from(wte.writeType), wte.received, wte.blockFor);
209+ case READ_TIMEOUT:
210+ org.apache.cassandra.exceptions.ReadTimeoutException rte = (org.apache.cassandra.exceptions.ReadTimeoutException)te;
211+ return new ReadTimeoutException(ConsistencyLevel.from(rte.consistency), rte.received, rte.blockFor, rte.dataPresent);
212+ case SYNTAX_ERROR:
213+ return new SyntaxError(te.getMessage());
214+ case UNAUTHORIZED:
215+ return new UnauthorizedException(te.getMessage());
216+ case INVALID:
217+ return new InvalidQueryException(te.getMessage());
218+ case CONFIG_ERROR:
219+ return new InvalidConfigurationInQueryException(te.getMessage());
220+ case ALREADY_EXISTS:
221+ org.apache.cassandra.exceptions.AlreadyExistsException aee = (org.apache.cassandra.exceptions.AlreadyExistsException)te;
222+ return new AlreadyExistsException(aee.ksName, aee.cfName);
223+ default:
224+ return new DriverInternalError("Unknown error return code: " + te.code());
225+ }
226+ }
227+}
228+
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +2 −2
@@ -39,7 +39,7 @@
3939
4040 public final Host host;
4141 public volatile HostDistance hostDistance;
42- private final Session.Manager manager;
42+ private final SessionManager manager;
4343
4444 private final List<Connection> connections;
4545 private final AtomicInteger open;
@@ -54,7 +54,7 @@
5454
5555 private final AtomicInteger scheduledForCreation = new AtomicInteger();
5656
57- public HostConnectionPool(Host host, HostDistance hostDistance, Session.Manager manager) throws ConnectionException {
57+ public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException {
5858 assert hostDistance != HostDistance.IGNORED;
5959 this.host = host;
6060 this.hostDistance = hostDistance;
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +2 −2
@@ -36,7 +36,7 @@
3636 private final ConcurrentMap<InetAddress, Host> hosts = new ConcurrentHashMap<InetAddress, Host>();
3737 private final ConcurrentMap<String, KeyspaceMetadata> keyspaces = new ConcurrentHashMap<String, KeyspaceMetadata>();
3838
39- @SuppressWarnings("unchecked")
39+ @SuppressWarnings({"unchecked", "rawtypes"})
4040 private volatile TokenMap<? extends Token> tokenMap;
4141
4242 Metadata(Cluster.Manager cluster) {
@@ -170,7 +170,7 @@
170170 * this information. It is also not guarantee that the returned set won't
171171 * be empty (which is then some form of staleness).
172172 */
173- @SuppressWarnings("unchecked")
173+ @SuppressWarnings({"unchecked", "rawtypes"})
174174 public Set<Host> getReplicas(ByteBuffer partitionKey) {
175175 TokenMap current = tokenMap;
176176 if (current == null) {
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +4 −4
@@ -55,8 +55,8 @@
5555 @Override
5656 public Integer value() {
5757 Set<Host> s = new HashSet<Host>();
58- for (Session session : manager.sessions)
59- s.addAll(session.manager.pools.keySet());
58+ for (SessionManager session : manager.sessions)
59+ s.addAll(session.pools.keySet());
6060 return s.size();
6161 }
6262 });
@@ -64,8 +64,8 @@
6464 @Override
6565 public Integer value() {
6666 int value = manager.controlConnection.isOpen() ? 1 : 0;
67- for (Session session : manager.sessions)
68- for (HostConnectionPool pool : session.manager.pools.values())
67+ for (SessionManager session : manager.sessions)
68+ for (HostConnectionPool pool : session.pools.values())
6969 value += pool.opened();
7070 return value;
7171 }
modified driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java +16 −2
@@ -133,13 +133,13 @@
133133 * Creates a new BoundStatement object and bind its variables to the
134134 * provided values.
135135 * <p>
136- * This method is a convenience method for {@code new BoundStatement(this).bind(...)}.
137- * <p>
138136 * While the number of {@code values} cannot be greater than the number of bound
139137 * variables, the number of {@code values} may be fewer than the number of bound
140138 * variables. In that case, the remaining variables will have to be bound
141139 * to values by another mean because the resulting {@code BoundStatement}
142140 * being executable.
141+ * <p>
142+ * This method is a convenience for {@code bind().bind(...)}.
143143 *
144144 * @param values the values to bind to the variables of the newly created
145145 * BoundStatement.
@@ -158,6 +158,20 @@
158158 return bs.bind(values);
159159 }
160160
161+ /**
162+ * Creates a new BoundStatement object for this prepared statement.
163+ * <p>
164+ * This method do not bind any values to any of the prepared variables. Said
165+ * values need to be bound on the resulting statement using BoundStatement's
166+ * setters methods ({@link BoundStatement#setInt}, {@link BoundStatement#setLong}, ...).
167+ *
168+ * @return the newly created {@code BoundStatement}.
169+ */
170+ public BoundStatement bind()
171+ {
172+ return new BoundStatement(this);
173+ }
174+
161175 /**
162176 * Sets the routing key for this prepared statement.
163177 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/QueryTrace.java +2 −2
@@ -59,10 +59,10 @@
5959 private volatile long startedAt;
6060 private volatile List<Event> events;
6161
62- private final Session.Manager session;
62+ private final SessionManager session;
6363 private final Lock fetchLock = new ReentrantLock();
6464
65- QueryTrace(UUID traceId, Session.Manager session) {
65+ QueryTrace(UUID traceId, SessionManager session) {
6666 this.traceId = traceId;
6767 this.session = session;
6868 }
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +2 −2
@@ -52,7 +52,7 @@
5252
5353 private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
5454
55- private final Session.Manager manager;
55+ private final SessionManager manager;
5656 private final Callback callback;
5757
5858 private final Iterator<Host> queryPlan;
@@ -72,7 +72,7 @@
7272 private final TimerContext timerContext;
7373 private final long startTime;
7474
75- public RequestHandler(Session.Manager manager, Callback callback, Query query) {
75+ public RequestHandler(SessionManager manager, Callback callback, Query query) {
7676 this.manager = manager;
7777 this.callback = callback;
7878
modified driver-core/src/main/java/com/datastax/driver/core/ResultSet.java +7 −93
@@ -28,69 +28,21 @@
2828 *
2929 * Note that this class is not thread-safe.
3030 */
31-public class ResultSet implements Iterable<Row> {
32-
33- private static final Logger logger = LoggerFactory.getLogger(ResultSet.class);
34-
35- private static final Queue<List<ByteBuffer>> EMPTY_QUEUE = new ArrayDeque<List<ByteBuffer>>(0);
36-
37- private final ColumnDefinitions metadata;
38- private final Queue<List<ByteBuffer>> rows;
39- private final ExecutionInfo info;
40-
41- private ResultSet(ColumnDefinitions metadata, Queue<List<ByteBuffer>> rows, ExecutionInfo info) {
42- this.metadata = metadata;
43- this.rows = rows;
44- this.info = info;
45- }
46-
47- static ResultSet fromMessage(ResultMessage msg, Session.Manager session, ExecutionInfo info) {
48-
49- UUID tracingId = msg.getTracingId();
50- info = tracingId == null || info == null ? info : info.withTrace(new QueryTrace(tracingId, session));
51-
52- switch (msg.kind) {
53- case VOID:
54- return empty(info);
55- case ROWS:
56- ResultMessage.Rows r = (ResultMessage.Rows)msg;
57- ColumnDefinitions.Definition[] defs = new ColumnDefinitions.Definition[r.result.metadata.names.size()];
58- for (int i = 0; i < defs.length; i++)
59- defs[i] = ColumnDefinitions.Definition.fromTransportSpecification(r.result.metadata.names.get(i));
60-
61- return new ResultSet(new ColumnDefinitions(defs), new ArrayDeque<List<ByteBuffer>>(r.result.rows), info);
62- case SET_KEYSPACE:
63- case SCHEMA_CHANGE:
64- return empty(info);
65- case PREPARED:
66- throw new RuntimeException("Prepared statement received when a ResultSet was expected");
67- default:
68- logger.error("Received unknow result type '{}'; returning empty result set", msg.kind);
69- return empty(info);
70- }
71- }
72-
73- private static ResultSet empty(ExecutionInfo info) {
74- return new ResultSet(ColumnDefinitions.EMPTY, EMPTY_QUEUE, info);
75- }
31+public interface ResultSet extends Iterable<Row> {
7632
7733 /**
7834 * Returns the columns returned in this ResultSet.
7935 *
8036 * @return the columns returned in this ResultSet.
8137 */
82- public ColumnDefinitions getColumnDefinitions() {
83- return metadata;
84- }
38+ public ColumnDefinitions getColumnDefinitions();
8539
8640 /**
8741 * Returns whether this ResultSet has more results.
8842 *
8943 * @return whether this ResultSet has more results.
9044 */
91- public boolean isExhausted() {
92- return rows.isEmpty();
93- }
45+ public boolean isExhausted();
9446
9547 /**
9648 * Returns the the next result from this ResultSet.
@@ -98,9 +50,7 @@
9850 * @return the next row in this resultSet or null if this ResultSet is
9951 * exhausted.
10052 */
101- public Row one() {
102- return Row.fromData(metadata, rows.poll());
103- }
53+ public Row one();
10454
10555 /**
10656 * Returns all the remaining rows in this ResultSet as a list.
@@ -108,15 +58,7 @@
10858 * @return a list containing the remaining results of this ResultSet. The
10959 * returned list is empty if and only the ResultSet is exhausted.
11060 */
111- public List<Row> all() {
112- if (isExhausted())
113- return Collections.emptyList();
114-
115- List<Row> result = new ArrayList<Row>(rows.size());
116- for (Row row : this)
117- result.add(row);
118- return result;
119- }
61+ public List<Row> all();
12062
12163 /**
12264 * Returns an iterator over the rows contained in this ResultSet.
@@ -131,25 +73,7 @@
13173 * this ResultSet.
13274 */
13375 @Override
134- public Iterator<Row> iterator() {
135- return new Iterator<Row>() {
136-
137- @Override
138- public boolean hasNext() {
139- return !rows.isEmpty();
140- }
141-
142- @Override
143- public Row next() {
144- return Row.fromData(metadata, rows.poll());
145- }
146-
147- @Override
148- public void remove() {
149- throw new UnsupportedOperationException();
150- }
151- };
152- }
76+ public Iterator<Row> iterator();
15377
15478 /**
15579 * Returns information on the execution of this query.
@@ -159,15 +83,5 @@
15983 *
16084 * @return the execution info for this query.
16185 */
162- public ExecutionInfo getExecutionInfo() {
163- return info;
164- }
165-
166- @Override
167- public String toString() {
168- StringBuilder sb = new StringBuilder();
169- sb.append("ResultSet[ exhausted: ").append(isExhausted());
170- sb.append(", ").append(metadata).append("]");
171- return sb.toString();
172- }
86+ public ExecutionInfo getExecutionInfo();
17387 }
modified driver-core/src/main/java/com/datastax/driver/core/ResultSetFuture.java +5 −198
@@ -19,6 +19,7 @@
1919 import java.util.concurrent.TimeoutException;
2020 import java.util.concurrent.TimeUnit;
2121
22+import com.google.common.util.concurrent.ListenableFuture;
2223 import com.google.common.util.concurrent.Uninterruptibles;
2324
2425 import org.apache.cassandra.transport.Message;
@@ -36,125 +37,7 @@
3637 * Note that this class implements <a href="http://code.google.com/p/guava-libraries/">Guava</a>'s {@code
3738 * ListenableFuture} and can so be used with Guava's future utilities.
3839 */
39-public class ResultSetFuture extends SimpleFuture<ResultSet> {
40-
41- private static final Logger logger = LoggerFactory.getLogger(ResultSetFuture.class);
42-
43- private final Session.Manager session;
44- final ResponseCallback callback;
45-
46- ResultSetFuture(Session.Manager session, Message.Request request) {
47- this.session = session;
48- this.callback = new ResponseCallback(request);
49- }
50-
51- // The reason this exists is because we don't want to expose its method
52- // publicly (otherwise Future could implement RequestHandler.Callback directly)
53- class ResponseCallback implements RequestHandler.Callback {
54-
55- private final Message.Request request;
56- private volatile RequestHandler handler;
57-
58- ResponseCallback(Message.Request request) {
59- this.request = request;
60- }
61-
62- @Override
63- public void register(RequestHandler handler) {
64- this.handler = handler;
65- }
66-
67- @Override
68- public Message.Request request() {
69- return request;
70- }
71-
72- @Override
73- public void onSet(Connection connection, Message.Response response, ExecutionInfo info, long latency) {
74- try {
75- switch (response.type) {
76- case RESULT:
77- ResultMessage rm = (ResultMessage)response;
78- switch (rm.kind) {
79- case SET_KEYSPACE:
80- // propagate the keyspace change to other connections
81- session.poolsState.setKeyspace(((ResultMessage.SetKeyspace)rm).keyspace);
82- set(ResultSet.fromMessage(rm, session, info));
83- break;
84- case SCHEMA_CHANGE:
85- ResultMessage.SchemaChange scc = (ResultMessage.SchemaChange)rm;
86- ResultSet rs = ResultSet.fromMessage(rm, session, info);
87- switch (scc.change) {
88- case CREATED:
89- if (scc.columnFamily.isEmpty()) {
90- session.cluster.manager.refreshSchema(connection, ResultSetFuture.this, rs, null, null);
91- } else {
92- session.cluster.manager.refreshSchema(connection, ResultSetFuture.this, rs, scc.keyspace, null);
93- }
94- break;
95- case DROPPED:
96- if (scc.columnFamily.isEmpty()) {
97- // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...)
98- // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements.
99- // We'll add it back if CASSANDRA-5358 changes that behavior
100- //if (scc.keyspace.equals(session.poolsState.keyspace))
101- // session.poolsState.setKeyspace(null);
102- session.cluster.manager.refreshSchema(connection, ResultSetFuture.this, rs, null, null);
103- } else {
104- session.cluster.manager.refreshSchema(connection, ResultSetFuture.this, rs, scc.keyspace, null);
105- }
106- break;
107- case UPDATED:
108- if (scc.columnFamily.isEmpty()) {
109- session.cluster.manager.refreshSchema(connection, ResultSetFuture.this, rs, scc.keyspace, null);
110- } else {
111- session.cluster.manager.refreshSchema(connection, ResultSetFuture.this, rs, scc.keyspace, scc.columnFamily);
112- }
113- break;
114- default:
115- logger.info("Ignoring unknown schema change result");
116- break;
117- }
118- break;
119- default:
120- set(ResultSet.fromMessage(rm, session, info));
121- break;
122- }
123- break;
124- case ERROR:
125- setException(convertException(((ErrorMessage)response).error));
126- break;
127- default:
128- // This mean we have probably have a bad node, so defunct the connection
129- connection.defunct(new ConnectionException(connection.address, String.format("Got unexpected %s response", response.type)));
130- setException(new DriverInternalError(String.format("Got unexpected %s response from %s", response.type, connection.address)));
131- break;
132- }
133- } catch (RuntimeException e) {
134- // If we get a bug here, the client will not get it, so better forwarding the error
135- setException(new DriverInternalError("Unexpected error while processing response from " + connection.address, e));
136- }
137- }
138-
139- @Override
140- public void onSet(Connection connection, Message.Response response, long latency) {
141- // This is only called for internal calls (i.e, when the callback is not wrapped in ResponseHandler),
142- // so don't bother with ExecutionInfo.
143- onSet(connection, response, null, latency);
144- }
145-
146- @Override
147- public void onException(Connection connection, Exception exception, long latency) {
148- setException(exception);
149- }
150-
151- @Override
152- public void onTimeout(Connection connection, long latency) {
153- // This is only called for internal calls (i.e, when the callback is not wrapped in ResponseHandler).
154- // So just set an exception for the final result, which should be handled correctly by said internal call.
155- setException(new ConnectionException(connection.address, "Operation Timeouted"));
156- }
157- }
40+public interface ResultSetFuture extends ListenableFuture<ResultSet> {
15841
15942 /**
16043 * Waits for the query to return and return its result.
@@ -176,14 +59,7 @@
17659 * @throws QueryValidationException if the query is invalid (syntax error,
17760 * unauthorized or any other validation problem).
17861 */
179- public ResultSet getUninterruptibly() {
180- try {
181- return Uninterruptibles.getUninterruptibly(this);
182- } catch (ExecutionException e) {
183- extractCauseFromExecutionException(e);
184- throw new AssertionError();
185- }
186- }
62+ public ResultSet getUninterruptibly();
18763
18864 /**
18965 * Waits for the provided time for the query to return and return its
@@ -209,14 +85,7 @@
20985 * different from a Cassandra timeout, which is a {@code
21086 * QueryExecutionException}).
21187 */
212- public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException {
213- try {
214- return Uninterruptibles.getUninterruptibly(this, timeout, unit);
215- } catch (ExecutionException e) {
216- extractCauseFromExecutionException(e);
217- throw new AssertionError();
218- }
219- }
88+ public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException;
22089
22190 /**
22291 * Attempts to cancel the execution of the request corresponding to this
@@ -251,67 +120,5 @@
251120 * completed normally); {@code true} otherwise.
252121 */
253122 @Override
254- public boolean cancel(boolean mayInterruptIfRunning) {
255- if (!super.cancel(mayInterruptIfRunning))
256- return false;
257-
258- callback.handler.cancel();
259- return true;
260- }
261-
262- static void extractCauseFromExecutionException(ExecutionException e) {
263- // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
264- // created on the I/O thread receiving the response. Which means that the stacktrace associated
265- // with said cause will make no mention of the current thread. This is painful for say, finding
266- // out which execute() statement actually raised the exception. So instead, we re-create the
267- // exception.
268- if (e.getCause() instanceof DriverException)
269- throw ((DriverException)e.getCause()).copy();
270- else
271- throw new DriverInternalError("Unexpected exception thrown", e.getCause());
272- }
273-
274- static void extractCause(Throwable cause) {
275- // Same as above
276- if (cause instanceof DriverException)
277- throw ((DriverException)cause).copy();
278- throw new DriverInternalError("Unexpected exception thrown", cause);
279- }
280-
281- static Exception convertException(org.apache.cassandra.exceptions.TransportException te) {
282- switch (te.code()) {
283- case SERVER_ERROR:
284- return new DriverInternalError("An unexpected error occured server side: " + te.getMessage());
285- case PROTOCOL_ERROR:
286- return new DriverInternalError("An unexpected protocol error occured. This is a bug in this library, please report: " + te.getMessage());
287- case UNAVAILABLE:
288- org.apache.cassandra.exceptions.UnavailableException ue = (org.apache.cassandra.exceptions.UnavailableException)te;
289- return new UnavailableException(ConsistencyLevel.from(ue.consistency), ue.required, ue.alive);
290- case OVERLOADED:
291- return new DriverInternalError("Queried host was overloaded; this shouldn't happen, another node should have been tried");
292- case IS_BOOTSTRAPPING:
293- return new DriverInternalError("Queried host was boostrapping; this shouldn't happen, another node should have been tried");
294- case TRUNCATE_ERROR:
295- return new TruncateException(te.getMessage());
296- case WRITE_TIMEOUT:
297- org.apache.cassandra.exceptions.WriteTimeoutException wte = (org.apache.cassandra.exceptions.WriteTimeoutException)te;
298- return new WriteTimeoutException(ConsistencyLevel.from(wte.consistency), WriteType.from(wte.writeType), wte.received, wte.blockFor);
299- case READ_TIMEOUT:
300- org.apache.cassandra.exceptions.ReadTimeoutException rte = (org.apache.cassandra.exceptions.ReadTimeoutException)te;
301- return new ReadTimeoutException(ConsistencyLevel.from(rte.consistency), rte.received, rte.blockFor, rte.dataPresent);
302- case SYNTAX_ERROR:
303- return new SyntaxError(te.getMessage());
304- case UNAUTHORIZED:
305- return new UnauthorizedException(te.getMessage());
306- case INVALID:
307- return new InvalidQueryException(te.getMessage());
308- case CONFIG_ERROR:
309- return new InvalidConfigurationInQueryException(te.getMessage());
310- case ALREADY_EXISTS:
311- org.apache.cassandra.exceptions.AlreadyExistsException aee = (org.apache.cassandra.exceptions.AlreadyExistsException)te;
312- return new AlreadyExistsException(aee.ksName, aee.cfName);
313- default:
314- return new DriverInternalError("Unknown error return code: " + te.code());
315- }
316- }
123+ public boolean cancel(boolean mayInterruptIfRunning);
317124 }
modified driver-core/src/main/java/com/datastax/driver/core/Row.java +36 −259
@@ -32,31 +32,14 @@
3232 * or name. When setting them by name, names follow the case insensitivity
3333 * rules explained in {@link ColumnDefinitions}.
3434 */
35-public class Row {
36-
37- private final ColumnDefinitions metadata;
38- private final List<ByteBuffer> data;
39-
40- private Row(ColumnDefinitions metadata, List<ByteBuffer> data) {
41- this.metadata = metadata;
42- this.data = data;
43- }
44-
45- static Row fromData(ColumnDefinitions metadata, List<ByteBuffer> data) {
46- if (data == null)
47- return null;
48-
49- return new Row(metadata, data);
50- }
35+public interface Row {
5136
5237 /**
5338 * Returns the columns contained in this Row.
5439 *
5540 * @return the columns contained in this Row.
5641 */
57- public ColumnDefinitions getColumnDefinitions() {
58- return metadata;
59- }
42+ public ColumnDefinitions getColumnDefinitions();
6043
6144 /**
6245 * Returns whether the {@code i}th value of this row is NULL.
@@ -66,10 +49,7 @@
6649 *
6750 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
6851 */
69- public boolean isNull(int i) {
70- metadata.checkBounds(i);
71- return data.get(i) == null;
72- }
52+ public boolean isNull(int i);
7353
7454 /**
7555 * Returns whether the value for column {@code name} in this row is NULL.
@@ -80,9 +60,7 @@
8060 * @throws IllegalArgumentException if {@code name} is not part of the
8161 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
8262 */
83- public boolean isNull(String name) {
84- return isNull(metadata.getIdx(name));
85- }
63+ public boolean isNull(String name);
8664
8765 /**
8866 * Returns the {@code i}th value of this row as a boolean.
@@ -94,15 +72,7 @@
9472 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
9573 * @throws InvalidTypeException if column {@code i} is not of type BOOLEAN.
9674 */
97- public boolean getBool(int i) {
98- metadata.checkType(i, DataType.Name.BOOLEAN);
99-
100- ByteBuffer value = data.get(i);
101- if (value == null || value.remaining() == 0)
102- return false;
103-
104- return BooleanType.instance.compose(value);
105- }
75+ public boolean getBool(int i);
10676
10777 /**
10878 * Returns the value of column {@code name} as a boolean.
@@ -115,9 +85,7 @@
11585 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
11686 * @throws InvalidTypeException if column {@code name} is not of type BOOLEAN.
11787 */
118- public boolean getBool(String name) {
119- return getBool(metadata.getIdx(name));
120- }
88+ public boolean getBool(String name);
12189
12290 /**
12391 * Returns the {@code i}th value of this row as an integer.
@@ -129,15 +97,7 @@
12997 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
13098 * @throws InvalidTypeException if column {@code i} is not of type INT.
13199 */
132- public int getInt(int i) {
133- metadata.checkType(i, DataType.Name.INT);
134-
135- ByteBuffer value = data.get(i);
136- if (value == null || value.remaining() == 0)
137- return 0;
138-
139- return Int32Type.instance.compose(value);
140- }
100+ public int getInt(int i);
141101
142102 /**
143103 * Returns the value of column {@code name} as an integer.
@@ -150,9 +110,7 @@
150110 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
151111 * @throws InvalidTypeException if column {@code name} is not of type INT.
152112 */
153- public int getInt(String name) {
154- return getInt(metadata.getIdx(name));
155- }
113+ public int getInt(String name);
156114
157115 /**
158116 * Returns the {@code i}th value of this row as a long.
@@ -164,15 +122,7 @@
164122 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
165123 * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
166124 */
167- public long getLong(int i) {
168- metadata.checkType(i, DataType.Name.BIGINT, DataType.Name.COUNTER);
169-
170- ByteBuffer value = data.get(i);
171- if (value == null || value.remaining() == 0)
172- return 0L;
173-
174- return LongType.instance.compose(value);
175- }
125+ public long getLong(int i);
176126
177127 /**
178128 * Returns the value of column {@code name} as a long.
@@ -185,9 +135,7 @@
185135 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
186136 * @throws InvalidTypeException if column {@code i} is not of type BIGINT or COUNTER.
187137 */
188- public long getLong(String name) {
189- return getLong(metadata.getIdx(name));
190- }
138+ public long getLong(String name);
191139
192140 /**
193141 * Returns the {@code i}th value of this row as a date.
@@ -199,15 +147,7 @@
199147 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
200148 * @throws InvalidTypeException if column {@code i} is not of type TIMESTAMP.
201149 */
202- public Date getDate(int i) {
203- metadata.checkType(i, DataType.Name.TIMESTAMP);
204-
205- ByteBuffer value = data.get(i);
206- if (value == null || value.remaining() == 0)
207- return null;
208-
209- return DateType.instance.compose(value);
210- }
150+ public Date getDate(int i);
211151
212152 /**
213153 * Returns the value of column {@code name} as a date.
@@ -220,9 +160,7 @@
220160 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
221161 * @throws InvalidTypeException if column {@code name} is not of type TIMESTAMP.
222162 */
223- public Date getDate(String name) {
224- return getDate(metadata.getIdx(name));
225- }
163+ public Date getDate(String name);
226164
227165 /**
228166 * Returns the {@code i}th value of this row as a float.
@@ -234,15 +172,7 @@
234172 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
235173 * @throws InvalidTypeException if column {@code i} is not of type FLOAT.
236174 */
237- public float getFloat(int i) {
238- metadata.checkType(i, DataType.Name.FLOAT);
239-
240- ByteBuffer value = data.get(i);
241- if (value == null || value.remaining() == 0)
242- return 0.0f;
243-
244- return FloatType.instance.compose(value);
245- }
175+ public float getFloat(int i);
246176
247177 /**
248178 * Returns the value of column {@code name} as a float.
@@ -255,9 +185,7 @@
255185 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
256186 * @throws InvalidTypeException if column {@code name} is not of type FLOAT.
257187 */
258- public float getFloat(String name) {
259- return getFloat(metadata.getIdx(name));
260- }
188+ public float getFloat(String name);
261189
262190 /**
263191 * Returns the {@code i}th value of this row as a double.
@@ -269,15 +197,7 @@
269197 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
270198 * @throws InvalidTypeException if column {@code i} is not of type DOUBLE.
271199 */
272- public double getDouble(int i) {
273- metadata.checkType(i, DataType.Name.DOUBLE);
274-
275- ByteBuffer value = data.get(i);
276- if (value == null || value.remaining() == 0)
277- return 0.0;
278-
279- return DoubleType.instance.compose(value);
280- }
200+ public double getDouble(int i);
281201
282202 /**
283203 * Returns the value of column {@code name} as a double.
@@ -290,9 +210,7 @@
290210 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
291211 * @throws InvalidTypeException if column {@code name} is not of type DOUBLE.
292212 */
293- public double getDouble(String name) {
294- return getDouble(metadata.getIdx(name));
295- }
213+ public double getDouble(String name);
296214
297215 /**
298216 * Returns the {@code i}th value of this row as a ByteBuffer.
@@ -308,15 +226,7 @@
308226 *
309227 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
310228 */
311- public ByteBuffer getBytesUnsafe(int i) {
312- metadata.checkBounds(i);
313-
314- ByteBuffer value = data.get(i);
315- if (value == null)
316- return null;
317-
318- return value.duplicate();
319- }
229+ public ByteBuffer getBytesUnsafe(int i);
320230
321231 /**
322232 * Returns the value of column {@code name} as a ByteBuffer.
@@ -333,9 +243,7 @@
333243 * @throws IllegalArgumentException if {@code name} is not part of the
334244 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
335245 */
336- public ByteBuffer getBytesUnsafe(String name) {
337- return getBytesUnsafe(metadata.getIdx(name));
338- }
246+ public ByteBuffer getBytesUnsafe(String name);
339247
340248 /**
341249 * Returns the {@code i}th value of this row as a byte array.
@@ -350,10 +258,7 @@
350258 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
351259 * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
352260 */
353- public ByteBuffer getBytes(int i) {
354- metadata.checkType(i, DataType.Name.BLOB);
355- return getBytesUnsafe(i);
356- }
261+ public ByteBuffer getBytes(int i);
357262
358263 /**
359264 * Returns the value of column {@code name} as a byte array.
@@ -369,9 +274,7 @@
369274 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
370275 * @throws InvalidTypeException if column {@code i} type is not of type BLOB.
371276 */
372- public ByteBuffer getBytes(String name) {
373- return getBytes(metadata.getIdx(name));
374- }
277+ public ByteBuffer getBytes(String name);
375278
376279 /**
377280 * Returns the {@code i}th value of this row as a string.
@@ -384,19 +287,7 @@
384287 * @throws InvalidTypeException if column {@code i} type is none of:
385288 * VARCHAR, TEXT or ASCII.
386289 */
387- public String getString(int i) {
388- DataType.Name type = metadata.checkType(i, DataType.Name.VARCHAR,
389- DataType.Name.TEXT,
390- DataType.Name.ASCII);
391-
392- ByteBuffer value = data.get(i);
393- if (value == null)
394- return null;
395-
396- return type == DataType.Name.ASCII
397- ? AsciiType.instance.compose(value)
398- : UTF8Type.instance.compose(value);
399- }
290+ public String getString(int i);
400291
401292 /**
402293 * Returns the value of column {@code name} as a string.
@@ -410,9 +301,7 @@
410301 * @throws InvalidTypeException if column {@code name} type is none of:
411302 * VARCHAR, TEXT or ASCII.
412303 */
413- public String getString(String name) {
414- return getString(metadata.getIdx(name));
415- }
304+ public String getString(String name);
416305
417306 /**
418307 * Returns the {@code i}th value of this row as a variable length integer.
@@ -424,15 +313,7 @@
424313 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
425314 * @throws InvalidTypeException if column {@code i} is not of type VARINT.
426315 */
427- public BigInteger getVarint(int i) {
428- metadata.checkType(i, DataType.Name.VARINT);
429-
430- ByteBuffer value = data.get(i);
431- if (value == null || value.remaining() == 0)
432- return null;
433-
434- return IntegerType.instance.compose(value);
435- }
316+ public BigInteger getVarint(int i);
436317
437318 /**
438319 * Returns the value of column {@code name} as a variable length integer.
@@ -445,9 +326,7 @@
445326 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
446327 * @throws InvalidTypeException if column {@code name} is not of type VARINT.
447328 */
448- public BigInteger getVarint(String name) {
449- return getVarint(metadata.getIdx(name));
450- }
329+ public BigInteger getVarint(String name);
451330
452331 /**
453332 * Returns the {@code i}th value of this row as a variable length decimal.
@@ -459,15 +338,7 @@
459338 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
460339 * @throws InvalidTypeException if column {@code i} is not of type DECIMAL.
461340 */
462- public BigDecimal getDecimal(int i) {
463- metadata.checkType(i, DataType.Name.DECIMAL);
464-
465- ByteBuffer value = data.get(i);
466- if (value == null || value.remaining() == 0)
467- return null;
468-
469- return DecimalType.instance.compose(value);
470- }
341+ public BigDecimal getDecimal(int i);
471342
472343 /**
473344 * Returns the value of column {@code name} as a variable length decimal.
@@ -480,9 +351,7 @@
480351 * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}.
481352 * @throws InvalidTypeException if column {@code name} is not of type DECIMAL.
482353 */
483- public BigDecimal getDecimal(String name) {
484- return getDecimal(metadata.getIdx(name));
485- }
354+ public BigDecimal getDecimal(String name);
486355
487356 /**
488357 * Returns the {@code i}th value of this row as a UUID.
@@ -495,17 +364,7 @@
495364 * @throws InvalidTypeException if column {@code i} is not of type UUID
496365 * or TIMEUUID.
497366 */
498- public UUID getUUID(int i) {
499- DataType.Name type = metadata.checkType(i, DataType.Name.UUID, DataType.Name.TIMEUUID);
500-
501- ByteBuffer value = data.get(i);
502- if (value == null || value.remaining() == 0)
503- return null;
504-
505- return type == DataType.Name.UUID
506- ? UUIDType.instance.compose(value)
507- : TimeUUIDType.instance.compose(value);
508- }
367+ public UUID getUUID(int i);
509368
510369 /**
511370 * Returns the value of column {@code name} as a UUID.
@@ -519,9 +378,7 @@
519378 * @throws InvalidTypeException if column {@code name} is not of type
520379 * UUID or TIMEUUID.
521380 */
522- public UUID getUUID(String name) {
523- return getUUID(metadata.getIdx(name));
524- }
381+ public UUID getUUID(String name);
525382
526383 /**
527384 * Returns the {@code i}th value of this row as an InetAddress.
@@ -533,15 +390,7 @@
533390 * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}.
534391 * @throws InvalidTypeException if column {@code i} is not of type INET.
535392 */
536- public InetAddress getInet(int i) {
537- metadata.checkType(i, DataType.Name.INET);
538-
539- ByteBuffer value = data.get(i);
540- if (value == null || value.remaining() == 0)
541- return null;
542-
543- return InetAddressType.instance.compose(value);
544- }
393+ public InetAddress getInet(int i);
545394
546395 /**
547396 * Returns the value of column {@code name} as an InetAddress.
@@ -555,9 +404,7 @@
555404 * @throws InvalidTypeException if column {@code name} is not of type
556405 * INET.
557406 */
558- public InetAddress getInet(String name) {
559- return getInet(metadata.getIdx(name));
560- }
407+ public InetAddress getInet(String name);
561408
562409 /**
563410 * Returns the {@code i}th value of this row as a list.
@@ -573,23 +420,7 @@
573420 * @throws InvalidTypeException if column {@code i} is not a list or if its
574421 * elements are not of class {@code elementsClass}.
575422 */
576- @SuppressWarnings("unchecked")
577- public <T> List<T> getList(int i, Class<T> elementsClass) {
578- DataType type = metadata.getType(i);
579- if (type.getName() != DataType.Name.LIST)
580- throw new InvalidTypeException(String.format("Column %s is not of list type", metadata.getName(i)));
581-
582- Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
583- if (!elementsClass.isAssignableFrom(expectedClass))
584- throw new InvalidTypeException(String.format("Column %s is a list of %s (CQL type %s), cannot be retrieve as a list of %s", metadata.getName(i), expectedClass, type, elementsClass));
585-
586- ByteBuffer value = data.get(i);
587- if (value == null)
588- return Collections.<T>emptyList();
589-
590- // TODO: we could avoid the getCodec call if we kept a reference to the original message.
591- return Collections.unmodifiableList(Codec.<List<T>>getCodec(type).compose(value));
592- }
423+ public <T> List<T> getList(int i, Class<T> elementsClass);
593424
594425 /**
595426 * Returns the value of column {@code name} as a list.
@@ -606,9 +437,7 @@
606437 * @throws InvalidTypeException if column {@code name} is not a list or if its
607438 * elements are not of class {@code elementsClass}.
608439 */
609- public <T> List<T> getList(String name, Class<T> elementsClass) {
610- return getList(metadata.getIdx(name), elementsClass);
611- }
440+ public <T> List<T> getList(String name, Class<T> elementsClass);
612441
613442 /**
614443 * Returns the {@code i}th value of this row as a set.
@@ -624,22 +453,7 @@
624453 * @throws InvalidTypeException if column {@code i} is not a set or if its
625454 * elements are not of class {@code elementsClass}.
626455 */
627- @SuppressWarnings("unchecked")
628- public <T> Set<T> getSet(int i, Class<T> elementsClass) {
629- DataType type = metadata.getType(i);
630- if (type.getName() != DataType.Name.SET)
631- throw new InvalidTypeException(String.format("Column %s is not of set type", metadata.getName(i)));
632-
633- Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
634- if (!elementsClass.isAssignableFrom(expectedClass))
635- throw new InvalidTypeException(String.format("Column %s is a set of %s (CQL type %s), cannot be retrieve as a set of %s", metadata.getName(i), expectedClass, type, elementsClass));
636-
637- ByteBuffer value = data.get(i);
638- if (value == null)
639- return Collections.<T>emptySet();
640-
641- return Collections.unmodifiableSet(Codec.<Set<T>>getCodec(type).compose(value));
642- }
456+ public <T> Set<T> getSet(int i, Class<T> elementsClass);
643457
644458 /**
645459 * Returns the value of column {@code name} as a set.
@@ -656,9 +470,7 @@
656470 * @throws InvalidTypeException if column {@code name} is not a set or if its
657471 * elements are not of class {@code elementsClass}.
658472 */
659- public <T> Set<T> getSet(String name, Class<T> elementsClass) {
660- return getSet(metadata.getIdx(name), elementsClass);
661- }
473+ public <T> Set<T> getSet(String name, Class<T> elementsClass);
662474
663475 /**
664476 * Returns the {@code i}th value of this row as a map.
@@ -677,23 +489,7 @@
677489 * keys are not of class {@code keysClass} or if its values are not of
678490 * class {@code valuesClass}.
679491 */
680- @SuppressWarnings("unchecked")
681- public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) {
682- DataType type = metadata.getType(i);
683- if (type.getName() != DataType.Name.MAP)
684- throw new InvalidTypeException(String.format("Column %s is not of map type", metadata.getName(i)));
685-
686- Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType;
687- Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType;
688- if (!keysClass.isAssignableFrom(expectedKeysClass) || !valuesClass.isAssignableFrom(expectedValuesClass))
689- throw new InvalidTypeException(String.format("Column %s is a map of %s->%s (CQL type %s), cannot be retrieve as a map of %s->%s", metadata.getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass));
690-
691- ByteBuffer value = data.get(i);
692- if (value == null)
693- return Collections.<K, V>emptyMap();
694-
695- return Collections.unmodifiableMap(Codec.<Map<K, V>>getCodec(type).compose(value));
696- }
492+ public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass);
697493
698494 /**
699495 * Returns the value of column {@code name} as a map.
@@ -713,24 +509,5 @@
713509 * keys are not of class {@code keysClass} or if its values are not of
714510 * class {@code valuesClass}.
715511 */
716- public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass) {
717- return getMap(metadata.getIdx(name), keysClass, valuesClass);
718- }
719-
720- @Override
721- public String toString() {
722- StringBuilder sb = new StringBuilder();
723- sb.append("Row[");
724- for (int i = 0; i < metadata.size(); i++) {
725- if (i != 0)
726- sb.append(", ");
727- ByteBuffer bb = data.get(i);
728- if (bb == null)
729- sb.append("NULL");
730- else
731- sb.append(Codec.getCodec(metadata.getType(i)).getString(bb));
732- }
733- sb.append("]");
734- return sb.toString();
735- }
512+ public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass);
736513 }
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +10 −305
@@ -48,16 +48,7 @@
4848 * per application. However, a given session can only be set to one keyspace
4949 * at a time, so one instance per keyspace is necessary.
5050 */
51-public class Session {
52-
53- private static final Logger logger = LoggerFactory.getLogger(Session.class);
54-
55- final Manager manager;
56-
57- // Package protected, only Cluster should construct that.
58- Session(Cluster cluster, Collection<Host> hosts) {
59- this.manager = new Manager(cluster, hosts);
60- }
51+public interface Session {
6152
6253 /**
6354 * Executes the provided query.
@@ -76,9 +67,7 @@
7667 * @throws QueryValidationException if the query if invalid (syntax error,
7768 * unauthorized or any other validation problem).
7869 */
79- public ResultSet execute(String query) {
80- return execute(new SimpleStatement(query));
81- }
70+ public ResultSet execute(String query);
8271
8372 /**
8473 * Executes the provided query.
@@ -107,9 +96,7 @@
10796 * @throws IllegalStateException if {@code query} is a {@code BoundStatement}
10897 * but {@code !query.isReady()}.
10998 */
110- public ResultSet execute(Query query) {
111- return executeAsync(query).getUninterruptibly();
112- }
99+ public ResultSet execute(Query query);
113100
114101 /**
115102 * Executes the provided query asynchronously.
@@ -119,9 +106,7 @@
119106 * @param query the CQL query to execute.
120107 * @return a future on the result of the query.
121108 */
122- public ResultSetFuture executeAsync(String query) {
123- return executeAsync(new SimpleStatement(query));
124- }
109+ public ResultSetFuture executeAsync(String query);
125110
126111 /**
127112 * Executes the provided query asynchronously.
@@ -145,17 +130,7 @@
145130 * @throws IllegalStateException if {@code query} is a {@code BoundStatement}
146131 * but {@code !query.isReady()}.
147132 */
148- public ResultSetFuture executeAsync(Query query) {
149-
150- if (query instanceof Statement) {
151- return manager.executeQuery(new QueryMessage(((Statement)query).getQueryString(), ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())), query);
152- } else {
153- assert query instanceof BoundStatement : query;
154-
155- BoundStatement bs = (BoundStatement)query;
156- return manager.executeQuery(new ExecuteMessage(bs.statement.id, Arrays.asList(bs.values), ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())), query);
157- }
158- }
133+ public ResultSetFuture executeAsync(Query query);
159134
160135 /**
161136 * Prepares the provided query string.
@@ -166,11 +141,7 @@
166141 * @throws NoHostAvailableException if no host in the cluster can be
167142 * contacted successfully to prepare this query.
168143 */
169- public PreparedStatement prepare(String query) {
170- Connection.Future future = new Connection.Future(new PrepareMessage(query));
171- manager.execute(future, Query.DEFAULT);
172- return toPreparedStatement(query, future);
173- }
144+ public PreparedStatement prepare(String query);
174145
175146 /**
176147 * Prepares the provided query.
@@ -191,19 +162,7 @@
191162 * @throws NoHostAvailableException if no host in the cluster can be
192163 * contacted successfully to prepare this statement.
193164 */
194- public PreparedStatement prepare(Statement statement) {
195- PreparedStatement prepared = prepare(statement.getQueryString());
196-
197- ByteBuffer routingKey = statement.getRoutingKey();
198- if (routingKey != null)
199- prepared.setRoutingKey(routingKey);
200- prepared.setConsistencyLevel(statement.getConsistencyLevel());
201- if (statement.isTracing())
202- prepared.enableTracing();
203- prepared.setRetryPolicy(statement.getRetryPolicy());
204-
205- return prepared;
206- }
165+ public PreparedStatement prepare(Statement statement);
207166
208167 /**
209168 * Shuts down this session instance.
@@ -215,9 +174,7 @@
215174 * <p>
216175 * This method has no effect if the session was already shutdown.
217176 */
218- public void shutdown() {
219- shutdown(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
220- }
177+ public void shutdown();
221178
222179 /**
223180 * Shutdown this session instance, only waiting a definite amount of time.
@@ -236,264 +193,12 @@
236193 * @return {@code true} if the session has been properly shutdown within
237194 * the {@code timeout}, {@code false} otherwise.
238195 */
239- public boolean shutdown(long timeout, TimeUnit unit) {
240- try {
241- return manager.shutdown(timeout, unit);
242- } catch (InterruptedException e) {
243- Thread.currentThread().interrupt();
244- return false;
245- }
246- }
196+ public boolean shutdown(long timeout, TimeUnit unit);
247197
248198 /**
249199 * Returns the {@code Cluster} object this session is part of.
250200 *
251201 * @return the {@code Cluster} object this session is part of.
252202 */
253- public Cluster getCluster() {
254- return manager.cluster;
255- }
256-
257- private PreparedStatement toPreparedStatement(String query, Connection.Future future) {
258-
259- try {
260- Message.Response response = Uninterruptibles.getUninterruptibly(future);
261- switch (response.type) {
262- case RESULT:
263- ResultMessage rm = (ResultMessage)response;
264- switch (rm.kind) {
265- case PREPARED:
266- ResultMessage.Prepared pmsg = (ResultMessage.Prepared)rm;
267- PreparedStatement stmt = PreparedStatement.fromMessage(pmsg, manager.cluster.getMetadata(), query, manager.poolsState.keyspace);
268- try {
269- manager.cluster.manager.prepare(stmt, future.getAddress());
270- } catch (InterruptedException e) {
271- Thread.currentThread().interrupt();
272- // This method doesn't propagate interruption, at least not for now. However, if we've
273- // interrupted preparing queries on other node it's not a problem as we'll re-prepare
274- // later if need be. So just ignore.
275- }
276- return stmt;
277- default:
278- throw new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind));
279- }
280- case ERROR:
281- ResultSetFuture.extractCause(ResultSetFuture.convertException(((ErrorMessage)response).error));
282- break;
283- default:
284- throw new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type));
285- }
286- throw new AssertionError();
287- } catch (ExecutionException e) {
288- ResultSetFuture.extractCauseFromExecutionException(e);
289- throw new AssertionError();
290- }
291- }
292-
293- static class Manager {
294-
295- final Cluster cluster;
296-
297- final ConcurrentMap<Host, HostConnectionPool> pools;
298-
299- final HostConnectionPool.PoolState poolsState;
300-
301- final AtomicBoolean isShutdown = new AtomicBoolean(false);
302-
303- public Manager(Cluster cluster, Collection<Host> hosts) {
304- this.cluster = cluster;
305-
306- this.pools = new ConcurrentHashMap<Host, HostConnectionPool>(hosts.size());
307- this.poolsState = new HostConnectionPool.PoolState();
308-
309- // Create pool to initial nodes (and wait for them to be created)
310- for (Host host : hosts) {
311- try {
312- addOrRenewPool(host, false).get();
313- } catch (ExecutionException e) {
314- // This is not supposed to happen
315- throw new DriverInternalError(e);
316- } catch (InterruptedException e) {
317- Thread.currentThread().interrupt();
318- }
319- }
320- }
321-
322- public Connection.Factory connectionFactory() {
323- return cluster.manager.connectionFactory;
324- }
325-
326- public Configuration configuration() {
327- return cluster.manager.configuration;
328- }
329-
330- LoadBalancingPolicy loadBalancingPolicy() {
331- return cluster.manager.loadBalancingPolicy();
332- }
333-
334- ReconnectionPolicy reconnectionPolicy() {
335- return cluster.manager.reconnectionPolicy();
336- }
337-
338- public ListeningExecutorService executor() {
339- return cluster.manager.executor;
340- }
341-
342- public ListeningExecutorService blockingExecutor() {
343- return cluster.manager.blockingTasksExecutor;
344- }
345-
346- private boolean shutdown(long timeout, TimeUnit unit) throws InterruptedException {
347-
348- if (!isShutdown.compareAndSet(false, true))
349- return true;
350-
351- long start = System.nanoTime();
352- boolean success = true;
353- for (HostConnectionPool pool : pools.values())
354- success &= pool.shutdown(timeout - Cluster.timeSince(start, unit), unit);
355- return success;
356- }
357-
358- ListenableFuture<Boolean> addOrRenewPool(final Host host, final boolean isHostAddition) {
359- final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
360- if (distance == HostDistance.IGNORED)
361- return Futures.immediateFuture(true);
362-
363- // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously.
364- return executor().submit(new Callable<Boolean>() {
365- public Boolean call() {
366- logger.debug("Adding {} to list of queried hosts", host);
367- try {
368- HostConnectionPool previous = pools.put(host, new HostConnectionPool(host, distance, Session.Manager.this));
369- if (previous != null)
370- previous.shutdown(); // The previous was probably already shutdown but that's ok
371- return true;
372- } catch (AuthenticationException e) {
373- logger.error("Error creating pool to {} ({})", host, e.getMessage());
374- cluster.manager.signalConnectionFailure(host, new ConnectionException(e.getHost(), e.getMessage()), isHostAddition);
375- return false;
376- } catch (ConnectionException e) {
377- logger.debug("Error creating pool to {} ({})", host, e.getMessage());
378- cluster.manager.signalConnectionFailure(host, e, isHostAddition);
379- return false;
380- }
381- }
382- });
383- }
384-
385- ListenableFuture<?> removePool(Host host) {
386- final HostConnectionPool pool = pools.remove(host);
387- if (pool == null)
388- return Futures.immediateFuture(null);
389-
390- // Shutdown can take some time and we don't care about holding the thread on that.
391- return executor().submit(new Runnable() {
392- public void run() {
393- pool.shutdown();
394- }
395- });
396- }
397-
398- /*
399- * When the set of live nodes change, the loadbalancer will change his
400- * mind on host distances. It might change it on the node that came/left
401- * but also on other nodes (for instance, if a node dies, another
402- * previously ignored node may be now considered).
403- *
404- * This method ensures that all hosts for which a pool should exist
405- * have one, and hosts that shouldn't don't.
406- */
407- void updateCreatedPools() {
408- for (Host h : cluster.getMetadata().allHosts()) {
409- HostDistance dist = loadBalancingPolicy().distance(h);
410- HostConnectionPool pool = pools.get(h);
411-
412- if (pool == null) {
413- if (dist != HostDistance.IGNORED && h.isUp())
414- addOrRenewPool(h, false);
415- } else if (dist != pool.hostDistance) {
416- if (dist == HostDistance.IGNORED) {
417- removePool(h);
418- } else {
419- pool.hostDistance = dist;
420- }
421- }
422- }
423- }
424-
425- public void onDown(Host host) {
426- // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary
427- // since updateCreatedPools should take care of it. But better protect against non well behaving policies.
428- removePool(host).addListener(new Runnable() {
429- public void run() {
430- updateCreatedPools();
431- }
432- }, MoreExecutors.sameThreadExecutor());
433- }
434-
435- public void onRemove(Host host) {
436- onDown(host);
437- }
438-
439- public void setKeyspace(String keyspace) {
440- long timeout = configuration().getSocketOptions().getConnectTimeoutMillis();
441- try {
442- Future<?> future = executeQuery(new QueryMessage("use " + keyspace, ConsistencyLevel.DEFAULT_CASSANDRA_CL), Query.DEFAULT);
443- // Note: using the connection timeout is perfectly correct, we should probably change that someday
444- Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
445- } catch (TimeoutException e) {
446- throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout));
447- } catch (ExecutionException e) {
448- ResultSetFuture.extractCauseFromExecutionException(e);
449- }
450- }
451-
452- /**
453- * Execute the provided request.
454- *
455- * This method will find a suitable node to connect to using the
456- * {@link LoadBalancingPolicy} and handle host failover.
457- */
458- public void execute(RequestHandler.Callback callback, Query query) {
459- new RequestHandler(this, callback, query).sendRequest();
460- }
461-
462- public void prepare(String query, InetAddress toExclude) throws InterruptedException {
463- for (Map.Entry<Host, HostConnectionPool> entry : pools.entrySet()) {
464- if (entry.getKey().getAddress().equals(toExclude))
465- continue;
466-
467- // Let's not wait too long if we can't get a connection. Things
468- // will fix themselves once the user tries a query anyway.
469- Connection c = null;
470- try {
471- c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
472- c.write(new PrepareMessage(query)).get();
473- } catch (ConnectionException e) {
474- // Again, not being able to prepare the query right now is no big deal, so just ignore
475- } catch (BusyConnectionException e) {
476- // Same as above
477- } catch (TimeoutException e) {
478- // Same as above
479- } catch (ExecutionException e) {
480- // We shouldn't really get exception while preparing a
481- // query, so log this (but ignore otherwise as it's not a big deal)
482- logger.error(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), e);
483- } finally {
484- if (c != null)
485- entry.getValue().returnConnection(c);
486- }
487- }
488- }
489-
490- public ResultSetFuture executeQuery(Message.Request msg, Query query) {
491- if (query.isTracing())
492- msg.setTracingRequested();
493-
494- ResultSetFuture future = new ResultSetFuture(this, msg);
495- execute(future.callback, query);
496- return future;
497- }
498- }
203+ public Cluster getCluster();
499204 }
added driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +338 −0
@@ -0,0 +1,338 @@
1+/*
2+ * Copyright (C) 2012 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.net.InetAddress;
19+import java.nio.ByteBuffer;
20+import java.util.*;
21+import java.util.concurrent.*;
22+import java.util.concurrent.atomic.AtomicBoolean;
23+
24+import com.google.common.util.concurrent.Futures;
25+import com.google.common.util.concurrent.ListenableFuture;
26+import com.google.common.util.concurrent.ListeningExecutorService;
27+import com.google.common.util.concurrent.MoreExecutors;
28+import com.google.common.util.concurrent.Uninterruptibles;
29+
30+import com.datastax.driver.core.exceptions.*;
31+import com.datastax.driver.core.policies.*;
32+
33+import org.apache.cassandra.transport.Message;
34+import org.apache.cassandra.transport.messages.*;
35+
36+import org.slf4j.Logger;
37+import org.slf4j.LoggerFactory;
38+
39+/**
40+ * Driver implementation of the Session interface.
41+ */
42+class SessionManager implements Session {
43+
44+ private static final Logger logger = LoggerFactory.getLogger(Session.class);
45+
46+ final Cluster cluster;
47+ final ConcurrentMap<Host, HostConnectionPool> pools;
48+ final HostConnectionPool.PoolState poolsState;
49+ final AtomicBoolean isShutdown = new AtomicBoolean(false);
50+
51+ // Package protected, only Cluster should construct that.
52+ SessionManager(Cluster cluster, Collection<Host> hosts) {
53+ this.cluster = cluster;
54+
55+ this.pools = new ConcurrentHashMap<Host, HostConnectionPool>(hosts.size());
56+ this.poolsState = new HostConnectionPool.PoolState();
57+
58+ // Create pool to initial nodes (and wait for them to be created)
59+ for (Host host : hosts) {
60+ try {
61+ addOrRenewPool(host, false).get();
62+ } catch (ExecutionException e) {
63+ // This is not supposed to happen
64+ throw new DriverInternalError(e);
65+ } catch (InterruptedException e) {
66+ Thread.currentThread().interrupt();
67+ }
68+ }
69+ }
70+
71+ public ResultSet execute(String query) {
72+ return execute(new SimpleStatement(query));
73+ }
74+
75+ public ResultSet execute(Query query) {
76+ return executeAsync(query).getUninterruptibly();
77+ }
78+
79+ public ResultSetFuture executeAsync(String query) {
80+ return executeAsync(new SimpleStatement(query));
81+ }
82+
83+ public ResultSetFuture executeAsync(Query query) {
84+
85+ if (query instanceof Statement) {
86+ return executeQuery(new QueryMessage(((Statement)query).getQueryString(), ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())), query);
87+ } else {
88+ assert query instanceof BoundStatement : query;
89+
90+ BoundStatement bs = (BoundStatement)query;
91+ return executeQuery(new ExecuteMessage(bs.statement.id, Arrays.asList(bs.values), ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())), query);
92+ }
93+ }
94+
95+ public PreparedStatement prepare(String query) {
96+ Connection.Future future = new Connection.Future(new PrepareMessage(query));
97+ execute(future, Query.DEFAULT);
98+ return toPreparedStatement(query, future);
99+ }
100+
101+ public PreparedStatement prepare(Statement statement) {
102+ PreparedStatement prepared = prepare(statement.getQueryString());
103+
104+ ByteBuffer routingKey = statement.getRoutingKey();
105+ if (routingKey != null)
106+ prepared.setRoutingKey(routingKey);
107+ prepared.setConsistencyLevel(statement.getConsistencyLevel());
108+ if (statement.isTracing())
109+ prepared.enableTracing();
110+ prepared.setRetryPolicy(statement.getRetryPolicy());
111+
112+ return prepared;
113+ }
114+
115+ public void shutdown() {
116+ shutdown(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
117+ }
118+
119+ public boolean shutdown(long timeout, TimeUnit unit) {
120+ if (!isShutdown.compareAndSet(false, true))
121+ return true;
122+
123+ try {
124+ long start = System.nanoTime();
125+ boolean success = true;
126+ for (HostConnectionPool pool : pools.values())
127+ success &= pool.shutdown(timeout - Cluster.timeSince(start, unit), unit);
128+ return success;
129+ } catch (InterruptedException e) {
130+ Thread.currentThread().interrupt();
131+ return false;
132+ }
133+ }
134+
135+ public Cluster getCluster() {
136+ return cluster;
137+ }
138+
139+ private PreparedStatement toPreparedStatement(String query, Connection.Future future) {
140+ try {
141+ Message.Response response = Uninterruptibles.getUninterruptibly(future);
142+ switch (response.type) {
143+ case RESULT:
144+ ResultMessage rm = (ResultMessage)response;
145+ switch (rm.kind) {
146+ case PREPARED:
147+ ResultMessage.Prepared pmsg = (ResultMessage.Prepared)rm;
148+ PreparedStatement stmt = PreparedStatement.fromMessage(pmsg, cluster.getMetadata(), query, poolsState.keyspace);
149+ try {
150+ cluster.manager.prepare(stmt, future.getAddress());
151+ } catch (InterruptedException e) {
152+ Thread.currentThread().interrupt();
153+ // This method doesn't propagate interruption, at least not for now. However, if we've
154+ // interrupted preparing queries on other node it's not a problem as we'll re-prepare
155+ // later if need be. So just ignore.
156+ }
157+ return stmt;
158+ default:
159+ throw new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind));
160+ }
161+ case ERROR:
162+ DefaultResultSetFuture.extractCause(DefaultResultSetFuture.convertException(((ErrorMessage)response).error));
163+ break;
164+ default:
165+ throw new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type));
166+ }
167+ throw new AssertionError();
168+ } catch (ExecutionException e) {
169+ DefaultResultSetFuture.extractCauseFromExecutionException(e);
170+ throw new AssertionError();
171+ }
172+ }
173+
174+ Connection.Factory connectionFactory() {
175+ return cluster.manager.connectionFactory;
176+ }
177+
178+ Configuration configuration() {
179+ return cluster.manager.configuration;
180+ }
181+
182+ LoadBalancingPolicy loadBalancingPolicy() {
183+ return cluster.manager.loadBalancingPolicy();
184+ }
185+
186+ ReconnectionPolicy reconnectionPolicy() {
187+ return cluster.manager.reconnectionPolicy();
188+ }
189+
190+ ListeningExecutorService executor() {
191+ return cluster.manager.executor;
192+ }
193+
194+ ListeningExecutorService blockingExecutor() {
195+ return cluster.manager.blockingTasksExecutor;
196+ }
197+
198+ ListenableFuture<Boolean> addOrRenewPool(final Host host, final boolean isHostAddition) {
199+ final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
200+ if (distance == HostDistance.IGNORED)
201+ return Futures.immediateFuture(true);
202+
203+ // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously.
204+ return executor().submit(new Callable<Boolean>() {
205+ public Boolean call() {
206+ logger.debug("Adding {} to list of queried hosts", host);
207+ try {
208+ HostConnectionPool previous = pools.put(host, new HostConnectionPool(host, distance, SessionManager.this));
209+ if (previous != null)
210+ previous.shutdown(); // The previous was probably already shutdown but that's ok
211+ return true;
212+ } catch (AuthenticationException e) {
213+ logger.error("Error creating pool to {} ({})", host, e.getMessage());
214+ cluster.manager.signalConnectionFailure(host, new ConnectionException(e.getHost(), e.getMessage()), isHostAddition);
215+ return false;
216+ } catch (ConnectionException e) {
217+ logger.debug("Error creating pool to {} ({})", host, e.getMessage());
218+ cluster.manager.signalConnectionFailure(host, e, isHostAddition);
219+ return false;
220+ }
221+ }
222+ });
223+ }
224+
225+ ListenableFuture<?> removePool(Host host) {
226+ final HostConnectionPool pool = pools.remove(host);
227+ if (pool == null)
228+ return Futures.immediateFuture(null);
229+
230+ // Shutdown can take some time and we don't care about holding the thread on that.
231+ return executor().submit(new Runnable() {
232+ public void run() {
233+ pool.shutdown();
234+ }
235+ });
236+ }
237+
238+ /*
239+ * When the set of live nodes change, the loadbalancer will change his
240+ * mind on host distances. It might change it on the node that came/left
241+ * but also on other nodes (for instance, if a node dies, another
242+ * previously ignored node may be now considered).
243+ *
244+ * This method ensures that all hosts for which a pool should exist
245+ * have one, and hosts that shouldn't don't.
246+ */
247+ void updateCreatedPools() {
248+ for (Host h : cluster.getMetadata().allHosts()) {
249+ HostDistance dist = loadBalancingPolicy().distance(h);
250+ HostConnectionPool pool = pools.get(h);
251+
252+ if (pool == null) {
253+ if (dist != HostDistance.IGNORED && h.isUp())
254+ addOrRenewPool(h, false);
255+ } else if (dist != pool.hostDistance) {
256+ if (dist == HostDistance.IGNORED) {
257+ removePool(h);
258+ } else {
259+ pool.hostDistance = dist;
260+ }
261+ }
262+ }
263+ }
264+
265+ void onDown(Host host) {
266+ // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary
267+ // since updateCreatedPools should take care of it. But better protect against non well behaving policies.
268+ removePool(host).addListener(new Runnable() {
269+ public void run() {
270+ updateCreatedPools();
271+ }
272+ }, MoreExecutors.sameThreadExecutor());
273+ }
274+
275+ void onRemove(Host host) {
276+ onDown(host);
277+ }
278+
279+ void setKeyspace(String keyspace) {
280+ long timeout = configuration().getSocketOptions().getConnectTimeoutMillis();
281+ try {
282+ Future<?> future = executeQuery(new QueryMessage("use " + keyspace, ConsistencyLevel.DEFAULT_CASSANDRA_CL), Query.DEFAULT);
283+ // Note: using the connection timeout is perfectly correct, we should probably change that someday
284+ Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
285+ } catch (TimeoutException e) {
286+ throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout));
287+ } catch (ExecutionException e) {
288+ DefaultResultSetFuture.extractCauseFromExecutionException(e);
289+ }
290+ }
291+
292+ /**
293+ * Execute the provided request.
294+ *
295+ * This method will find a suitable node to connect to using the
296+ * {@link LoadBalancingPolicy} and handle host failover.
297+ */
298+ void execute(RequestHandler.Callback callback, Query query) {
299+ new RequestHandler(this, callback, query).sendRequest();
300+ }
301+
302+ void prepare(String query, InetAddress toExclude) throws InterruptedException {
303+ for (Map.Entry<Host, HostConnectionPool> entry : pools.entrySet()) {
304+ if (entry.getKey().getAddress().equals(toExclude))
305+ continue;
306+
307+ // Let's not wait too long if we can't get a connection. Things
308+ // will fix themselves once the user tries a query anyway.
309+ Connection c = null;
310+ try {
311+ c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
312+ c.write(new PrepareMessage(query)).get();
313+ } catch (ConnectionException e) {
314+ // Again, not being able to prepare the query right now is no big deal, so just ignore
315+ } catch (BusyConnectionException e) {
316+ // Same as above
317+ } catch (TimeoutException e) {
318+ // Same as above
319+ } catch (ExecutionException e) {
320+ // We shouldn't really get exception while preparing a
321+ // query, so log this (but ignore otherwise as it's not a big deal)
322+ logger.error(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), e);
323+ } finally {
324+ if (c != null)
325+ entry.getValue().returnConnection(c);
326+ }
327+ }
328+ }
329+
330+ ResultSetFuture executeQuery(Message.Request msg, Query query) {
331+ if (query.isTracing())
332+ msg.setTracingRequested();
333+
334+ DefaultResultSetFuture future = new DefaultResultSetFuture(this, msg);
335+ execute(future, query);
336+ return future;
337+ }
338+}
modified driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java +1 −1
@@ -240,7 +240,7 @@
240240 * Returns a snapshot of the scores (latency averages) maintained by this
241241 * policy.
242242 *
243- * @return a new (immutable) {@link Snaphot} object containing the current
243+ * @return a new (immutable) {@link Snapshot} object containing the current
244244 * latency scores maintained by this policy.
245245 */
246246 public Snapshot getScoresSnapshot() {