Elffuss BraidHub

kikocis/java-driver public

Merge pull request #501 from datastax/java846

JAVA-846: Provide custom codecs library as an extra module
Changeseta8c38a6edadba4110ef98bcc7b45a0c852a1b382cf1a841262246cfd0856c204
AuthorAlexandre Dutra <adutra@users.noreply.github.com> · 2015-11-17 15:22 +01:00
CommitterAlexandre Dutra <adutra@users.noreply.github.com> · 2015-11-17 15:22 +01:00
Parents7aa30ea93ee9, 5390190f3856

Browse the files at this changeset

113 files changed

modified README.md +11 −0
@@ -90,6 +90,17 @@
9090 </dependency>
9191 ```
9292
93+The 'extras' module is also published as a separate artifact:
94+
95+```xml
96+<dependency>
97+ <groupId>com.datastax.cassandra</groupId>
98+ <artifactId>cassandra-driver-extras</artifactId>
99+ <version>3.0.0-alpha4</version>
100+</dependency>
101+```
102+
103+
93104 We also provide a [shaded JAR](features/shaded_jar/)
94105 to avoid the explicit dependency to Netty.
95106
modified changelog/README.md +6 −0
@@ -14,6 +14,12 @@
1414 - [improvement] JAVA-948: Don't limit cipher suites by default.
1515 - [improvement] JAVA-917: Document SSL configuration.
1616 - [improvement] JAVA-936: Adapt schema metadata parsing logic to new storage format of CQL types in C* 3.0.
17+- [new feature] JAVA-846: Provide custom codecs library as an extra module.
18+- [new feature] JAVA-742: Codec Support for JSON.
19+- [new feature] JAVA-606: Codec support for Java 8.
20+- [new feature] JAVA-565: Codec support for Java arrays.
21+- [new feature] JAVA-605: Codec support for Java enums.
22+- [bug] JAVA-884: Fix UDT mapper to process fields in the correct order.
1723
1824 Merged from 2.1 branch:
1925
modified driver-core/pom.xml +1 −23
@@ -121,21 +121,7 @@
121121 <dependency>
122122 <groupId>org.apache.commons</groupId>
123123 <artifactId>commons-exec</artifactId>
124- <version>1.3</version>
125- <scope>test</scope>
126- </dependency>
127-
128- <dependency>
129- <groupId>com.fasterxml.jackson.core</groupId>
130- <artifactId>jackson-databind</artifactId>
131- <version>2.5.3</version>
132- <scope>test</scope>
133- </dependency>
134-
135- <dependency>
136- <groupId>joda-time</groupId>
137- <artifactId>joda-time</artifactId>
138- <version>2.8.1</version>
124+ <version>${commons-exec.version}</version>
139125 <scope>test</scope>
140126 </dependency>
141127
@@ -157,14 +143,6 @@
157143 </resource>
158144 </resources>
159145 <plugins>
160- <plugin>
161- <artifactId>maven-compiler-plugin</artifactId>
162- <configuration>
163- <compilerArgument>-Xlint:all</compilerArgument>
164- <showWarnings>true</showWarnings>
165- <showDeprecation>true</showDeprecation>
166- </configuration>
167- </plugin>
168146 <plugin>
169147 <groupId>org.apache.maven.plugins</groupId>
170148 <artifactId>maven-jar-plugin</artifactId>
modified driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java +9 −9
@@ -24,9 +24,9 @@
2424 import com.google.common.base.Objects;
2525 import com.google.common.reflect.TypeToken;
2626
27-import static com.datastax.driver.core.CodecUtils.listOf;
28-import static com.datastax.driver.core.CodecUtils.mapOf;
29-import static com.datastax.driver.core.CodecUtils.setOf;
27+import static com.datastax.driver.core.TypeTokens.listOf;
28+import static com.datastax.driver.core.TypeTokens.mapOf;
29+import static com.datastax.driver.core.TypeTokens.setOf;
3030
3131 abstract class AbstractAddressableByIndexData<T extends SettableByIndexData<T>> extends AbstractGettableByIndexData implements SettableByIndexData<T> {
3232
@@ -170,12 +170,12 @@
170170
171171 @Override
172172 public <E> T setList(int i, List<E> v, Class<E> elementsClass) {
173- return setValue(i, codecFor(i, listOf(elementsClass)).serialize(v, protocolVersion));
173+ return setValue(i, codecFor(i, TypeTokens.listOf(elementsClass)).serialize(v, protocolVersion));
174174 }
175175
176176 @Override
177177 public <E> T setList(int i, List<E> v, TypeToken<E> elementsType) {
178- return setValue(i, codecFor(i, listOf(elementsType)).serialize(v, protocolVersion));
178+ return setValue(i, codecFor(i, TypeTokens.listOf(elementsType)).serialize(v, protocolVersion));
179179 }
180180
181181 @SuppressWarnings("unchecked")
@@ -185,12 +185,12 @@
185185
186186 @Override
187187 public <K, V> T setMap(int i, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass) {
188- return setValue(i, codecFor(i, mapOf(keysClass, valuesClass)).serialize(v, protocolVersion));
188+ return setValue(i, codecFor(i, TypeTokens.mapOf(keysClass, valuesClass)).serialize(v, protocolVersion));
189189 }
190190
191191 @Override
192192 public <K, V> T setMap(int i, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType) {
193- return setValue(i, codecFor(i, mapOf(keysType, valuesType)).serialize(v, protocolVersion));
193+ return setValue(i, codecFor(i, TypeTokens.mapOf(keysType, valuesType)).serialize(v, protocolVersion));
194194 }
195195
196196 @SuppressWarnings("unchecked")
@@ -200,12 +200,12 @@
200200
201201 @Override
202202 public <E> T setSet(int i, Set<E> v, Class<E> elementsClass) {
203- return setValue(i, codecFor(i, setOf(elementsClass)).serialize(v, protocolVersion));
203+ return setValue(i, codecFor(i, TypeTokens.setOf(elementsClass)).serialize(v, protocolVersion));
204204 }
205205
206206 @Override
207207 public <E> T setSet(int i, Set<E> v, TypeToken<E> elementsType) {
208- return setValue(i, codecFor(i, setOf(elementsType)).serialize(v, protocolVersion));
208+ return setValue(i, codecFor(i, TypeTokens.setOf(elementsType)).serialize(v, protocolVersion));
209209 }
210210
211211 public T setUDTValue(int i, UDTValue v) {
modified driver-core/src/main/java/com/datastax/driver/core/AbstractData.java +9 −9
@@ -24,9 +24,9 @@
2424 import com.google.common.base.Objects;
2525 import com.google.common.reflect.TypeToken;
2626
27-import static com.datastax.driver.core.CodecUtils.listOf;
28-import static com.datastax.driver.core.CodecUtils.mapOf;
29-import static com.datastax.driver.core.CodecUtils.setOf;
27+import static com.datastax.driver.core.TypeTokens.listOf;
28+import static com.datastax.driver.core.TypeTokens.mapOf;
29+import static com.datastax.driver.core.TypeTokens.setOf;
3030
3131 // We don't want to expose this one: it's less useful externally and it's a bit ugly to expose anyway (but it's convenient).
3232 abstract class AbstractData<T extends SettableData<T>> extends AbstractGettableData implements SettableData<T> {
@@ -364,12 +364,12 @@
364364
365365 @Override
366366 public <E> T setList(int i, List<E> v, Class<E> elementsClass) {
367- return setValue(i, codecFor(i, listOf(elementsClass)).serialize(v, protocolVersion));
367+ return setValue(i, codecFor(i, TypeTokens.listOf(elementsClass)).serialize(v, protocolVersion));
368368 }
369369
370370 @Override
371371 public <E> T setList(int i, List<E> v, TypeToken<E> elementsType) {
372- return setValue(i, codecFor(i, listOf(elementsType)).serialize(v, protocolVersion));
372+ return setValue(i, codecFor(i, TypeTokens.listOf(elementsType)).serialize(v, protocolVersion));
373373 }
374374
375375 @Override
@@ -404,12 +404,12 @@
404404
405405 @Override
406406 public <K, V> T setMap(int i, Map<K, V> v, Class<K> keysClass, Class<V> valuesClass) {
407- return setValue(i, codecFor(i, mapOf(keysClass, valuesClass)).serialize(v, protocolVersion));
407+ return setValue(i, codecFor(i, TypeTokens.mapOf(keysClass, valuesClass)).serialize(v, protocolVersion));
408408 }
409409
410410 @Override
411411 public <K, V> T setMap(int i, Map<K, V> v, TypeToken<K> keysType, TypeToken<V> valuesType) {
412- return setValue(i, codecFor(i, mapOf(keysType, valuesType)).serialize(v, protocolVersion));
412+ return setValue(i, codecFor(i, TypeTokens.mapOf(keysType, valuesType)).serialize(v, protocolVersion));
413413 }
414414
415415 @Override
@@ -444,12 +444,12 @@
444444
445445 @Override
446446 public <E> T setSet(int i, Set<E> v, Class<E> elementsClass) {
447- return setValue(i, codecFor(i, setOf(elementsClass)).serialize(v, protocolVersion));
447+ return setValue(i, codecFor(i, TypeTokens.setOf(elementsClass)).serialize(v, protocolVersion));
448448 }
449449
450450 @Override
451451 public <E> T setSet(int i, Set<E> v, TypeToken<E> elementsType) {
452- return setValue(i, codecFor(i, setOf(elementsType)).serialize(v, protocolVersion));
452+ return setValue(i, codecFor(i, TypeTokens.setOf(elementsType)).serialize(v, protocolVersion));
453453 }
454454
455455 @Override
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +6 −6
@@ -25,9 +25,9 @@
2525
2626 import com.datastax.driver.core.exceptions.InvalidTypeException;
2727
28-import static com.datastax.driver.core.CodecUtils.listOf;
29-import static com.datastax.driver.core.CodecUtils.mapOf;
30-import static com.datastax.driver.core.CodecUtils.setOf;
28+import static com.datastax.driver.core.TypeTokens.listOf;
29+import static com.datastax.driver.core.TypeTokens.mapOf;
30+import static com.datastax.driver.core.TypeTokens.setOf;
3131
3232 abstract class AbstractGettableByIndexData implements GettableByIndexData {
3333
@@ -302,7 +302,7 @@
302302 @SuppressWarnings("unchecked")
303303 public <T> List<T> getList(int i, TypeToken<T> elementsType) {
304304 ByteBuffer value = getValue(i);
305- TypeToken<List<T>> javaType = listOf(elementsType);
305+ TypeToken<List<T>> javaType = TypeTokens.listOf(elementsType);
306306 return codecFor(i, javaType).deserialize(value, protocolVersion);
307307 }
308308
@@ -322,7 +322,7 @@
322322 @SuppressWarnings("unchecked")
323323 public <T> Set<T> getSet(int i, TypeToken<T> elementsType) {
324324 ByteBuffer value = getValue(i);
325- TypeToken<Set<T>> javaType = setOf(elementsType);
325+ TypeToken<Set<T>> javaType = TypeTokens.setOf(elementsType);
326326 return codecFor(i, javaType).deserialize(value, protocolVersion);
327327 }
328328
@@ -342,7 +342,7 @@
342342 @SuppressWarnings("unchecked")
343343 public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) {
344344 ByteBuffer value = getValue(i);
345- TypeToken<Map<K, V>> javaType = mapOf(keysType, valuesType);
345+ TypeToken<Map<K, V>> javaType = TypeTokens.mapOf(keysType, valuesType);
346346 return codecFor(i, javaType).deserialize(value, protocolVersion);
347347 }
348348
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +1 −1
@@ -242,7 +242,7 @@
242242 return null;
243243 components[i] = value;
244244 }
245- return CodecUtils.compose(components);
245+ return SimpleStatement.compose(components);
246246 }
247247 }
248248 return null;
modified driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java +119 −189
@@ -26,155 +26,15 @@
2626 import com.datastax.driver.core.exceptions.InvalidTypeException;
2727
2828 /**
29- * A set of utility methods to deal with type conversion,
30- * serialization, and to create {@link TypeToken} instances.
31- * <p>
32- * This class is public because it is accessed from {@link com.datastax.driver.core.querybuilder.BuiltStatement}
33- * but its use by client code is not supported.
29+ * A set of utility methods to deal with type conversion and serialization.
3430 */
3531 public final class CodecUtils {
3632
37- private CodecUtils(){}
38-
39- public static <T> TypeToken<List<T>> listOf(Class<T> eltType) {
40- return new TypeToken<List<T>>(){}.where(new TypeParameter<T>(){}, eltType);
41- }
42-
43- public static <T> TypeToken<List<T>> listOf(TypeToken<T> eltType) {
44- return new TypeToken<List<T>>(){}.where(new TypeParameter<T>(){}, eltType);
45- }
46-
47- public static <T> TypeToken<Set<T>> setOf(Class<T> eltType) {
48- return new TypeToken<Set<T>>(){}.where(new TypeParameter<T>(){}, eltType);
49- }
50-
51- public static <T> TypeToken<Set<T>> setOf(TypeToken<T> eltType) {
52- return new TypeToken<Set<T>>(){}.where(new TypeParameter<T>(){}, eltType);
53- }
54-
55- public static <K, V> TypeToken<Map<K, V>> mapOf(Class<K> keyType, Class<V> valueType) {
56- return new TypeToken<Map<K, V>>(){}
57- .where(new TypeParameter<K>(){}, keyType)
58- .where(new TypeParameter<V>(){}, valueType);
59- }
60-
61- public static <K, V> TypeToken<Map<K, V>> mapOf(TypeToken<K> keyType, TypeToken<V> valueType) {
62- return new TypeToken<Map<K, V>>(){}
63- .where(new TypeParameter<K>(){}, keyType)
64- .where(new TypeParameter<V>(){}, valueType);
65- }
66-
67- /**
68- * Propagate a CodecRegistry instance to a given type and its child types, if any.
69- * <p>
70- * By the time CQL types are decoded from response messages, the codec registry is not available;
71- * This method manually sets a CodecRegistry on all CQL types that require it,
72- * and thus should be called immediately after a response is decoded
73- * into either a prepared statement or a result set.
74- *
75- * @param cqlType The decodec {@link DataType cqlType}.
76- * @param codecRegistry The {@link CodecRegistry} instance to use.
77- */
78- static void setCodecRegistry(DataType cqlType, CodecRegistry codecRegistry) {
79- // user types
80- if(cqlType instanceof UserType) {
81- UserType userType = (UserType)cqlType;
82- userType.setCodecRegistry(codecRegistry);
83- for (UserType.Field field : userType.getFields()) {
84- setCodecRegistry(field.getType(), codecRegistry);
85- }
86- }
87- // tuples
88- else if(cqlType instanceof TupleType) {
89- TupleType tupleType = (TupleType)cqlType;
90- tupleType.setCodecRegistry(codecRegistry);
91- for (DataType componentType : tupleType.getComponentTypes()) {
92- setCodecRegistry(componentType, codecRegistry);
93- }
94- }
95- // collections
96- else if(cqlType.isCollection()) {
97- for (DataType inner : cqlType.getTypeArguments()) {
98- setCodecRegistry(inner, codecRegistry);
99- }
100- }
101- }
102-
103- /**
104- * Utility method to serialize user-provided values.
105- * <p>
106- * This method is useful in situations where there is no metadata available and the underlying CQL
107- * type for the values is not known.
108- * <p>
109- * This situation happens when a {@link SimpleStatement}
110- * or a {@link com.datastax.driver.core.querybuilder.BuiltStatement} (Query Builder) contain values;
111- * in these places, the driver has no way to determine the right CQL type to use.
112- * <p>
113- * This method performs a best-effort heuristic to guess which codec to use.
114- * Note that this is not particularly efficient as the codec registry needs to iterate over
115- * the registered codecs until it finds a suitable one.
116- *
117- * @param values The values to convert.
118- * @param protocolVersion The protocol version to use.
119- * @param codecRegistry The {@link CodecRegistry} to use.
120- * @return The converted values.
121- */
122- public static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
123- ByteBuffer[] serializedValues = new ByteBuffer[values.length];
124- for (int i = 0; i < values.length; i++) {
125- Object value = values[i];
126- if (value == null) {
127- // impossible to locate the right codec when object is null,
128- // so forcing the result to null
129- serializedValues[i] = null;
130- } else {
131- if (value instanceof Token) {
132- // bypass CodecRegistry for Token instances
133- serializedValues[i] = ((Token)value).serialize(protocolVersion);
134- } else {
135- try {
136- TypeCodec<Object> codec = codecRegistry.codecFor(value);
137- serializedValues[i] = codec.serialize(value, protocolVersion);
138- } catch (Exception e) {
139- // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
140- throw new InvalidTypeException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, value.getClass()), e);
141- }
142- }
143- }
144- }
145- return serializedValues;
146- }
147-
148- /**
149- * Utility method to assemble different routing key components into a single {@link ByteBuffer}.
150- * Mainly intended for statements that need to generate a routing key out of their current values.
151- *
152- * @param buffers the components of the routing key.
153- * @return A ByteBuffer containing the serialized routing key
154- */
155- public static ByteBuffer compose(ByteBuffer... buffers) {
156- if (buffers.length == 1)
157- return buffers[0];
158-
159- int totalLength = 0;
160- for (ByteBuffer bb : buffers)
161- totalLength += 2 + bb.remaining() + 1;
33+ private static final long MAX_CQL_LONG_VALUE = ((1L << 32) - 1);
16234
163- ByteBuffer out = ByteBuffer.allocate(totalLength);
164- for (ByteBuffer buffer : buffers) {
165- ByteBuffer bb = buffer.duplicate();
166- putShortLength(out, bb.remaining());
167- out.put(bb);
168- out.put((byte)0);
169- }
170- out.flip();
171- return out;
172- }
35+ private static final long EPOCH_AS_CQL_LONG = (1L << 31);
17336
174- private static void putShortLength(ByteBuffer bb, int length) {
175- bb.put((byte)((length >> 8) & 0xFF));
176- bb.put((byte)(length & 0xFF));
177- }
37+ private CodecUtils(){}
17838
17939 /**
18040 * Utility method that "packs" together a list of {@link ByteBuffer}s containing
@@ -186,27 +46,27 @@
18646 * @param version the protocol version to use
18747 * @return The serialized collection
18848 */
189- public static ByteBuffer pack(List<ByteBuffer> buffers, int elements, ProtocolVersion version) {
49+ public static ByteBuffer pack(ByteBuffer[] buffers, int elements, ProtocolVersion version) {
19050 int size = 0;
19151 for (ByteBuffer bb : buffers) {
19252 int elemSize = sizeOfValue(bb, version);
19353 size += elemSize;
19454 }
19555 ByteBuffer result = ByteBuffer.allocate(sizeOfCollectionSize(version) + size);
196- writeCollectionSize(result, elements, version);
56+ writeSize(result, elements, version);
19757 for (ByteBuffer bb : buffers)
198- writeCollectionValue(result, bb, version);
58+ writeValue(result, bb, version);
19959 return (ByteBuffer)result.flip();
20060 }
20161
20262 /**
203- * Utility method that reads the collection size.
63+ * Utility method that reads a size value.
20464 * Mainly intended for collection codecs when deserializing CQL collections.
205- * @param input A ByteBuffer containing a serialized CQL collection
65+ * @param input The ByteBuffer to read from.
20666 * @param version The protocol version to use.
207- * @return The collection size
67+ * @return The size value.
20868 */
209- public static int readCollectionSize(ByteBuffer input, ProtocolVersion version) {
69+ public static int readSize(ByteBuffer input, ProtocolVersion version) {
21070 switch (version) {
21171 case V1:
21272 case V2:
@@ -219,48 +79,140 @@
21979 }
22080 }
22181
222- public static ByteBuffer readBytes(ByteBuffer bb, int length) {
223- ByteBuffer copy = bb.duplicate();
224- copy.limit(copy.position() + length);
225- bb.position(bb.position() + length);
226- return copy;
227- }
228-
229- public static ByteBuffer readCollectionValue(ByteBuffer input, ProtocolVersion version) {
230- int size;
82+ /**
83+ * Utility method that writes a size value.
84+ * Mainly intended for collection codecs when serializing CQL collections.
85+ *
86+ * @param output The ByteBuffer to write to.
87+ * @param size The collection size.
88+ * @param version The protocol version to use.
89+ */
90+ public static void writeSize(ByteBuffer output, int size, ProtocolVersion version) {
23191 switch (version) {
23292 case V1:
23393 case V2:
234- size = getUnsignedShort(input);
94+ if (size > 65535)
95+ throw new IllegalArgumentException(String.format("Native protocol version %d supports up to 65535 elements in any collection - but collection contains %d elements", version.toInt(), size));
96+ output.putShort((short)size);
23597 break;
23698 case V3:
23799 case V4:
238- size = input.getInt();
100+ output.putInt(size);
239101 break;
240102 default:
241103 throw version.unsupported();
242104 }
105+ }
106+
107+ /**
108+ * Utility method that reads a value.
109+ * Mainly intended for collection codecs when deserializing CQL collections.
110+ *
111+ * @param input The ByteBuffer to read from.
112+ * @param version The protocol version to use.
113+ * @return The collection element.
114+ */
115+ public static ByteBuffer readValue(ByteBuffer input, ProtocolVersion version) {
116+ int size = readSize(input, version);
243117 return size < 0 ? null : readBytes(input, size);
244118 }
245119
120+ /**
121+ * Utility method that writes a value.
122+ * Mainly intended for collection codecs when deserializing CQL collections.
246123
247- private static void writeCollectionSize(ByteBuffer output, int elements, ProtocolVersion version) {
124+ * @param output The ByteBuffer to write to.
125+ * @param value The value to write.
126+ * @param version The protocol version to use.
127+ */
128+ public static void writeValue(ByteBuffer output, ByteBuffer value, ProtocolVersion version) {
248129 switch (version) {
249130 case V1:
250131 case V2:
251- if (elements > 65535)
252- throw new IllegalArgumentException(String.format("Native protocol version %d supports up to 65535 elements in any collection - but collection contains %d elements", version.toInt(), elements));
253- output.putShort((short)elements);
132+ assert value != null;
133+ output.putShort((short)value.remaining());
134+ output.put(value.duplicate());
254135 break;
255136 case V3:
256137 case V4:
257- output.putInt(elements);
138+ if (value == null) {
139+ output.putInt(-1);
140+ } else {
141+ output.putInt(value.remaining());
142+ output.put(value.duplicate());
143+ }
258144 break;
259145 default:
260146 throw version.unsupported();
261147 }
262148 }
263149
150+ /**
151+ * Read {@code length} bytes from {@code bb} into a new ByteBuffer.
152+ *
153+ * @param bb The ByteBuffer to read.
154+ * @param length The number of bytes to read.
155+ * @return The read bytes.
156+ */
157+ public static ByteBuffer readBytes(ByteBuffer bb, int length) {
158+ ByteBuffer copy = bb.duplicate();
159+ copy.limit(copy.position() + length);
160+ bb.position(bb.position() + length);
161+ return copy;
162+ }
163+
164+ /**
165+ * Converts an "unsigned" int read from a DATE value into a signed int.
166+ * <p>
167+ * The protocol encodes DATE values as <em>unsigned</em> ints with the Epoch in the middle of the range (2^31).
168+ * This method handles the conversion from an "unsigned" to a signed int.
169+ */
170+ public static int fromUnsignedToSignedInt(int unsigned) {
171+ return unsigned + Integer.MIN_VALUE; // this relies on overflow for "negative" values
172+ }
173+
174+ /**
175+ * Converts an int into an "unsigned" int suitable to be written as a DATE value.
176+ * <p>
177+ * The protocol encodes DATE values as <em>unsigned</em> ints with the Epoch in the middle of the range (2^31).
178+ * This method handles the conversion from a signed to an "unsigned" int.
179+ */
180+ public static int fromSignedToUnsignedInt(int signed) {
181+ return signed - Integer.MIN_VALUE;
182+ }
183+
184+ /**
185+ * Convert from a raw CQL long representing a numeric DATE literal
186+ * to the number of days since the Epoch.
187+ * In CQL, numeric DATE literals are longs (unsigned integers actually)
188+ * between 0 and 2^32 - 1, with the epoch in the middle;
189+ * this method re-centers the epoch at 0.
190+ *
191+ * @param raw The CQL date value to convert.
192+ * @return The number of days since the Epoch corresponding to the given raw value.
193+ * @throws IllegalArgumentException if the value is out of range.
194+ */
195+ public static int fromCqlDateToDaysSinceEpoch(long raw) {
196+ if (raw < 0 || raw > MAX_CQL_LONG_VALUE)
197+ throw new IllegalArgumentException(String.format("Numeric literals for DATE must be between 0 and %d (got %d)", MAX_CQL_LONG_VALUE, raw));
198+ return (int)(raw - EPOCH_AS_CQL_LONG);
199+ }
200+
201+ /**
202+ * Convert the number of days since the Epoch into
203+ * a raw CQL long representing a numeric DATE literal.
204+ *
205+ * In CQL, numeric DATE literals are longs (unsigned integers actually)
206+ * between 0 and 2^32 - 1, with the epoch in the middle;
207+ * this method re-centers the epoch at 2^31.
208+ *
209+ * @param days The number of days since the Epoch convert.
210+ * @return The CQL date value corresponding to the given value.
211+ */
212+ public static long fromDaysSinceEpochToCqlDate(int days) {
213+ return ((long)days + EPOCH_AS_CQL_LONG);
214+ }
215+
264216 private static int sizeOfCollectionSize(ProtocolVersion version) {
265217 switch (version) {
266218 case V1:
@@ -274,28 +226,6 @@
274226 }
275227 }
276228
277- private static void writeCollectionValue(ByteBuffer output, ByteBuffer value, ProtocolVersion version) {
278- switch (version) {
279- case V1:
280- case V2:
281- assert value != null;
282- output.putShort((short)value.remaining());
283- output.put(value.duplicate());
284- break;
285- case V3:
286- case V4:
287- if (value == null) {
288- output.putInt(-1);
289- } else {
290- output.putInt(value.remaining());
291- output.put(value.duplicate());
292- }
293- break;
294- default:
295- throw version.unsupported();
296- }
297- }
298-
299229 private static int sizeOfValue(ByteBuffer value, ProtocolVersion version) {
300230 switch (version) {
301231 case V1:
modified driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java +37 −1
@@ -286,11 +286,47 @@
286286
287287 void setCodecRegistry(CodecRegistry codecRegistry) {
288288 for (Definition definition : byIdx) {
289- CodecUtils.setCodecRegistry(definition.type, codecRegistry);
289+ propagateCodecRegistry(definition.type, codecRegistry);
290290 }
291291 this.codecRegistry = codecRegistry;
292292 }
293293
294+ /**
295+ * Propagate a CodecRegistry instance to a given type and its child types, if any.
296+ * <p>
297+ * By the time CQL types are decoded from response messages, the codec registry is not available;
298+ * This method manually sets a CodecRegistry on all CQL types that require it,
299+ * and thus should be called immediately after a response is decoded
300+ * into either a prepared statement or a result set.
301+ *
302+ * @param cqlType The decodec {@link DataType cqlType}.
303+ * @param codecRegistry The {@link CodecRegistry} instance to use.
304+ */
305+ static void propagateCodecRegistry(DataType cqlType, CodecRegistry codecRegistry) {
306+ // user types
307+ if(cqlType instanceof UserType) {
308+ UserType userType = (UserType)cqlType;
309+ userType.setCodecRegistry(codecRegistry);
310+ for (UserType.Field field : userType.byIdx) {
311+ propagateCodecRegistry(field.getType(), codecRegistry);
312+ }
313+ }
314+ // tuples
315+ else if(cqlType instanceof TupleType) {
316+ TupleType tupleType = (TupleType)cqlType;
317+ tupleType.setCodecRegistry(codecRegistry);
318+ for (DataType componentType : tupleType.getComponentTypes()) {
319+ propagateCodecRegistry(componentType, codecRegistry);
320+ }
321+ }
322+ // collections
323+ else if(cqlType.isCollection()) {
324+ for (DataType inner : cqlType.getTypeArguments()) {
325+ propagateCodecRegistry(inner, codecRegistry);
326+ }
327+ }
328+ }
329+
294330 /**
295331 * A column definition.
296332 */
modified driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +1 −1
@@ -136,7 +136,7 @@
136136 }
137137
138138 public PreparedStatement setRoutingKey(ByteBuffer... routingKeyComponents) {
139- this.routingKey = CodecUtils.compose(routingKeyComponents);
139+ this.routingKey = SimpleStatement.compose(routingKeyComponents);
140140 return this;
141141 }
142142
modified driver-core/src/main/java/com/datastax/driver/core/ParseUtils.java +326 −5
@@ -15,12 +15,37 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.text.ParseException;
19+import java.text.ParsePosition;
20+import java.text.SimpleDateFormat;
21+import java.util.Date;
22+import java.util.TimeZone;
23+import java.util.concurrent.TimeUnit;
24+
1825 /**
19- * Simple utility method used to help parsing CQL values (mainly UDT and collection ones).
26+ * Simple utility class used to help parsing CQL values (mainly UDT and collection ones).
2027 */
21-abstract class ParseUtils {
28+public abstract class ParseUtils {
2229
23- private ParseUtils() {}
30+ /**
31+ * Valid ISO-8601 patterns for CQL timestamp literals.
32+ */
33+ private static final String[] iso8601Patterns = new String[]{
34+ "yyyy-MM-dd HH:mm",
35+ "yyyy-MM-dd HH:mm:ss",
36+ "yyyy-MM-dd HH:mmZ",
37+ "yyyy-MM-dd HH:mm:ssZ",
38+ "yyyy-MM-dd HH:mm:ss.SSS",
39+ "yyyy-MM-dd HH:mm:ss.SSSZ",
40+ "yyyy-MM-dd'T'HH:mm",
41+ "yyyy-MM-dd'T'HH:mmZ",
42+ "yyyy-MM-dd'T'HH:mm:ss",
43+ "yyyy-MM-dd'T'HH:mm:ssZ",
44+ "yyyy-MM-dd'T'HH:mm:ss.SSS",
45+ "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
46+ "yyyy-MM-dd",
47+ "yyyy-MM-ddZ"
48+ };
2449
2550 /**
2651 * Returns the index of the first character in toParse from idx that is not a "space".
@@ -149,15 +174,311 @@
149174 throw new IllegalArgumentException();
150175 }
151176
152- // [0..9a..zA..Z-+._&]
177+ /**
178+ * Return {@code true} if the given character
179+ * is allowed in a CQL identifier, that is,
180+ * if it is in the range: {@code [0..9a..zA..Z-+._&]}.
181+ *
182+ * @param c The character to inspect.
183+ * @return {@code true} if the given character
184+ * is allowed in a CQL identifier, {@code false} otherwise.
185+ */
153186 public static boolean isIdentifierChar(int c) {
154187 return (c >= '0' && c <= '9')
155188 || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
156189 || c == '-' || c == '+' || c == '.' || c == '_' || c == '&';
157190 }
158191
159- // [ \t\n]
192+ /**
193+ * Return {@code true} if the given character
194+ * is a valid whitespace character in CQL, that is,
195+ * if it is a regular space, a tabulation sign,
196+ * or a new line sign.
197+ *
198+ * @param c The character to inspect.
199+ * @return {@code true} if the given character
200+ * is a valid whitespace character, {@code false} otherwise.
201+ */
160202 public static boolean isBlank(int c) {
161203 return c == ' ' || c == '\t' || c == '\n';
162204 }
205+
206+ /**
207+ * Check whether the given string corresponds
208+ * to a valid CQL long literal.
209+ * Long literals are composed solely by digits,
210+ * but can have an optional leading minus sign.
211+ *
212+ * @param str The string to inspect.
213+ * @return {@code true} if the given string corresponds
214+ * to a valid CQL integer literal, {@code false} otherwise.
215+ */
216+ public static boolean isLongLiteral(String str) {
217+ if (str == null || str.isEmpty())
218+ return false;
219+ char[] chars = str.toCharArray();
220+ for (int i = 0; i < chars.length; i++) {
221+ char c = chars[i];
222+ if ((c < '0' && (i != 0 || c != '-')) || c > '9')
223+ return false;
224+ }
225+ return true;
226+ }
227+
228+ /**
229+ * Return {@code true} if the given string is surrounded
230+ * by single quotes, and {@code false} otherwise.
231+ *
232+ * @param value The string to inspect.
233+ * @return {@code true} if the given string is surrounded
234+ * by single quotes, and {@code false} otherwise.
235+ */
236+ public static boolean isQuoted(String value) {
237+ return value.charAt(0) == '\'' && value.charAt(value.length() - 1) == '\'';
238+ }
239+
240+
241+ /**
242+ * Quote the given string; single quotes are escaped.
243+ *
244+ * @param value The value to quote.
245+ * @return The quoted string.
246+ */
247+ public static String quote(String value) {
248+ return '\'' + replaceChar(value, '\'', "''") + '\'';
249+ }
250+
251+ /**
252+ * Unquote the given string; single quotes are unescaped.
253+ *
254+ * @param value The string to unquote.
255+ * @return The unquoted string.
256+ */
257+ public static String unquote(String value) {
258+ return value.substring(1, value.length() - 1).replace("''", "'");
259+ }
260+
261+ /**
262+ * Parse the given string as a date, using one of the accepted ISO-8601 date patterns.
263+ * <p>
264+ * This method is adapted from Apache Commons {@code DateUtils.parseStrictly()} method (that is used Cassandra side
265+ * to parse date strings)..
266+ *
267+ * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps">Working with timestamps</a>
268+ * section of CQL specification.
269+ * @throws ParseException If the given string is not a valid ISO-8601 date.
270+ */
271+ public static Date parseDate(String str) throws ParseException {
272+ SimpleDateFormat parser = new SimpleDateFormat();
273+ parser.setLenient(false);
274+ // set a default timezone for patterns that do not provide one
275+ parser.setTimeZone(TimeZone.getTimeZone("UTC"));
276+ // Java 6 has very limited support for ISO-8601 time zone formats,
277+ // so we need to transform the string first
278+ // so that accepted patterns are correctly handled,
279+ // such as Z for UTC, or "+00:00" instead of "+0000".
280+ // Note: we cannot use the X letter in the pattern
281+ // because it has been introduced in Java 7.
282+ str = str.replaceAll("(\\+|\\-)(\\d\\d):(\\d\\d)$", "$1$2$3");
283+ str = str.replaceAll("Z$", "+0000");
284+ ParsePosition pos = new ParsePosition(0);
285+ for (String parsePattern : iso8601Patterns) {
286+ parser.applyPattern(parsePattern);
287+ pos.setIndex(0);
288+ Date date = parser.parse(str, pos);
289+ if (date != null && pos.getIndex() == str.length()) {
290+ return date;
291+ }
292+ }
293+ throw new ParseException("Unable to parse the date: " + str, -1);
294+ }
295+
296+ /**
297+ * Parse the given string as a date, using the supplied date pattern.
298+ * <p>
299+ * This method is adapted from Apache Commons {@code DateUtils.parseStrictly()} method (that is used Cassandra side
300+ * to parse date strings)..
301+ *
302+ * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps">Working with timestamps</a>
303+ * section of CQL specification.
304+ * @throws ParseException If the given string cannot be parsed with the given pattern.
305+ */
306+ public static Date parseDate(String str, String pattern) throws ParseException {
307+ SimpleDateFormat parser = new SimpleDateFormat();
308+ parser.setLenient(false);
309+ // set a default timezone for patterns that do not provide one
310+ parser.setTimeZone(TimeZone.getTimeZone("UTC"));
311+ // Java 6 has very limited support for ISO-8601 time zone formats,
312+ // so we need to transform the string first
313+ // so that accepted patterns are correctly handled,
314+ // such as Z for UTC, or "+00:00" instead of "+0000".
315+ // Note: we cannot use the X letter in the pattern
316+ // because it has been introduced in Java 7.
317+ str = str.replaceAll("(\\+|\\-)(\\d\\d):(\\d\\d)$", "$1$2$3");
318+ str = str.replaceAll("Z$", "+0000");
319+ ParsePosition pos = new ParsePosition(0);
320+ parser.applyPattern(pattern);
321+ pos.setIndex(0);
322+ Date date = parser.parse(str, pos);
323+ if (date != null && pos.getIndex() == str.length()) {
324+ return date;
325+ }
326+ throw new ParseException("Unable to parse the date: " + str, -1);
327+ }
328+
329+ /**
330+ * Parse the given string as a time, using the following time pattern: {@code hh:mm:ss[.fffffffff]}.
331+ * <p>
332+ * This method is loosely based on {@code java.sql.Timestamp}.
333+ *
334+ * @param str The string to parse.
335+ * @return A long value representing the number of nanoseconds since midnight.
336+ * @throws ParseException if the string cannot be parsed.
337+ * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtime">Working with time</a>
338+ * section of CQL specification.
339+ */
340+ public static long parseTime(String str) throws ParseException {
341+ String nanos_s;
342+
343+ long hour;
344+ long minute;
345+ long second;
346+ long a_nanos = 0;
347+
348+ String formatError = "Timestamp format must be hh:mm:ss[.fffffffff]";
349+ String zeros = "000000000";
350+
351+ if (str == null)
352+ throw new IllegalArgumentException(formatError);
353+ str = str.trim();
354+
355+ // Parse the time
356+ int firstColon = str.indexOf(':');
357+ int secondColon = str.indexOf(':', firstColon + 1);
358+
359+ // Convert the time; default missing nanos
360+ if (firstColon > 0 && secondColon > 0 && secondColon < str.length() - 1) {
361+ int period = str.indexOf('.', secondColon + 1);
362+ hour = Integer.parseInt(str.substring(0, firstColon));
363+ if (hour < 0 || hour >= 24)
364+ throw new IllegalArgumentException("Hour out of bounds.");
365+
366+ minute = Integer.parseInt(str.substring(firstColon + 1, secondColon));
367+ if (minute < 0 || minute >= 60)
368+ throw new IllegalArgumentException("Minute out of bounds.");
369+
370+ if (period > 0 && period < str.length() - 1) {
371+ second = Integer.parseInt(str.substring(secondColon + 1, period));
372+ if (second < 0 || second >= 60)
373+ throw new IllegalArgumentException("Second out of bounds.");
374+
375+ nanos_s = str.substring(period + 1);
376+ if (nanos_s.length() > 9)
377+ throw new IllegalArgumentException(formatError);
378+ if (!Character.isDigit(nanos_s.charAt(0)))
379+ throw new IllegalArgumentException(formatError);
380+ nanos_s = nanos_s + zeros.substring(0, 9 - nanos_s.length());
381+ a_nanos = Integer.parseInt(nanos_s);
382+ } else if (period > 0)
383+ throw new ParseException(formatError, -1);
384+ else {
385+ second = Integer.parseInt(str.substring(secondColon + 1));
386+ if (second < 0 || second >= 60)
387+ throw new ParseException("Second out of bounds.", -1);
388+ }
389+ } else
390+ throw new ParseException(formatError, -1);
391+
392+ long rawTime = 0;
393+ rawTime += TimeUnit.HOURS.toNanos(hour);
394+ rawTime += TimeUnit.MINUTES.toNanos(minute);
395+ rawTime += TimeUnit.SECONDS.toNanos(second);
396+ rawTime += a_nanos;
397+ return rawTime;
398+ }
399+
400+ /**
401+ * Format the given long value as a CQL time literal, using the following time pattern: {@code hh:mm:ss[.fffffffff]}.
402+ *
403+ * @param value A long value representing the number of nanoseconds since midnight.
404+ * @return The formatted value.
405+ * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtime">Working with time</a>
406+ * section of CQL specification.
407+ */
408+ public static String formatTime(long value) {
409+ int nano = (int)(value % 1000000000);
410+ value -= nano;
411+ value /= 1000000000;
412+ int seconds = (int)(value % 60);
413+ value -= seconds;
414+ value /= 60;
415+ int minutes = (int)(value % 60);
416+ value -= minutes;
417+ value /= 60;
418+ int hours = (int)(value % 24);
419+ value -= hours;
420+ value /= 24;
421+ assert (value == 0);
422+ StringBuilder sb = new StringBuilder();
423+ leftPadZeros(hours, 2, sb);
424+ sb.append(":");
425+ leftPadZeros(minutes, 2, sb);
426+ sb.append(":");
427+ leftPadZeros(seconds, 2, sb);
428+ sb.append(".");
429+ leftPadZeros(nano, 9, sb);
430+ return sb.toString();
431+ }
432+
433+ /**
434+ * Simple method to replace a single character.
435+ * {@code String.replace()} is a bit too inefficient (see JAVA-67).
436+ * This methods is specially useful for escaping single quotes
437+ * in CQL strings:
438+ *
439+ * <pre>{@code
440+ * ParseUtils.replaceChar(value, '\'', "''");
441+ * }</pre>
442+ *
443+ * @param text The text.
444+ * @param search The character to search for.
445+ * @param replacement The replacement.
446+ * @return The text with all occurrences of {@code search} replaced with {@code replacement}.
447+ */
448+ private static String replaceChar(String text, char search, String replacement) {
449+ if (text == null || text.isEmpty())
450+ return text;
451+
452+ int nbMatch = 0;
453+ int start = -1;
454+ do {
455+ start = text.indexOf(search, start + 1);
456+ if (start != -1)
457+ ++nbMatch;
458+ } while (start != -1);
459+
460+ if (nbMatch == 0)
461+ return text;
462+
463+ int newLength = text.length() + nbMatch * (replacement.length() - 1);
464+ char[] result = new char[newLength];
465+ int newIdx = 0;
466+ for (int i = 0; i < text.length(); i++) {
467+ char c = text.charAt(i);
468+ if (c == search) {
469+ for (int r = 0; r < replacement.length(); r++)
470+ result[newIdx++] = replacement.charAt(r);
471+ } else {
472+ result[newIdx++] = c;
473+ }
474+ }
475+ return new String(result);
476+ }
477+
478+ private static void leftPadZeros(int value, int digits, StringBuilder sb) {
479+ sb.append(String.format("%0" + digits + "d", value));
480+ }
481+
482+ private ParseUtils() {}
483+
163484 }
modified driver-core/src/main/java/com/datastax/driver/core/SanityChecks.java +1 −1
@@ -47,7 +47,7 @@
4747 */
4848 static void checkGuava() {
4949 boolean resolved = false;
50- TypeToken<Map<String,String>> mapOfString = CodecUtils.mapOf(String.class, String.class);
50+ TypeToken<Map<String,String>> mapOfString = TypeTokens.mapOf(String.class, String.class);
5151 Type type = mapOfString.getType();
5252 if(type instanceof ParameterizedType) {
5353 ParameterizedType pType = (ParameterizedType)type;
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +78 −2
@@ -17,8 +17,7 @@
1717
1818 import java.nio.ByteBuffer;
1919
20-import static com.datastax.driver.core.CodecUtils.compose;
21-import static com.datastax.driver.core.CodecUtils.convert;
20+import com.datastax.driver.core.exceptions.InvalidTypeException;
2221
2322 /**
2423 * A simple {@code RegularStatement} implementation built directly from a query
@@ -195,4 +194,81 @@
195194 return this;
196195 }
197196
197+ /**
198+ * <p>
199+ * Utility method to serialize user-provided values.
200+ * <p>
201+ * This method is useful in situations where there is no metadata available and the underlying CQL
202+ * type for the values is not known.
203+ * <p>
204+ * This situation happens when a {@link SimpleStatement}
205+ * or a {@link com.datastax.driver.core.querybuilder.BuiltStatement} (Query Builder) contain values;
206+ * in these places, the driver has no way to determine the right CQL type to use.
207+ * <p>
208+ * This method performs a best-effort heuristic to guess which codec to use.
209+ * Note that this is not particularly efficient as the codec registry needs to iterate over
210+ * the registered codecs until it finds a suitable one.
211+ *
212+ * @param values The values to convert.
213+ * @param protocolVersion The protocol version to use.
214+ * @param codecRegistry The {@link CodecRegistry} to use.
215+ * @return The converted values.
216+ */
217+ public static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
218+ ByteBuffer[] serializedValues = new ByteBuffer[values.length];
219+ for (int i = 0; i < values.length; i++) {
220+ Object value = values[i];
221+ if (value == null) {
222+ // impossible to locate the right codec when object is null,
223+ // so forcing the result to null
224+ serializedValues[i] = null;
225+ } else {
226+ if (value instanceof Token) {
227+ // bypass CodecRegistry for Token instances
228+ serializedValues[i] = ((Token)value).serialize(protocolVersion);
229+ } else {
230+ try {
231+ TypeCodec<Object> codec = codecRegistry.codecFor(value);
232+ serializedValues[i] = codec.serialize(value, protocolVersion);
233+ } catch (Exception e) {
234+ // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
235+ throw new InvalidTypeException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, value.getClass()), e);
236+ }
237+ }
238+ }
239+ }
240+ return serializedValues;
241+ }
242+
243+ /**
244+ * Utility method to assemble different routing key components into a single {@link ByteBuffer}.
245+ * Mainly intended for statements that need to generate a routing key out of their current values.
246+ *
247+ * @param buffers the components of the routing key.
248+ * @return A ByteBuffer containing the serialized routing key
249+ */
250+ static ByteBuffer compose(ByteBuffer... buffers) {
251+ if (buffers.length == 1)
252+ return buffers[0];
253+
254+ int totalLength = 0;
255+ for (ByteBuffer bb : buffers)
256+ totalLength += 2 + bb.remaining() + 1;
257+
258+ ByteBuffer out = ByteBuffer.allocate(totalLength);
259+ for (ByteBuffer buffer : buffers) {
260+ ByteBuffer bb = buffer.duplicate();
261+ putShortLength(out, bb.remaining());
262+ out.put(bb);
263+ out.put((byte)0);
264+ }
265+ out.flip();
266+ return out;
267+ }
268+
269+ static void putShortLength(ByteBuffer bb, int length) {
270+ bb.put((byte)((length >> 8) & 0xFF));
271+ bb.put((byte)(length & 0xFF));
272+ }
273+
198274 }
modified driver-core/src/main/java/com/datastax/driver/core/TupleValue.java +2 −14
@@ -76,20 +76,8 @@
7676 @Override
7777 public String toString() {
7878 StringBuilder sb = new StringBuilder();
79- sb.append("(");
80- for (int i = 0; i < values.length; i++) {
81- if (i > 0)
82- sb.append(", ");
83-
84- if(values[i] == null)
85- sb.append("null");
86- else {
87- DataType dt = getType(i);
88- TypeCodec<Object> codec = getCodecRegistry().codecFor(dt);
89- sb.append(codec.format(codec.deserialize(values[i], protocolVersion)));
90- }
91- }
92- sb.append(")");
79+ TypeCodec<Object> codec = getCodecRegistry().codecFor(type);
80+ sb.append(codec.format(this));
9381 return sb.toString();
9482 }
9583 }
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +477 −387
@@ -23,10 +23,7 @@
2323 import java.nio.ByteBuffer;
2424 import java.nio.charset.Charset;
2525 import java.text.ParseException;
26-import java.text.ParsePosition;
27-import java.text.SimpleDateFormat;
2826 import java.util.*;
29-import java.util.concurrent.TimeUnit;
3027 import java.util.regex.Pattern;
3128
3229 import com.google.common.collect.ImmutableMap;
@@ -38,9 +35,9 @@
3835 import com.datastax.driver.core.exceptions.InvalidTypeException;
3936 import com.datastax.driver.core.utils.Bytes;
4037
41-import static com.datastax.driver.core.CodecUtils.listOf;
42-import static com.datastax.driver.core.CodecUtils.mapOf;
43-import static com.datastax.driver.core.CodecUtils.setOf;
38+import static com.datastax.driver.core.TypeTokens.listOf;
39+import static com.datastax.driver.core.TypeTokens.mapOf;
40+import static com.datastax.driver.core.TypeTokens.setOf;
4441 import static com.datastax.driver.core.DataType.*;
4542
4643 /**
@@ -264,7 +261,7 @@
264261 * The returned instance is a singleton.
265262 * @return the default codec for CQL type {@code time}.
266263 **/
267- public static TypeCodec<Long> time() {
264+ public static PrimitiveLongCodec time() {
268265 return TimeCodec.instance;
269266 }
270267
@@ -778,49 +775,17 @@
778775 public String parse(String value) {
779776 if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
780777 return null;
781- if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
778+ if (!ParseUtils.isQuoted(value))
782779 throw new InvalidTypeException("text or varchar values must be enclosed by single quotes");
783780
784- return value.substring(1, value.length() - 1).replace("''", "'");
781+ return ParseUtils.unquote(value);
785782 }
786783
787784 @Override
788785 public String format(String value) {
789786 if (value == null)
790787 return "NULL";
791- return '\'' + replace(value, '\'', "''") + '\'';
792- }
793-
794- // Simple method to replace a single character. String.replace is a bit too
795- // inefficient (see JAVA-67)
796- private static String replace(String text, char search, String replacement) {
797- if (text == null || text.isEmpty())
798- return text;
799-
800- int nbMatch = 0;
801- int start = -1;
802- do {
803- start = text.indexOf(search, start + 1);
804- if (start != -1)
805- ++nbMatch;
806- } while (start != -1);
807-
808- if (nbMatch == 0)
809- return text;
810-
811- int newLength = text.length() + nbMatch * (replacement.length() - 1);
812- char[] result = new char[newLength];
813- int newIdx = 0;
814- for (int i = 0; i < text.length(); i++) {
815- char c = text.charAt(i);
816- if (c == search) {
817- for (int r = 0; r < replacement.length(); r++)
818- result[newIdx++] = replacement.charAt(r);
819- } else {
820- result[newIdx++] = c;
821- }
822- }
823- return new String(result);
788+ return ParseUtils.quote(value);
824789 }
825790
826791 @Override
@@ -832,7 +797,7 @@
832797 * {@inheritDoc}
833798 *
834799 * Implementation note: this method treats {@code null}s and empty buffers differently:
835- * the formers are mapped to {@code null}s while the latters are mappend to empty strings.
800+ * the formers are mapped to {@code null}s while the latters are mapped to empty strings.
836801 */
837802 @Override
838803 public String deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
@@ -1243,7 +1208,7 @@
12431208 return null;
12441209
12451210 value = value.trim();
1246- if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
1211+ if (!ParseUtils.isQuoted(value))
12471212 throw new InvalidTypeException(String.format("inet values must be enclosed in single quotes (\"%s\")", value));
12481213 try {
12491214 return InetAddress.getByName(value.substring(1, value.length() - 1));
@@ -1416,64 +1381,21 @@
14161381 */
14171382 private static class TimestampCodec extends TypeCodec<Date> {
14181383
1419- private static final String[] iso8601Patterns = new String[]{
1420- "yyyy-MM-dd HH:mm",
1421- "yyyy-MM-dd HH:mm:ss",
1422- "yyyy-MM-dd HH:mmZ",
1423- "yyyy-MM-dd HH:mm:ssZ",
1424- "yyyy-MM-dd HH:mm:ss.SSS",
1425- "yyyy-MM-dd HH:mm:ss.SSSZ",
1426- "yyyy-MM-dd'T'HH:mm",
1427- "yyyy-MM-dd'T'HH:mmZ",
1428- "yyyy-MM-dd'T'HH:mm:ss",
1429- "yyyy-MM-dd'T'HH:mm:ssZ",
1430- "yyyy-MM-dd'T'HH:mm:ss.SSS",
1431- "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
1432- "yyyy-MM-dd",
1433- "yyyy-MM-ddZ"
1434- };
1435-
14361384 private static final TimestampCodec instance = new TimestampCodec();
14371385
1438- private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
1439-
14401386 private TimestampCodec() {
14411387 super(DataType.timestamp(), Date.class);
14421388 }
14431389
1444- /*
1445- * Copied and adapted from apache commons DateUtils.parseStrictly method (that is used Cassandra side
1446- * to parse date strings). It is copied here so as to not create a dependency on apache commons "just
1447- * for this".
1448- */
1449- private static Date parseDate(String str, final String[] parsePatterns) throws ParseException {
1450- SimpleDateFormat parser = new SimpleDateFormat();
1451- parser.setLenient(false);
1452-
1453- ParsePosition pos = new ParsePosition(0);
1454- for (String parsePattern : parsePatterns) {
1455-
1456- parser.applyPattern(parsePattern);
1457- pos.setIndex(0);
1458-
1459- Date date = parser.parse(str, pos);
1460- if (date != null && pos.getIndex() == str.length()) {
1461- return date;
1462- }
1463- }
1464- throw new ParseException("Unable to parse the date: " + str, -1);
1465- }
1466-
14671390 @Override
14681391 public Date parse(String value) {
14691392 if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
14701393 return null;
1471-
14721394 // strip enclosing single quotes, if any
1473- if (value.charAt(0) == '\'' && value.charAt(value.length() - 1) == '\'')
1474- value = value.substring(1, value.length() - 1);
1395+ if (ParseUtils.isQuoted(value))
1396+ value = ParseUtils.unquote(value);
14751397
1476- if (IS_LONG_PATTERN.matcher(value).matches()) {
1398+ if (ParseUtils.isLongLiteral(value)) {
14771399 try {
14781400 return new Date(Long.parseLong(value));
14791401 } catch (NumberFormatException e) {
@@ -1482,7 +1404,7 @@
14821404 }
14831405
14841406 try {
1485- return parseDate(value, iso8601Patterns);
1407+ return ParseUtils.parseDate(value);
14861408 } catch (ParseException e) {
14871409 throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value));
14881410 }
@@ -1513,10 +1435,7 @@
15131435
15141436 private static final DateCodec instance = new DateCodec();
15151437
1516- private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
15171438 private static final String pattern = "yyyy-MM-dd";
1518- private static final long MAX_LONG_VALUE = (1L << 32) - 1;
1519- private static final long EPOCH_AS_CQL_LONG = (1L << 31);
15201439
15211440 private DateCodec() {
15221441 super(DataType.date(), LocalDate.class);
@@ -1527,69 +1446,58 @@
15271446 if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
15281447 return null;
15291448
1530- // strip enclosing single quotes, if any
15311449 // single quotes are optional for long literals, mandatory for date patterns
1532- if (value.charAt(0) == '\'' && value.charAt(value.length() - 1) == '\'')
1533- value = value.substring(1, value.length() - 1);
1534-
1535- if (IS_LONG_PATTERN.matcher(value).matches()) {
1536- // In CQL, numeric DATE literals are longs between 0 and 2^32 - 1, with the epoch in the middle,
1537- // so parse it as a long and re-center at 0
1538- long cqlLong;
1450+ // strip enclosing single quotes, if any
1451+ if (ParseUtils.isQuoted(value))
1452+ value = ParseUtils.unquote(value);
1453+
1454+ if (ParseUtils.isLongLiteral(value)) {
1455+ long unsigned;
15391456 try {
1540- cqlLong = Long.parseLong(value);
1457+ unsigned = Long.parseLong(value);
15411458 } catch (NumberFormatException e) {
1542- throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
1459+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value), e);
1460+ }
1461+ try {
1462+ int days = CodecUtils.fromCqlDateToDaysSinceEpoch(unsigned);
1463+ return LocalDate.fromDaysSinceEpoch(days);
1464+ } catch (IllegalArgumentException e) {
1465+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value), e);
15431466 }
1544- if (cqlLong < 0 || cqlLong > MAX_LONG_VALUE)
1545- throw new InvalidTypeException(String.format("Numeric literals for DATE must be between 0 and %d (got %d)",
1546- MAX_LONG_VALUE, cqlLong));
1547-
1548- int days = (int)(cqlLong - EPOCH_AS_CQL_LONG);
1549-
1550- return LocalDate.fromDaysSinceEpoch(days);
15511467 }
15521468
1553- SimpleDateFormat parser = new SimpleDateFormat(pattern);
1554- parser.setLenient(false);
1555- parser.setTimeZone(TimeZone.getTimeZone("UTC"));
1556-
1557- ParsePosition pos = new ParsePosition(0);
1558- Date date = parser.parse(value, pos);
1559- if (date != null && pos.getIndex() == value.length()) {
1469+ try {
1470+ Date date = ParseUtils.parseDate(value, pattern);
15601471 return LocalDate.fromMillisSinceEpoch(date.getTime());
1472+ } catch (ParseException e) {
1473+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value), e);
15611474 }
1562-
1563- throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
15641475 }
15651476
15661477 @Override
15671478 public String format(LocalDate value) {
15681479 if (value == null)
15691480 return "NULL";
1570- return "'" + value.toString() + "'";
1481+ return ParseUtils.quote(value.toString());
15711482 }
15721483
15731484 @Override
15741485 public ByteBuffer serialize(LocalDate value, ProtocolVersion protocolVersion) {
1575- return value == null ? null : IntCodec.instance.serializeNoBoxing(javaToProtocol(value.getDaysSinceEpoch()), protocolVersion);
1486+ if (value == null)
1487+ return null;
1488+ int unsigned = CodecUtils.fromSignedToUnsignedInt(value.getDaysSinceEpoch());
1489+ return IntCodec.instance.serializeNoBoxing(unsigned, protocolVersion);
15761490 }
15771491
15781492 @Override
15791493 public LocalDate deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
1580- return bytes == null || bytes.remaining() == 0 ? null : LocalDate.fromDaysSinceEpoch(protocolToJava(IntCodec.instance.deserializeNoBoxing(bytes, protocolVersion)));
1581- }
1582-
1583- // The protocol encodes DATE as an _unsigned_ int with the epoch in the middle of the range (2^31).
1584- // We read this with ByteBuffer#getInt which expects a signed int, and we want epoch at 0.
1585- // These two methods handle the conversions.
1586- private static int protocolToJava(int p) {
1587- return p + Integer.MIN_VALUE; // this relies on overflow for "negative" values
1494+ if (bytes == null || bytes.remaining() == 0)
1495+ return null;
1496+ int unsigned = IntCodec.instance.deserializeNoBoxing(bytes, protocolVersion);
1497+ int signed = CodecUtils.fromUnsignedToSignedInt(unsigned);
1498+ return LocalDate.fromDaysSinceEpoch(signed);
15881499 }
15891500
1590- private static int javaToProtocol(int j) {
1591- return j - Integer.MIN_VALUE;
1592- }
15931501 }
15941502
15951503 /**
@@ -1597,97 +1505,34 @@
15971505 */
15981506 private static class TimeCodec extends LongCodec {
15991507
1600- private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$");
1601-
16021508 private static final TimeCodec instance = new TimeCodec();
16031509
16041510 private TimeCodec() {
16051511 super(DataType.time());
16061512 }
16071513
1608- // Time specific parsing loosely based on java.sql.Timestamp
1609- private static Long parseTime(String s) throws IllegalArgumentException {
1610- String nanos_s;
1611-
1612- long hour;
1613- long minute;
1614- long second;
1615- long a_nanos = 0;
1616-
1617- String formatError = "Timestamp format must be hh:mm:ss[.fffffffff]";
1618- String zeros = "000000000";
1619-
1620- if (s == null)
1621- throw new java.lang.IllegalArgumentException(formatError);
1622- s = s.trim();
1623-
1624- // Parse the time
1625- int firstColon = s.indexOf(':');
1626- int secondColon = s.indexOf(':', firstColon + 1);
1627-
1628- // Convert the time; default missing nanos
1629- if (firstColon > 0 && secondColon > 0 && secondColon < s.length() - 1) {
1630- int period = s.indexOf('.', secondColon + 1);
1631- hour = Integer.parseInt(s.substring(0, firstColon));
1632- if (hour < 0 || hour >= 24)
1633- throw new IllegalArgumentException("Hour out of bounds.");
1634-
1635- minute = Integer.parseInt(s.substring(firstColon + 1, secondColon));
1636- if (minute < 0 || minute >= 60)
1637- throw new IllegalArgumentException("Minute out of bounds.");
1638-
1639- if (period > 0 && period < s.length() - 1) {
1640- second = Integer.parseInt(s.substring(secondColon + 1, period));
1641- if (second < 0 || second >= 60)
1642- throw new IllegalArgumentException("Second out of bounds.");
1643-
1644- nanos_s = s.substring(period + 1);
1645- if (nanos_s.length() > 9)
1646- throw new IllegalArgumentException(formatError);
1647- if (!Character.isDigit(nanos_s.charAt(0)))
1648- throw new IllegalArgumentException(formatError);
1649- nanos_s = nanos_s + zeros.substring(0, 9 - nanos_s.length());
1650- a_nanos = Integer.parseInt(nanos_s);
1651- } else if (period > 0)
1652- throw new IllegalArgumentException(formatError);
1653- else {
1654- second = Integer.parseInt(s.substring(secondColon + 1));
1655- if (second < 0 || second >= 60)
1656- throw new IllegalArgumentException("Second out of bounds.");
1657- }
1658- } else
1659- throw new IllegalArgumentException(formatError);
1660-
1661- long rawTime = 0;
1662- rawTime += TimeUnit.HOURS.toNanos(hour);
1663- rawTime += TimeUnit.MINUTES.toNanos(minute);
1664- rawTime += TimeUnit.SECONDS.toNanos(second);
1665- rawTime += a_nanos;
1666- return rawTime;
1667- }
1668-
16691514 @Override
16701515 public Long parse(String value) {
16711516 if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
16721517 return null;
16731518
16741519 // enclosing single quotes required, even for long literals
1675- if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
1520+ if (!ParseUtils.isQuoted(value))
16761521 throw new InvalidTypeException("time values must be enclosed by single quotes");
16771522 value = value.substring(1, value.length() - 1);
16781523
1679- if (IS_LONG_PATTERN.matcher(value).matches()) {
1524+ if (ParseUtils.isLongLiteral(value)) {
16801525 try {
16811526 return Long.parseLong(value);
16821527 } catch (NumberFormatException e) {
1683- throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value));
1528+ throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e);
16841529 }
16851530 }
16861531
16871532 try {
1688- return parseTime(value);
1689- } catch (IllegalArgumentException e) {
1690- throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value));
1533+ return ParseUtils.parseTime(value);
1534+ } catch (ParseException e) {
1535+ throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e);
16911536 }
16921537 }
16931538
@@ -1695,33 +1540,7 @@
16951540 public String format(Long value) {
16961541 if (value == null)
16971542 return "NULL";
1698- int nano = (int)(value % 1000000000);
1699- value -= nano;
1700- value /= 1000000000;
1701- int seconds = (int)(value % 60);
1702- value -= seconds;
1703- value /= 60;
1704- int minutes = (int)(value % 60);
1705- value -= minutes;
1706- value /= 60;
1707- int hours = (int)(value % 24);
1708- value -= hours;
1709- value /= 24;
1710- assert (value == 0);
1711- StringBuilder sb = new StringBuilder("'");
1712- leftPadZeros(hours, 2, sb);
1713- sb.append(":");
1714- leftPadZeros(minutes, 2, sb);
1715- sb.append(":");
1716- leftPadZeros(seconds, 2, sb);
1717- sb.append(".");
1718- leftPadZeros(nano, 9, sb);
1719- sb.append("'");
1720- return sb.toString();
1721- }
1722-
1723- private static void leftPadZeros(int value, int digits, StringBuilder sb) {
1724- sb.append(String.format("%0" + digits + "d", value));
1543+ return ParseUtils.quote(ParseUtils.formatTime(value));
17251544 }
17261545
17271546 }
@@ -1740,7 +1559,7 @@
17401559 try {
17411560 return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : UUID.fromString(value);
17421561 } catch (IllegalArgumentException e) {
1743- throw new InvalidTypeException(String.format("Cannot parse UUID value from \"%s\"", value));
1562+ throw new InvalidTypeException(String.format("Cannot parse UUID value from \"%s\"", value), e);
17441563 }
17451564 }
17461565
@@ -1826,7 +1645,7 @@
18261645 try {
18271646 return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : new BigInteger(value);
18281647 } catch (NumberFormatException e) {
1829- throw new InvalidTypeException(String.format("Cannot parse varint value from \"%s\"", value));
1648+ throw new InvalidTypeException(String.format("Cannot parse varint value from \"%s\"", value), e);
18301649 }
18311650 }
18321651
@@ -1849,16 +1668,16 @@
18491668 }
18501669
18511670 /**
1852- * Base class for codecs handling CQL collection types such as {@link DataType#list(DataType)}
1853- * or {@link DataType#set(DataType)}.
1854- * Note that for practical reasons, {@link MapCodec} does not inherit from this class.
1671+ * Base class for codecs mapping CQL {@link DataType#list(DataType) lists}
1672+ * and {@link DataType#set(DataType) sets} to Java collections.
18551673 */
1856- private abstract static class CollectionCodec<E, C extends Collection<E>> extends TypeCodec<C> {
1674+ public abstract static class AbstractCollectionCodec<E, C extends Collection<E>> extends TypeCodec<C> {
18571675
18581676 protected final TypeCodec<E> eltCodec;
18591677
1860- private CollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) {
1678+ protected AbstractCollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) {
18611679 super(cqlType, javaType);
1680+ checkArgument(cqlType.getName() == Name.LIST || cqlType.getName() == Name.SET, "Expecting list or set type, got %s", cqlType);
18621681 this.eltCodec = eltCodec;
18631682 }
18641683
@@ -1866,7 +1685,8 @@
18661685 public ByteBuffer serialize(C value, ProtocolVersion protocolVersion) {
18671686 if (value == null)
18681687 return null;
1869- List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(value.size());
1688+ int i = 0;
1689+ ByteBuffer[] bbs = new ByteBuffer[value.size()];
18701690 for (E elt : value) {
18711691 if (elt == null) {
18721692 throw new NullPointerException("Collection elements cannot be null");
@@ -1879,7 +1699,7 @@
18791699 String.format("Invalid type for %s element, expecting %s but got %s",
18801700 cqlType, eltCodec.getJavaType(), elt.getClass()), e);
18811701 }
1882- bbs.add(bb);
1702+ bbs[i++] = bb;
18831703 }
18841704 return CodecUtils.pack(bbs, value.size(), protocolVersion);
18851705 }
@@ -1890,15 +1710,15 @@
18901710 return newInstance(0);
18911711 try {
18921712 ByteBuffer input = bytes.duplicate();
1893- int n = CodecUtils.readCollectionSize(input, protocolVersion);
1894- C coll = newInstance(n);
1895- for (int i = 0; i < n; i++) {
1896- ByteBuffer databb = CodecUtils.readCollectionValue(input, protocolVersion);
1713+ int size = CodecUtils.readSize(input, protocolVersion);
1714+ C coll = newInstance(size);
1715+ for (int i = 0; i < size; i++) {
1716+ ByteBuffer databb = CodecUtils.readValue(input, protocolVersion);
18971717 coll.add(eltCodec.deserialize(databb, protocolVersion));
18981718 }
18991719 return coll;
19001720 } catch (BufferUnderflowException e) {
1901- throw new InvalidTypeException("Not enough bytes to deserialize list");
1721+ throw new InvalidTypeException("Not enough bytes to deserialize collection", e);
19021722 }
19031723 }
19041724
@@ -1925,7 +1745,7 @@
19251745
19261746 int idx = ParseUtils.skipSpaces(value, 0);
19271747 if (value.charAt(idx++) != getOpeningChar())
1928- throw new InvalidTypeException(String.format("cannot parse list value from \"%s\", at character %d expecting '[' but got '%c'", value, idx, value.charAt(idx)));
1748+ throw new InvalidTypeException(String.format("cannot parse collection value from \"%s\", at character %d expecting '%s' but got '%c'", value, idx, getOpeningChar(), value.charAt(idx)));
19291749
19301750 idx = ParseUtils.skipSpaces(value, idx);
19311751
@@ -1938,7 +1758,7 @@
19381758 try {
19391759 n = ParseUtils.skipCQLValue(value, idx);
19401760 } catch (IllegalArgumentException e) {
1941- throw new InvalidTypeException(String.format("Cannot parse list value from \"%s\", invalid CQL value at character %d", value, idx), e);
1761+ throw new InvalidTypeException(String.format("Cannot parse collection value from \"%s\", invalid CQL value at character %d", value, idx), e);
19421762 }
19431763
19441764 l.add(eltCodec.parse(value.substring(idx, n)));
@@ -1948,31 +1768,51 @@
19481768 if (value.charAt(idx) == getClosingChar())
19491769 return l;
19501770 if (value.charAt(idx++) != ',')
1951- throw new InvalidTypeException(String.format("Cannot parse list value from \"%s\", at character %d expecting ',' but got '%c'", value, idx, value.charAt(idx)));
1771+ throw new InvalidTypeException(String.format("Cannot parse collection value from \"%s\", at character %d expecting ',' but got '%c'", value, idx, value.charAt(idx)));
19521772
19531773 idx = ParseUtils.skipSpaces(value, idx);
19541774 }
1955- throw new InvalidTypeException(String.format("Malformed list value \"%s\", missing closing ']'", value));
1775+ throw new InvalidTypeException(String.format("Malformed collection value \"%s\", missing closing '%s'", value, getClosingChar()));
19561776 }
19571777
19581778 @Override
19591779 public boolean accepts(Object value) {
19601780 if (getJavaType().getRawType().isAssignableFrom(value.getClass())) {
19611781 // runtime type ok, now check element type
1962- Collection<?> list = (Collection<?>)value;
1963- if (list.isEmpty())
1782+ Collection<?> coll = (Collection<?>)value;
1783+ if (coll.isEmpty())
19641784 return true;
1965- Object elt = list.iterator().next();
1785+ Object elt = coll.iterator().next();
19661786 return eltCodec.accepts(elt);
19671787 }
19681788 return false;
19691789 }
19701790
1971- protected abstract C newInstance(int capacity);
1791+ /**
1792+ * Return a new instance of {@code C} with the given estimated size.
1793+ *
1794+ * @param size The estimated size of the collection to create.
1795+ * @return new instance of {@code C} with the given estimated size.
1796+ */
1797+ protected abstract C newInstance(int size);
19721798
1973- protected abstract char getOpeningChar();
1799+ /**
1800+ * Return the opening character to use when formatting values as CQL literals.
1801+ *
1802+ * @return The opening character to use when formatting values as CQL literals.
1803+ */
1804+ private char getOpeningChar() {
1805+ return cqlType.getName() == Name.LIST ? '[' : '{';
1806+ }
19741807
1975- protected abstract char getClosingChar();
1808+ /**
1809+ * Return the closing character to use when formatting values as CQL literals.
1810+ *
1811+ * @return The closing character to use when formatting values as CQL literals.
1812+ */
1813+ private char getClosingChar() {
1814+ return cqlType.getName() == Name.LIST ? ']' : '}';
1815+ }
19761816
19771817 }
19781818
@@ -1980,25 +1820,15 @@
19801820 * This codec maps a CQL {@link DataType#list(DataType) list type} to a Java {@link List}.
19811821 * Implementation note: this codec returns mutable, non thread-safe {@link ArrayList} instances.
19821822 */
1983- private static class ListCodec<T> extends CollectionCodec<T, List<T>> {
1823+ private static class ListCodec<T> extends AbstractCollectionCodec<T, List<T>> {
19841824
19851825 private ListCodec(TypeCodec<T> eltCodec) {
1986- super(DataType.list(eltCodec.getCqlType()), listOf(eltCodec.getJavaType()), eltCodec);
1987- }
1988-
1989- @Override
1990- protected List<T> newInstance(int capacity) {
1991- return new ArrayList<T>(capacity);
1992- }
1993-
1994- @Override
1995- protected char getOpeningChar() {
1996- return '[';
1826+ super(DataType.list(eltCodec.getCqlType()), TypeTokens.listOf(eltCodec.getJavaType()), eltCodec);
19971827 }
19981828
19991829 @Override
2000- protected char getClosingChar() {
2001- return ']';
1830+ protected List<T> newInstance(int size) {
1831+ return new ArrayList<T>(size);
20021832 }
20031833
20041834 }
@@ -2007,40 +1837,30 @@
20071837 * This codec maps a CQL {@link DataType#set(DataType) set type} to a Java {@link Set}.
20081838 * Implementation note: this codec returns mutable, non thread-safe {@link LinkedHashSet} instances.
20091839 */
2010- private static class SetCodec<T> extends CollectionCodec<T, Set<T>> {
1840+ private static class SetCodec<T> extends AbstractCollectionCodec<T, Set<T>> {
20111841
20121842 private SetCodec(TypeCodec<T> eltCodec) {
2013- super(DataType.set(eltCodec.cqlType), setOf(eltCodec.getJavaType()), eltCodec);
2014- }
2015-
2016- @Override
2017- protected Set<T> newInstance(int capacity) {
2018- return new LinkedHashSet<T>(capacity);
1843+ super(DataType.set(eltCodec.cqlType), TypeTokens.setOf(eltCodec.getJavaType()), eltCodec);
20191844 }
20201845
20211846 @Override
2022- protected char getOpeningChar() {
2023- return '{';
1847+ protected Set<T> newInstance(int size) {
1848+ return new LinkedHashSet<T>(size);
20241849 }
20251850
2026- @Override
2027- protected char getClosingChar() {
2028- return '}';
2029- }
20301851 }
20311852
20321853 /**
2033- * This codec maps a CQL {@link DataType#map(DataType, DataType) map type} to a Java {@link Map}.
2034- * Implementation note: this codec returns mutable, non thread-safe {@link LinkedHashMap} instances.
1854+ * Base class for codecs mapping CQL {@link DataType#map(DataType, DataType) maps} to a Java {@link Map}.
20351855 */
2036- private static class MapCodec<K, V> extends TypeCodec<Map<K, V>> {
1856+ public abstract static class AbstractMapCodec<K, V> extends TypeCodec<Map<K, V>> {
20371857
2038- private final TypeCodec<K> keyCodec;
1858+ protected final TypeCodec<K> keyCodec;
20391859
2040- private final TypeCodec<V> valueCodec;
1860+ protected final TypeCodec<V> valueCodec;
20411861
2042- private MapCodec(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec) {
2043- super(DataType.map(keyCodec.getCqlType(), valueCodec.getCqlType()), mapOf(keyCodec.getJavaType(), valueCodec.getJavaType()));
1862+ protected AbstractMapCodec(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec) {
1863+ super(DataType.map(keyCodec.getCqlType(), valueCodec.getCqlType()), TypeTokens.mapOf(keyCodec.getJavaType(), valueCodec.getJavaType()));
20441864 this.keyCodec = keyCodec;
20451865 this.valueCodec = valueCodec;
20461866 }
@@ -2070,7 +1890,7 @@
20701890 idx = ParseUtils.skipSpaces(value, idx);
20711891
20721892 if (value.charAt(idx) == '}')
2073- return new LinkedHashMap<K, V>(0);
1893+ return newInstance(0);
20741894
20751895 Map<K, V> m = new HashMap<K, V>();
20761896 while (idx < value.length()) {
@@ -2134,7 +1954,8 @@
21341954 public ByteBuffer serialize(Map<K, V> value, ProtocolVersion protocolVersion) {
21351955 if (value == null)
21361956 return null;
2137- List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(2 * value.size());
1957+ int i = 0;
1958+ ByteBuffer[] bbs = new ByteBuffer[2 * value.size()];
21381959 for (Map.Entry<K, V> entry : value.entrySet()) {
21391960 ByteBuffer bbk;
21401961 K key = entry.getKey();
@@ -2144,7 +1965,7 @@
21441965 try {
21451966 bbk = keyCodec.serialize(key, protocolVersion);
21461967 } catch (ClassCastException e) {
2147- throw new InvalidTypeException(String.format("Invalid type for map key, expecting % but got %s", keyCodec.getJavaType(), key.getClass()), e);
1968+ throw new InvalidTypeException(String.format("Invalid type for map key, expecting %s but got %s", keyCodec.getJavaType(), key.getClass()), e);
21481969 }
21491970 ByteBuffer bbv;
21501971 V v = entry.getValue();
@@ -2154,10 +1975,10 @@
21541975 try {
21551976 bbv = valueCodec.serialize(v, protocolVersion);
21561977 } catch (ClassCastException e) {
2157- throw new InvalidTypeException(String.format("Invalid type for map value, expecting % but got %s", valueCodec.getJavaType(), v.getClass()), e);
1978+ throw new InvalidTypeException(String.format("Invalid type for map value, expecting %s but got %s", valueCodec.getJavaType(), v.getClass()), e);
21581979 }
2159- bbs.add(bbk);
2160- bbs.add(bbv);
1980+ bbs[i++] = bbk;
1981+ bbs[i++] = bbv;
21611982 }
21621983 return CodecUtils.pack(bbs, value.size(), protocolVersion);
21631984 }
@@ -2165,46 +1986,135 @@
21651986 @Override
21661987 public Map<K, V> deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
21671988 if (bytes == null || bytes.remaining() == 0)
2168- return new LinkedHashMap<K, V>(0);
1989+ return newInstance(0);
21691990 try {
21701991 ByteBuffer input = bytes.duplicate();
2171- int n = CodecUtils.readCollectionSize(input, protocolVersion);
2172- Map<K, V> m = new LinkedHashMap<K, V>(n);
1992+ int n = CodecUtils.readSize(input, protocolVersion);
1993+ Map<K, V> m = newInstance(n);
21731994 for (int i = 0; i < n; i++) {
2174- ByteBuffer kbb = CodecUtils.readCollectionValue(input, protocolVersion);
2175- ByteBuffer vbb = CodecUtils.readCollectionValue(input, protocolVersion);
1995+ ByteBuffer kbb = CodecUtils.readValue(input, protocolVersion);
1996+ ByteBuffer vbb = CodecUtils.readValue(input, protocolVersion);
21761997 m.put(keyCodec.deserialize(kbb, protocolVersion), valueCodec.deserialize(vbb, protocolVersion));
21771998 }
21781999 return m;
21792000 } catch (BufferUnderflowException e) {
2180- throw new InvalidTypeException("Not enough bytes to deserialize a map");
2001+ throw new InvalidTypeException("Not enough bytes to deserialize a map", e);
21812002 }
21822003 }
2004+
2005+ /**
2006+ * Return a new {@link Map} instance with the given estimated size.
2007+ *
2008+ * @param size The estimated size of the collection to create.
2009+ * @return A new {@link Map} instance with the given estimated size.
2010+ */
2011+ protected abstract Map<K, V> newInstance(int size);
2012+
2013+ }
2014+
2015+ /**
2016+ * This codec maps a CQL {@link DataType#map(DataType, DataType) map type} to a Java {@link Map}.
2017+ * Implementation note: this codec returns mutable, non thread-safe {@link LinkedHashMap} instances.
2018+ */
2019+ private static class MapCodec<K, V> extends AbstractMapCodec<K, V> {
2020+
2021+ private MapCodec(TypeCodec<K> keyCodec, TypeCodec<V> valueCodec) {
2022+ super(keyCodec, valueCodec);
2023+ }
2024+
2025+ @Override
2026+ protected Map<K, V> newInstance(int size) {
2027+ return new LinkedHashMap<K, V>(size);
2028+ }
2029+
21832030 }
21842031
21852032 /**
2186- * This codec maps a CQL {@link UserType} to a {@link UDTValue}.
2033+ * Base class for codecs mapping CQL {@link UserType user-defined types} (UDTs) to Java objects.
2034+ * It can serve as a base class for codecs dealing with direct UDT-to-Pojo mappings.
2035+ *
2036+ * @param <T> The Java type that the UDT will be mapped to.
21872037 */
2188- private static class UDTCodec extends TypeCodec<UDTValue> {
2038+ public abstract static class AbstractUDTCodec<T> extends TypeCodec<T> {
21892039
2190- private final UserType definition;
2040+ protected final UserType definition;
21912041
2192- private UDTCodec(UserType definition) {
2193- super(definition, UDTValue.class);
2042+ protected AbstractUDTCodec(UserType definition, Class<T> javaClass) {
2043+ super(definition, javaClass);
2044+ this.definition = definition;
2045+ }
2046+
2047+ protected AbstractUDTCodec(UserType definition, TypeToken<T> javaType) {
2048+ super(definition, javaType);
21942049 this.definition = definition;
21952050 }
21962051
21972052 @Override
2198- public boolean accepts(Object value) {
2199- return value instanceof UDTValue && ((UDTValue)value).getType().equals(definition);
2053+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) {
2054+ if (value == null)
2055+ return null;
2056+ int size = 0;
2057+ int length = definition.size();
2058+ ByteBuffer[] elements = new ByteBuffer[length];
2059+ int i = 0;
2060+ for (UserType.Field field : definition) {
2061+ elements[i] = serializeField(value, Metadata.escapeId(field.getName()), protocolVersion);
2062+ size += 4 + (elements[i] == null ? 0 : elements[i].remaining());
2063+ i++;
2064+ }
2065+ ByteBuffer result = ByteBuffer.allocate(size);
2066+ for (ByteBuffer bb : elements) {
2067+ if (bb == null) {
2068+ result.putInt(-1);
2069+ } else {
2070+ result.putInt(bb.remaining());
2071+ result.put(bb.duplicate());
2072+ }
2073+ }
2074+ return (ByteBuffer)result.flip();
22002075 }
22012076
22022077 @Override
2203- public UDTValue parse(String value) {
2204- if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
2078+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
2079+ if (bytes == null)
2080+ return null;
2081+ // empty byte buffers will result in empty values
2082+ ByteBuffer input = bytes.duplicate();
2083+ T value = newInstance();
2084+ for (UserType.Field field : definition) {
2085+ if (!input.hasRemaining())
2086+ break;
2087+ int n = input.getInt();
2088+ ByteBuffer element = n < 0 ? null : CodecUtils.readBytes(input, n);
2089+ value = deserializeAndSetField(element, value, Metadata.escapeId(field.getName()), protocolVersion);
2090+ }
2091+ return value;
2092+ }
2093+
2094+ @Override
2095+ public String format(T value) {
2096+ if (value == null)
2097+ return "NULL";
2098+ StringBuilder sb = new StringBuilder("{");
2099+ int i = 0;
2100+ for (UserType.Field field : definition) {
2101+ if (i > 0)
2102+ sb.append(",");
2103+ sb.append(Metadata.escapeId(field.getName()));
2104+ sb.append(":");
2105+ sb.append(formatField(value, Metadata.escapeId(field.getName())));
2106+ i += 1;
2107+ }
2108+ sb.append("}");
2109+ return sb.toString();
2110+ }
2111+
2112+ @Override
2113+ public T parse(String value) {
2114+ if (value == null || value.isEmpty() || value.equals("NULL"))
22052115 return null;
22062116
2207- UDTValue v = definition.newValue();
2117+ T v = newInstance();
22082118
22092119 int idx = ParseUtils.skipSpaces(value, 0);
22102120 if (value.charAt(idx++) != '{')
@@ -2240,9 +2150,8 @@
22402150 throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", invalid CQL value at character %d", value, idx), e);
22412151 }
22422152
2243- DataType dt = definition.getFieldType(name);
2244- TypeCodec<Object> codec = definition.getCodecRegistry().codecFor(dt);
2245- v.set(name, codec.parse(value.substring(idx, n)), codec.getJavaType());
2153+ String input = value.substring(idx, n);
2154+ v = parseAndSetField(input, v, name);
22462155 idx = n;
22472156
22482157 idx = ParseUtils.skipSpaces(value, idx);
@@ -2257,23 +2166,154 @@
22572166 throw new InvalidTypeException(String.format("Malformed UDT value \"%s\", missing closing '}'", value));
22582167 }
22592168
2169+ /**
2170+ * Return a new instance of {@code T}.
2171+ *
2172+ * @return A new instance of {@code T}.
2173+ */
2174+ protected abstract T newInstance();
2175+
2176+ /**
2177+ * Serialize an individual field in an object, as part of serializing the whole object to a CQL
2178+ * UDT (see {@link #serialize(Object, ProtocolVersion)}).
2179+ *
2180+ * @param source The object to read the field from.
2181+ * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
2182+ * characters, it will be double-quoted (i.e. the string will contain actual
2183+ * quote characters, as in {@code "\"foobar\""}).
2184+ * @param protocolVersion The protocol version to use.
2185+ * @return The serialized field, or {@code null} if that field should be ignored.
2186+ */
2187+ protected abstract ByteBuffer serializeField(T source, String fieldName, ProtocolVersion protocolVersion);
2188+
2189+ /**
2190+ * Deserialize an individual field and set it on an object, as part of deserializing the whole
2191+ * object from a CQL UDT (see {@link #deserialize(ByteBuffer, ProtocolVersion)}).
2192+ *
2193+ * @param input The serialized form of the field.
2194+ * @param target The object to set the field on.
2195+ * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
2196+ * characters, it will be double-quoted (i.e. the string will contain actual
2197+ * quote characters, as in {@code "\"foobar\""}).
2198+ * @param protocolVersion The protocol version to use.
2199+ * @return The target object with the field set. In most cases this should be the same as {@code target}, but if you're dealing
2200+ * with immutable types you'll need to return a different instance.
2201+ */
2202+ protected abstract T deserializeAndSetField(ByteBuffer input, T target, String fieldName, ProtocolVersion protocolVersion);
2203+
2204+ /**
2205+ * Format an individual field in an object as a CQL literal, as part of formatting the whole object
2206+ * (see {@link #format(Object)}).
2207+ *
2208+ * @param source The object to read the field from.
2209+ * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
2210+ * characters, it will be double-quoted (i.e. the string will contain actual
2211+ * quote characters, as in {@code "\"foobar\""}).
2212+ * @return The formatted value.
2213+ */
2214+ protected abstract String formatField(T source, String fieldName);
2215+
2216+ /**
2217+ * Parse an individual field and set it on an object, as part of parsing the whole object
2218+ * (see {@link #parse(String)}).
2219+ *
2220+ * @param input The String to parse the field from.
2221+ * @param target The value to write to.
2222+ * @param fieldName The name of the field. Note that if it is case-sensitive or contains special
2223+ * characters, it will be double-quoted (i.e. the string will contain actual
2224+ * quote characters, as in {@code "\"foobar\""}).
2225+ * @return The target object with the field set. In most cases this should be the same as {@code target}, but if you're dealing
2226+ * with immutable types you'll need to return a different instance.
2227+ */
2228+ protected abstract T parseAndSetField(String input, T target, String fieldName);
2229+ }
2230+
2231+ /**
2232+ * This codec maps a CQL {@link UserType} to a {@link UDTValue}.
2233+ */
2234+ private static class UDTCodec extends AbstractUDTCodec<UDTValue> {
2235+
2236+ private UDTCodec(UserType definition) {
2237+ super(definition, UDTValue.class);
2238+ }
2239+
22602240 @Override
2261- public String format(UDTValue value) {
2262- if (value == null)
2263- return "NULL";
2264- return value.toString();
2241+ public boolean accepts(Object value) {
2242+ return super.accepts(value) && ((UDTValue)value).getType().equals(definition);
2243+ }
2244+
2245+ @Override
2246+ protected UDTValue newInstance() {
2247+ return definition.newValue();
2248+ }
2249+
2250+ @Override
2251+ protected ByteBuffer serializeField(UDTValue source, String fieldName, ProtocolVersion protocolVersion) {
2252+ return source.getBytesUnsafe(fieldName);
2253+ }
2254+
2255+ @Override
2256+ protected UDTValue deserializeAndSetField(ByteBuffer input, UDTValue target, String fieldName, ProtocolVersion protocolVersion) {
2257+ return target.setBytesUnsafe(fieldName, input);
2258+ }
2259+
2260+ @Override
2261+ protected String formatField(UDTValue source, String fieldName) {
2262+ DataType elementType = definition.getFieldType(fieldName);
2263+ TypeCodec<Object> codec = definition.getCodecRegistry().codecFor(elementType);
2264+ return codec.format(source.get(fieldName, codec.getJavaType()));
2265+ }
2266+
2267+ @Override
2268+ protected UDTValue parseAndSetField(String input, UDTValue target, String fieldName) {
2269+ DataType elementType = definition.getFieldType(fieldName);
2270+ TypeCodec<Object> codec = definition.getCodecRegistry().codecFor(elementType);
2271+ target.set(fieldName, codec.parse(input), codec.getJavaType());
2272+ return target;
2273+ }
2274+ }
2275+
2276+ /**
2277+ * Base class for codecs mapping CQL {@link TupleType tuples} to Java objects.
2278+ * It can serve as a base class for codecs dealing with
2279+ * direct tuple-to-Pojo mappings.
2280+
2281+ * @param <T> The Java type that this codec handles.
2282+ */
2283+ public abstract static class AbstractTupleCodec<T> extends TypeCodec<T> {
2284+
2285+ protected final TupleType definition;
2286+
2287+ protected AbstractTupleCodec(TupleType definition, Class<T> javaClass) {
2288+ super(definition, javaClass);
2289+ this.definition = definition;
2290+ }
2291+
2292+ protected AbstractTupleCodec(TupleType definition, TypeToken<T> javaType) {
2293+ super(definition, javaType);
2294+ this.definition = definition;
2295+ }
2296+
2297+ @Override
2298+ public boolean accepts(DataType cqlType) {
2299+ // a tuple codec should accept tuple values of a different type,
2300+ // provided that the latter is contained in this codec's type.
2301+ return super.accepts(cqlType) && definition.contains((TupleType)cqlType);
22652302 }
22662303
22672304 @Override
2268- public ByteBuffer serialize(UDTValue value, ProtocolVersion protocolVersion) {
2305+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) {
22692306 if (value == null)
22702307 return null;
22712308 int size = 0;
2272- for (ByteBuffer v : value.values)
2273- size += 4 + (v == null ? 0 : v.remaining());
2274-
2309+ int length = definition.getComponentTypes().size();
2310+ ByteBuffer[] elements = new ByteBuffer[length];
2311+ for (int i = 0; i < length; i++) {
2312+ elements[i] = serializeField(value, i, protocolVersion);
2313+ size += 4 + (elements[i] == null ? 0 : elements[i].remaining());
2314+ }
22752315 ByteBuffer result = ByteBuffer.allocate(size);
2276- for (ByteBuffer bb : value.values) {
2316+ for (ByteBuffer bb : elements) {
22772317 if (bb == null) {
22782318 result.putInt(-1);
22792319 } else {
@@ -2285,54 +2325,42 @@
22852325 }
22862326
22872327 @Override
2288- public UDTValue deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
2328+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
22892329 if (bytes == null)
22902330 return null;
2291- // empty byte buffers will result in empty UDTValues
2331+ // empty byte buffers will result in empty values
22922332 ByteBuffer input = bytes.duplicate();
2293- UDTValue value = definition.newValue();
2294-
2333+ T value = newInstance();
22952334 int i = 0;
2296- while (input.hasRemaining() && i < value.values.length) {
2335+ while (input.hasRemaining() && i < definition.getComponentTypes().size()) {
22972336 int n = input.getInt();
2298- value.values[i++] = n < 0 ? null : CodecUtils.readBytes(input, n);
2337+ ByteBuffer element = n < 0 ? null : CodecUtils.readBytes(input, n);
2338+ value = deserializeAndSetField(element, value, i++, protocolVersion);
22992339 }
23002340 return value;
23012341 }
2302- }
2303-
2304- /**
2305- * This codec maps a CQL {@link TupleType} to a {@link TupleValue}.
2306- */
2307- private static class TupleCodec extends TypeCodec<TupleValue> {
2308-
2309- private final TupleType definition;
2310-
2311- private TupleCodec(TupleType definition) {
2312- super(definition, TupleValue.class);
2313- this.definition = definition;
2314- }
2315-
2316- @Override
2317- public boolean accepts(DataType cqlType) {
2318- // a tuple codec should accept tuple values of a different type,
2319- // provided that the latter is contained in this codec's type.
2320- return cqlType instanceof TupleType && definition.contains((TupleType)cqlType);
2321- }
23222342
23232343 @Override
2324- public boolean accepts(Object value) {
2325- // a tuple codec should accept tuple values of a different type,
2326- // provided that the latter is contained in this codec's type.
2327- return value instanceof TupleValue && definition.contains(((TupleValue)value).getType());
2344+ public String format(T value) {
2345+ if (value == null)
2346+ return "NULL";
2347+ StringBuilder sb = new StringBuilder("(");
2348+ int length = definition.getComponentTypes().size();
2349+ for (int i = 0; i < length; i++) {
2350+ if (i > 0)
2351+ sb.append(",");
2352+ sb.append(formatField(value, i));
2353+ }
2354+ sb.append(")");
2355+ return sb.toString();
23282356 }
23292357
23302358 @Override
2331- public TupleValue parse(String value) {
2359+ public T parse(String value) {
23322360 if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
23332361 return null;
23342362
2335- TupleValue v = definition.newValue();
2363+ T v = newInstance();
23362364
23372365 int idx = ParseUtils.skipSpaces(value, 0);
23382366 if (value.charAt(idx++) != '(')
@@ -2352,9 +2380,8 @@
23522380 throw new InvalidTypeException(String.format("Cannot parse tuple value from \"%s\", invalid CQL value at character %d", value, idx), e);
23532381 }
23542382
2355- DataType dt = definition.getComponentTypes().get(i);
2356- TypeCodec<Object> codec = definition.getCodecRegistry().codecFor(dt);
2357- v.set(i, codec.parse(value.substring(idx, n)), codec.getJavaType());
2383+ String input = value.substring(idx, n);
2384+ v = parseAndSetField(input, v, i);
23582385 idx = n;
23592386 i += 1;
23602387
@@ -2370,48 +2397,111 @@
23702397 throw new InvalidTypeException(String.format("Malformed tuple value \"%s\", missing closing ')'", value));
23712398 }
23722399
2400+ /**
2401+ * Return a new instance of {@code T}.
2402+ *
2403+ * @return A new instance of {@code T}.
2404+ */
2405+ protected abstract T newInstance();
2406+
2407+ /**
2408+ * Serialize an individual field in an object, as part of serializing the whole object to a CQL
2409+ * tuple (see {@link #serialize(Object, ProtocolVersion)}).
2410+ *
2411+ * @param source The object to read the field from.
2412+ * @param index The index of the field.
2413+ * @param protocolVersion The protocol version to use.
2414+ * @return The serialized field, or {@code null} if that field should be ignored.
2415+ */
2416+ protected abstract ByteBuffer serializeField(T source, int index, ProtocolVersion protocolVersion);
2417+
2418+ /**
2419+ * Deserialize an individual field and set it on an object, as part of deserializing the whole
2420+ * object from a CQL tuple (see {@link #deserialize(ByteBuffer, ProtocolVersion)}).
2421+ *
2422+ * @param input The serialized form of the field.
2423+ * @param target The object to set the field on.
2424+ * @param index The index of the field.
2425+ * @param protocolVersion The protocol version to use.
2426+ * @return The target object with the field set. In most cases this should be the same as {@code target}, but if you're dealing
2427+ * with immutable types you'll need to return a different instance.
2428+ */
2429+ protected abstract T deserializeAndSetField(ByteBuffer input, T target, int index, ProtocolVersion protocolVersion);
2430+
2431+ /**
2432+ * Format an individual field in an object as a CQL literal, as part of formatting the whole object
2433+ * (see {@link #format(Object)}).
2434+ *
2435+ * @param source The object to read the field from.
2436+ * @param index The index of the field.
2437+ * @return The formatted value.
2438+ */
2439+ protected abstract String formatField(T source, int index);
2440+
2441+ /**
2442+ * Parse an individual field and set it on an object, as part of parsing the whole object
2443+ * (see {@link #parse(String)}).
2444+ *
2445+ * @param input The String to parse the field from.
2446+ * @param target The value to write to.
2447+ * @param index The index of the field.
2448+ * @return The target object with the field set. In most cases this should be the same as {@code target}, but if you're dealing
2449+ * with immutable types you'll need to return a different instance.
2450+ */
2451+ protected abstract T parseAndSetField(String input, T target, int index);
2452+
2453+ }
2454+
2455+ /**
2456+ * This codec maps a CQL {@link TupleType tuple} to a {@link TupleValue}.
2457+ */
2458+ private static class TupleCodec extends AbstractTupleCodec<TupleValue> {
2459+
2460+ private TupleCodec(TupleType definition) {
2461+ super(definition, TupleValue.class);
2462+ }
2463+
23732464 @Override
2374- public String format(TupleValue value) {
2375- if (value == null)
2376- return "NULL";
2377- return value.toString();
2465+ public boolean accepts(Object value) {
2466+ // a tuple codec should accept tuple values of a different type,
2467+ // provided that the latter is contained in this codec's type.
2468+ return super.accepts(value) && definition.contains(((TupleValue)value).getType());
23782469 }
23792470
23802471 @Override
2381- public ByteBuffer serialize(TupleValue value, ProtocolVersion protocolVersion) {
2382- if (value == null)
2472+ protected TupleValue newInstance() {
2473+ return definition.newValue();
2474+ }
2475+
2476+ @Override
2477+ protected ByteBuffer serializeField(TupleValue source, int index, ProtocolVersion protocolVersion) {
2478+ if (index >= source.values.length)
23832479 return null;
2384- int size = 0;
2385- for (ByteBuffer v : value.values)
2386- size += 4 + (v == null ? 0 : v.remaining());
2480+ return source.getBytesUnsafe(index);
2481+ }
23872482
2388- ByteBuffer result = ByteBuffer.allocate(size);
2389- for (ByteBuffer bb : value.values) {
2390- if (bb == null) {
2391- result.putInt(-1);
2392- } else {
2393- result.putInt(bb.remaining());
2394- result.put(bb.duplicate());
2395- }
2396- }
2397- return (ByteBuffer)result.flip();
2483+ @Override
2484+ protected TupleValue deserializeAndSetField(ByteBuffer input, TupleValue target, int index, ProtocolVersion protocolVersion) {
2485+ if (index >= target.values.length)
2486+ return target;
2487+ return target.setBytesUnsafe(index, input);
23982488 }
23992489
24002490 @Override
2401- public TupleValue deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
2402- if (bytes == null)
2403- return null;
2404- // empty byte buffers will result in empty TupleValues
2405- ByteBuffer input = bytes.duplicate();
2406- TupleValue value = definition.newValue();
2491+ protected String formatField(TupleValue value, int index) {
2492+ DataType elementType = definition.getComponentTypes().get(index);
2493+ TypeCodec<Object> codec = definition.getCodecRegistry().codecFor(elementType);
2494+ return codec.format(value.get(index, codec.getJavaType()));
2495+ }
24072496
2408- int i = 0;
2409- while (input.hasRemaining() && i < value.values.length) {
2410- int n = input.getInt();
2411- value.values[i++] = n < 0 ? null : CodecUtils.readBytes(input, n);
2412- }
2413- return value;
2497+ @Override
2498+ protected TupleValue parseAndSetField(String input, TupleValue target, int index) {
2499+ DataType elementType = definition.getComponentTypes().get(index);
2500+ TypeCodec<Object> codec = definition.getCodecRegistry().codecFor(elementType);
2501+ target.set(index, codec.parse(input), codec.getJavaType());
2502+ return target;
24142503 }
2504+
24152505 }
24162506
24172507 }
added driver-core/src/main/java/com/datastax/driver/core/TypeTokens.java +117 −0
@@ -0,0 +1,117 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.List;
19+import java.util.Map;
20+import java.util.Set;
21+
22+import com.google.common.reflect.TypeParameter;
23+import com.google.common.reflect.TypeToken;
24+
25+/**
26+ * Utility methods to create {@code TypeToken} instances.
27+ */
28+public final class TypeTokens {
29+ private TypeTokens() {
30+ }
31+
32+ /**
33+ * Create a {@link TypeToken} that represents a {@link List} whose elements
34+ * are of the given type.
35+ *
36+ * @param eltType The list element type.
37+ * @param <T> The list element type.
38+ * @return A {@link TypeToken} that represents a {@link List} whose elements
39+ * are of the given type.
40+ */
41+ public static <T> TypeToken<List<T>> listOf(Class<T> eltType) {
42+ return new TypeToken<List<T>>(){}.where(new TypeParameter<T>(){}, eltType);
43+ }
44+
45+ /**
46+ * Create a {@link TypeToken} that represents a {@link List} whose elements
47+ * are of the given type.
48+ *
49+ * @param eltType The list element type.
50+ * @param <T> The list element type.
51+ * @return A {@link TypeToken} that represents a {@link List} whose elements
52+ * are of the given type.
53+ */
54+ public static <T> TypeToken<List<T>> listOf(TypeToken<T> eltType) {
55+ return new TypeToken<List<T>>(){}.where(new TypeParameter<T>(){}, eltType);
56+ }
57+
58+ /**
59+ * Create a {@link TypeToken} that represents a {@link Set} whose elements
60+ * are of the given type.
61+ *
62+ * @param eltType The set element type.
63+ * @param <T> The set element type.
64+ * @return A {@link TypeToken} that represents a {@link Set} whose elements
65+ * are of the given type.
66+ */
67+ public static <T> TypeToken<Set<T>> setOf(Class<T> eltType) {
68+ return new TypeToken<Set<T>>(){}.where(new TypeParameter<T>(){}, eltType);
69+ }
70+
71+ /**
72+ * Create a {@link TypeToken} that represents a {@link Set} whose elements
73+ * are of the given type.
74+ *
75+ * @param eltType The set element type.
76+ * @param <T> The set element type.
77+ * @return A {@link TypeToken} that represents a {@link Set} whose elements
78+ * are of the given type.
79+ */
80+ public static <T> TypeToken<Set<T>> setOf(TypeToken<T> eltType) {
81+ return new TypeToken<Set<T>>(){}.where(new TypeParameter<T>(){}, eltType);
82+ }
83+
84+ /**
85+ * Create a {@link TypeToken} that represents a {@link Map} whose keys
86+ * and values are of the given key and value types.
87+ *
88+ * @param keyType The map key type.
89+ * @param valueType The map value type
90+ * @param <K> The map key type.
91+ * @param <V> The map value type
92+ * @return A {@link TypeToken} that represents a {@link Map} whose keys
93+ * and values are of the given key and value types
94+ */
95+ public static <K, V> TypeToken<Map<K, V>> mapOf(Class<K> keyType, Class<V> valueType) {
96+ return new TypeToken<Map<K, V>>(){}
97+ .where(new TypeParameter<K>(){}, keyType)
98+ .where(new TypeParameter<V>(){}, valueType);
99+ }
100+
101+ /**
102+ * Create a {@link TypeToken} that represents a {@link Map} whose keys
103+ * and values are of the given key and value types.
104+ *
105+ * @param keyType The map key type.
106+ * @param valueType The map value type
107+ * @param <K> The map key type.
108+ * @param <V> The map value type
109+ * @return A {@link TypeToken} that represents a {@link Map} whose keys
110+ * and values are of the given key and value types
111+ */
112+ public static <K, V> TypeToken<Map<K, V>> mapOf(TypeToken<K> keyType, TypeToken<V> valueType) {
113+ return new TypeToken<Map<K, V>>(){}
114+ .where(new TypeParameter<K>(){}, keyType)
115+ .where(new TypeParameter<V>(){}, valueType);
116+ }
117+}
modified driver-core/src/main/java/com/datastax/driver/core/UDTValue.java +5 −20
@@ -30,11 +30,11 @@
3030 }
3131
3232 protected DataType getType(int i) {
33- return definition.getFields()[i].getType();
33+ return definition.byIdx[i].getType();
3434 }
3535
3636 protected String getName(int i) {
37- return definition.getFields()[i].getName();
37+ return definition.byIdx[i].getName();
3838 }
3939
4040 @Override
@@ -43,7 +43,7 @@
4343 }
4444
4545 protected int[] getAllIndexesOf(String name) {
46- int[] indexes = definition.getFieldIndicesByName().get(Metadata.handleId(name));
46+ int[] indexes = definition.byName.get(Metadata.handleId(name));
4747 if (indexes == null)
4848 throw new IllegalArgumentException(name + " is not a field defined in this UDT");
4949 return indexes;
@@ -78,23 +78,8 @@
7878 @Override
7979 public String toString() {
8080 StringBuilder sb = new StringBuilder();
81- sb.append("{");
82- for (int i = 0; i < values.length; i++) {
83- if (i > 0)
84- sb.append(",");
85-
86- sb.append(getName(i));
87- sb.append(":");
88-
89- if(values[i] == null)
90- sb.append("null");
91- else {
92- DataType dt = getType(i);
93- TypeCodec<Object> codec = getCodecRegistry().codecFor(dt);
94- sb.append(codec.format(codec.deserialize(values[i], protocolVersion)));
95- }
96- }
97- sb.append("}");
81+ TypeCodec<Object> codec = getCodecRegistry().codecFor(definition);
82+ sb.append(codec.format(this));
9883 return sb.toString();
9984 }
10085 }
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +3 −11
@@ -40,11 +40,11 @@
4040 // Note that we don't expose the order of fields, from an API perspective this is a map
4141 // of String->Field, but internally we care about the order because the serialization format
4242 // of UDT expects a particular order.
43- private final Field[] byIdx;
43+ final Field[] byIdx;
4444 // For a given name, we can only have one field with that name, so we don't need a int[] in
4545 // practice. However, storing one element arrays save allocations in UDTValue.getAllIndexesOf
4646 // implementation.
47- private final Map<String, int[]> byName;
47+ final Map<String, int[]> byName;
4848
4949 UserType(String keyspace, String typeName, Collection<Field> fields, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
5050 super(DataType.Name.UDT);
@@ -178,14 +178,6 @@
178178 return true;
179179 }
180180
181- Field[] getFields() {
182- return byIdx;
183- }
184-
185- Map<String, int[]> getFieldIndicesByName() {
186- return byName;
187- }
188-
189181 @Override
190182 public int hashCode() {
191183 int result = name.hashCode();
@@ -207,7 +199,7 @@
207199 return name.equals(other.name)
208200 && keyspace.equals(other.keyspace)
209201 && typeName.equals(other.typeName)
210- && Arrays.equals(getFields(), other.getFields());
202+ && Arrays.equals(byIdx, other.byIdx);
211203 }
212204
213205 /**
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +3 −6
@@ -24,9 +24,6 @@
2424 import com.datastax.driver.core.*;
2525 import com.datastax.driver.core.policies.RetryPolicy;
2626
27-import static com.datastax.driver.core.CodecUtils.compose;
28-import static com.datastax.driver.core.CodecUtils.convert;
29-
3027 /**
3128 * Common ancestor to the query builder built statements.
3229 */
@@ -68,7 +65,7 @@
6865 }
6966
7067 // Same as Metadata.escapeId, but we don't have access to it here.
71- protected String escapeId(String ident) {
68+ protected static String escapeId(String ident) {
7269 // we don't need to escape if it's lowercase and match non-quoted CQL3 ids.
7370 return lowercaseId.matcher(ident).matches() ? ident : Metadata.quote(ident);
7471 }
@@ -203,7 +200,7 @@
203200 }
204201 return routingKeyParts.length == 1
205202 ? routingKeyParts[0]
206- : compose(routingKeyParts);
203+ : Utils.compose(routingKeyParts);
207204 }
208205
209206 @Override
@@ -219,7 +216,7 @@
219216 @Override
220217 public ByteBuffer[] getValues() {
221218 maybeRebuildCache();
222- return values == null ? null : convert(values.toArray(), getProtocolVersion(), getCodecRegistry());
219+ return values == null ? null : Utils.convert(values.toArray(), getProtocolVersion(), getCodecRegistry());
223220 }
224221
225222 @Override
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +85 −1
@@ -17,6 +17,7 @@
1717
1818 import java.math.BigDecimal;
1919 import java.math.BigInteger;
20+import java.nio.ByteBuffer;
2021 import java.util.Collection;
2122 import java.util.List;
2223 import java.util.Map;
@@ -25,7 +26,11 @@
2526
2627 import static com.google.common.base.Preconditions.checkNotNull;
2728
28-import com.datastax.driver.core.*;
29+import com.datastax.driver.core.CodecRegistry;
30+import com.datastax.driver.core.ProtocolVersion;
31+import com.datastax.driver.core.Token;
32+import com.datastax.driver.core.TypeCodec;
33+import com.datastax.driver.core.exceptions.InvalidTypeException;
2934
3035 // Static utilities private to the query builder
3136 abstract class Utils {
@@ -263,6 +268,85 @@
263268 return sb;
264269 }
265270
271+ /**
272+ * This method is a copy of the one declared in {@link com.datastax.driver.core.SimpleStatement}.
273+ * <p>
274+ * Utility method to serialize user-provided values.
275+ * <p>
276+ * This method is useful in situations where there is no metadata available and the underlying CQL
277+ * type for the values is not known.
278+ * <p>
279+ * This situation happens when a {@link com.datastax.driver.core.SimpleStatement}
280+ * or a {@link com.datastax.driver.core.querybuilder.BuiltStatement} (Query Builder) contain values;
281+ * in these places, the driver has no way to determine the right CQL type to use.
282+ * <p>
283+ * This method performs a best-effort heuristic to guess which codec to use.
284+ * Note that this is not particularly efficient as the codec registry needs to iterate over
285+ * the registered codecs until it finds a suitable one.
286+ *
287+ * @param values The values to convert.
288+ * @param protocolVersion The protocol version to use.
289+ * @param codecRegistry The {@link CodecRegistry} to use.
290+ * @return The converted values.
291+ */
292+ public static ByteBuffer[] convert(Object[] values, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
293+ ByteBuffer[] serializedValues = new ByteBuffer[values.length];
294+ for (int i = 0; i < values.length; i++) {
295+ Object value = values[i];
296+ if (value == null) {
297+ // impossible to locate the right codec when object is null,
298+ // so forcing the result to null
299+ serializedValues[i] = null;
300+ } else {
301+ if (value instanceof Token) {
302+ // bypass CodecRegistry for Token instances
303+ serializedValues[i] = ((Token)value).serialize(protocolVersion);
304+ } else {
305+ try {
306+ TypeCodec<Object> codec = codecRegistry.codecFor(value);
307+ serializedValues[i] = codec.serialize(value, protocolVersion);
308+ } catch (Exception e) {
309+ // Catch and rethrow to provide a more helpful error message (one that include which value is bad)
310+ throw new InvalidTypeException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, value.getClass()), e);
311+ }
312+ }
313+ }
314+ }
315+ return serializedValues;
316+ }
317+
318+ /**
319+ * This method is a copy of the one declared in {@link com.datastax.driver.core.SimpleStatement}.
320+ * Utility method to assemble different routing key components into a single {@link ByteBuffer}.
321+ * Mainly intended for statements that need to generate a routing key out of their current values.
322+ *
323+ * @param buffers the components of the routing key.
324+ * @return A ByteBuffer containing the serialized routing key
325+ */
326+ static ByteBuffer compose(ByteBuffer... buffers) {
327+ if (buffers.length == 1)
328+ return buffers[0];
329+
330+ int totalLength = 0;
331+ for (ByteBuffer bb : buffers)
332+ totalLength += 2 + bb.remaining() + 1;
333+
334+ ByteBuffer out = ByteBuffer.allocate(totalLength);
335+ for (ByteBuffer buffer : buffers) {
336+ ByteBuffer bb = buffer.duplicate();
337+ putShortLength(out, bb.remaining());
338+ out.put(bb);
339+ out.put((byte)0);
340+ }
341+ out.flip();
342+ return out;
343+ }
344+
345+ static void putShortLength(ByteBuffer bb, int length) {
346+ bb.put((byte)((length >> 8) & 0xFF));
347+ bb.put((byte)(length & 0xFF));
348+ }
349+
266350 static abstract class Appendeable {
267351 abstract void appendTo(StringBuilder sb, List<Object> values, CodecRegistry codecRegistry);
268352 abstract boolean containsBindMarker();
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +5 −8
@@ -230,24 +230,21 @@
230230 @SuppressWarnings("serial")
231231 @Test(groups = "unit")
232232 public void parseFormatUDTTest() {
233-
234- String toParse = "{t:'fo''o',i:3,l:['a','b'],s:{3:{a:0x01}}}";
233+ String toParse = "{t:'fo''o',i:3,\"L\":['a','b'],s:{3:{a:0x01}}}";
235234
236235 final UserType udt1 = new UserType("ks", "t", Arrays.asList(new UserType.Field("a", DataType.blob())), protocolVersion, codecRegistry);
237236 UserType udt2 = new UserType("ks", "t", Arrays.asList(
238237 new UserType.Field("t", DataType.text()),
239238 new UserType.Field("i", DataType.cint()),
240- new UserType.Field("l", DataType.list(DataType.text())),
239+ new UserType.Field("L", DataType.list(DataType.text())),
241240 new UserType.Field("s", DataType.map(DataType.cint(), udt1))
242241 ), protocolVersion, codecRegistry);
243242
244243 UDTValue toFormat = udt2.newValue();
245244 toFormat.setString("t", "fo'o");
246245 toFormat.setInt("i", 3);
247- toFormat.setList("l", Arrays.<String>asList("a", "b"));
248- toFormat.setMap("s", new HashMap<Integer, UDTValue>() {{
249- put(3, udt1.newValue().setBytes("a", ByteBuffer.wrap(new byte[]{ 1 })));
250- }});
246+ toFormat.setList("\"L\"", Arrays.<String>asList("a", "b"));
247+ toFormat.setMap("s", new HashMap<Integer, UDTValue>(){{ put(3, udt1.newValue().setBytes("a", ByteBuffer.wrap(new byte[]{1}))); }});
251248
252249 assertEquals(codecRegistry.codecFor(udt2).parse(toParse), toFormat);
253250 assertEquals(codecRegistry.codecFor(udt2).format(toFormat), toParse);
@@ -257,7 +254,7 @@
257254 @Test(groups = "unit")
258255 public void parseFormatTupleTest() {
259256
260- String toParse = "(1, 'foo', 1.0)";
257+ String toParse = "(1,'foo',1.0)";
261258 TupleType t = new TupleType(newArrayList(DataType.cint(), DataType.text(), DataType.cfloat()), protocolVersion, codecRegistry);
262259 TupleValue toFormat = t.newValue(1, "foo", 1.0f);
263260
deleted driver-core/src/test/java/com/datastax/driver/core/EnumIntCodec.java +0 −75
@@ -1,75 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.nio.ByteBuffer;
19-
20-import com.datastax.driver.core.exceptions.InvalidTypeException;
21-
22-/**
23- * A codec that serializes {@link Enum} instances as CQL {@link DataType#cint() int}s
24- * representing their ordinal values as returned by {@link Enum#ordinal()}.
25- * <p>
26- * Note that, by default, the driver uses {@link EnumStringCodec} to serialize {@link Enum} instances;
27- * to force the use of this codec instead for a specific {@link Enum} instance,
28- * the appropriate {@link EnumIntCodec} instance must be explicitly
29- * {@link CodecRegistry#register(TypeCodec) registered}.
30- * <p>
31- * <strong>Note that this codec relies on the enum constants declaration order;
32- * it is therefore vital that this order remains immutable.</strong>
33- *
34- * @param <E> The Enum class this codec serializes from and deserializes to.
35- */
36-public class EnumIntCodec<E extends Enum<E>> extends TypeCodec<E> {
37-
38- private final E[] enumConstants;
39-
40- private final TypeCodec<Integer> innerCodec;
41-
42- public EnumIntCodec(Class<E> enumClass) {
43- this(TypeCodec.cint(), enumClass);
44- }
45-
46- public EnumIntCodec(TypeCodec<Integer> innerCodec, Class<E> enumClass) {
47- super(innerCodec.getCqlType(), enumClass);
48- this.enumConstants = enumClass.getEnumConstants();
49- this.innerCodec = innerCodec;
50- }
51-
52- @Override
53- public ByteBuffer serialize(E value, ProtocolVersion protocolVersion) throws InvalidTypeException {
54- return value == null ? null : innerCodec.serialize(value.ordinal(), protocolVersion);
55- }
56-
57- @Override
58- public E deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
59- Integer value = innerCodec.deserialize(bytes, protocolVersion);
60- return value == null ? null : enumConstants[value];
61- }
62-
63- @Override
64- public String format(E value) throws InvalidTypeException {
65- if (value == null)
66- return "NULL";
67- return innerCodec.format(value.ordinal());
68- }
69-
70- @Override
71- public E parse(String value) throws InvalidTypeException {
72- return value == null || value.isEmpty() || value.equals("NULL") ? null : enumConstants[innerCodec.parse(value)];
73- }
74-
75-}
deleted driver-core/src/test/java/com/datastax/driver/core/EnumStringCodec.java +0 −70
@@ -1,70 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.nio.ByteBuffer;
19-
20-import com.datastax.driver.core.exceptions.InvalidTypeException;
21-
22-/**
23- * A codec that serializes {@link Enum} instances as CQL {@link DataType#varchar() varchar}s
24- * representing their programmatic names as returned by {@link Enum#name()}.
25- * <p>
26- * This codec is automatically used by the driver to create codecs for {@link Enum}
27- * instances on the fly.
28- *
29- * @param <E> The Enum class this codec serializes from and deserializes to.
30- */
31-public class EnumStringCodec<E extends Enum<E>> extends TypeCodec<E> {
32-
33- private final Class<E> enumClass;
34-
35- private final TypeCodec<String> innerCodec;
36-
37- public EnumStringCodec(Class<E> enumClass) {
38- this(TypeCodec.varchar(), enumClass);
39- }
40-
41- public EnumStringCodec(TypeCodec<String> innerCodec, Class<E> enumClass) {
42- super(innerCodec.getCqlType(), enumClass);
43- this.innerCodec = innerCodec;
44- this.enumClass = enumClass;
45- }
46-
47- @Override
48- public ByteBuffer serialize(E value, ProtocolVersion protocolVersion) throws InvalidTypeException {
49- return value == null ? null : innerCodec.serialize(value.name(), protocolVersion);
50- }
51-
52- @Override
53- public E deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
54- String value = innerCodec.deserialize(bytes, protocolVersion);
55- return value == null ? null : Enum.valueOf(enumClass, value);
56- }
57-
58- @Override
59- public String format(E value) throws InvalidTypeException {
60- if (value == null)
61- return "NULL";
62- return innerCodec.format(value.name());
63- }
64-
65- @Override
66- public E parse(String value) throws InvalidTypeException {
67- return value == null || value.isEmpty() || value.equals("NULL") ? null : Enum.valueOf(enumClass, innerCodec.parse(value));
68- }
69-
70-}
modified driver-core/src/test/java/com/datastax/driver/core/GettableDataIntegrationTest.java +5 −5
@@ -37,7 +37,7 @@
3737 import static com.google.common.collect.Lists.newArrayList;
3838 import static org.assertj.core.api.Assertions.assertThat;
3939
40-import static com.datastax.driver.core.CodecUtils.listOf;
40+import static com.datastax.driver.core.TypeTokens.listOf;
4141 import static com.datastax.driver.core.TestUtils.getValue;
4242 import static com.datastax.driver.core.TestUtils.setValue;
4343
@@ -173,7 +173,7 @@
173173 byName.setMap("m", map, mapping.javaType, mapping.javaType);
174174 if(is21) {
175175 byName.setTupleValue("t", tupleValue);
176- byName.setSet("s", set, listOf(mapping.javaType));
176+ byName.setSet("s", set, TypeTokens.listOf(mapping.javaType));
177177 }
178178 session.execute(byName);
179179
@@ -187,7 +187,7 @@
187187 byIndex.setMap(3, map, mapping.javaType, mapping.javaType);
188188 if(is21) {
189189 byIndex.setTupleValue(4, tupleValue);
190- byIndex.setSet(5, set, listOf(mapping.javaType));
190+ byIndex.setSet(5, set, TypeTokens.listOf(mapping.javaType));
191191 }
192192 session.execute(byIndex);
193193
@@ -214,7 +214,7 @@
214214 assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)).isEqualTo(mapping.value);
215215 assertThat(getValue(returnedTuple, 1, mapping.outerType, registry)).isEqualTo(mapping.value);
216216
217- assertThat(row.getSet("s", listOf(mapping.javaType))).isEqualTo(set);
217+ assertThat(row.getSet("s", TypeTokens.listOf(mapping.javaType))).isEqualTo(set);
218218 }
219219
220220 // Retrieve by index.
@@ -227,7 +227,7 @@
227227 assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)).isEqualTo(mapping.value);
228228 assertThat(getValue(returnedTuple, 1, mapping.outerType, registry)).isEqualTo(mapping.value);
229229
230- assertThat(row.getSet(4, listOf(mapping.javaType))).isEqualTo(set);
230+ assertThat(row.getSet(4, TypeTokens.listOf(mapping.javaType))).isEqualTo(set);
231231 }
232232 }
233233 }
deleted driver-core/src/test/java/com/datastax/driver/core/JodaCodecs.java +0 −188
@@ -1,188 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import org.joda.time.DateTime;
19-import org.joda.time.DateTimeZone;
20-import org.joda.time.LocalTime;
21-
22-import java.util.Date;
23-import java.util.List;
24-import java.util.concurrent.TimeUnit;
25-
26-import static com.google.common.base.Preconditions.checkArgument;
27-
28-/**
29- * A collection of convenience {@link TypeCodec} instances useful for
30- * serializing between CQL types and Joda types like {@link DateTime}.
31- *
32- * These codecs may either be registered individually or they may all
33- * be registered via {@link JodaCodecs#withCodecs(CodecRegistry)}.
34- */
35-public class JodaCodecs {
36-
37- /**
38- * <p>
39- * Registers all defined {@link TypeCodec} instances in this class
40- * (with exception to {@link TimeZonePreservingDateTimeCodec}) with
41- * the given {@link CodecRegistry}.
42- * </p>
43- * @param registry registry to add Codecs to.
44- * @return updated registry with codecs.
45- */
46- public static CodecRegistry withCodecs(CodecRegistry registry) {
47- return registry.register(LocalTimeCodec.instance, LocalDateCodec.instance, DateTimeCodec.instance);
48- }
49-
50- /**
51- * {@link TypeCodec} that maps {@link LocalTime} <-> Long representing nanoseconds since midnight
52- * allowing the setting and retrieval of <code>time</code> columns as {@link LocalTime}
53- * instances.
54- *
55- * IMPORTANT: {@link LocalTime} as millisecond precision; nanoseconds below one millisecond will be lost
56- * during deserialization.
57- */
58- public static class LocalTimeCodec extends MappingCodec<LocalTime, Long> {
59-
60- public static final LocalTimeCodec instance = new LocalTimeCodec();
61-
62- private LocalTimeCodec() {
63- super(TypeCodec.time(), LocalTime.class);
64- }
65-
66- @Override
67- protected LocalTime deserialize(Long value) {
68- if (value == null)
69- return null;
70- return LocalTime.fromMillisOfDay(TimeUnit.NANOSECONDS.toMillis(value));
71- }
72-
73- @Override
74- protected Long serialize(LocalTime value) {
75- if (value == null)
76- return null;
77- return TimeUnit.MILLISECONDS.toNanos(value.getMillisOfDay());
78- }
79- }
80-
81- /**
82- * {@link TypeCodec} that maps
83- * {@link org.joda.time.LocalDate} <-> {@link LocalDate} allowing the
84- * setting and retrieval of <code>date</code> columns as
85- * {@link org.joda.time.LocalDate} instances.
86- */
87- public static class LocalDateCodec extends MappingCodec<org.joda.time.LocalDate, LocalDate> {
88-
89- public static final LocalDateCodec instance = new LocalDateCodec();
90-
91- private LocalDateCodec() {
92- super(TypeCodec.date(), org.joda.time.LocalDate.class);
93- }
94-
95- @Override
96- protected org.joda.time.LocalDate deserialize(LocalDate value) {
97- return value == null ? null : new org.joda.time.LocalDate(value.getYear(), value.getMonth(), value.getDay());
98- }
99-
100- @Override
101- protected LocalDate serialize(org.joda.time.LocalDate value) {
102- return value == null ? null : LocalDate.fromYearMonthDay(value.getYear(), value.getMonthOfYear(), value.getDayOfMonth());
103- }
104- }
105-
106- /**
107- * <p>
108- * {@link TypeCodec} that maps {@link DateTime} <-> {@link Date}
109- * allowing the setting and retrieval of <code>timestamp</code>
110- * columns as {@link DateTime} instances.
111- * </p>
112- *
113- * <p>
114- * Since C* <code>timestamp</code> columns do not preserve timezones
115- * any attached timezone information will be lost.
116- * </p>
117- *
118- * @see TimeZonePreservingDateTimeCodec
119- */
120- public static class DateTimeCodec extends MappingCodec<DateTime, Date> {
121-
122- public static final DateTimeCodec instance = new DateTimeCodec();
123-
124- private DateTimeCodec() {
125- super(TypeCodec.timestamp(), DateTime.class);
126- }
127-
128- @Override
129- protected DateTime deserialize(Date value) {
130- return new DateTime(value);
131- }
132-
133- @Override
134- protected Date serialize(DateTime value) {
135- return value.toDate();
136- }
137- }
138-
139- /**
140- * <p>
141- * {@link TypeCodec} that maps
142- * {@link LocalTime} <-> <code>tuple&lt;timestamp,varchar&gt;</code>
143- * providing a pattern for maintaining timezone information in
144- * cassandra.
145- * </p>
146- *
147- * <p>
148- * Since cassandra's <code>timestamp</code> type preserves only
149- * milliseconds since epoch, any timezone information passed in with
150- * a {@link Date} instance would normally be lost. By using a
151- * <code>tuple&lt;timestamp,varchar&gt;</code> a timezone ID can be
152- * persisted in the <code>varchar</code> field such that when the
153- * value is deserialized into a {@link DateTime} the timezone is
154- * preserved.
155- * </p>
156- *
157- */
158- public static class TimeZonePreservingDateTimeCodec extends MappingCodec<DateTime, TupleValue> {
159-
160- private final TupleType tupleType;
161-
162- public TimeZonePreservingDateTimeCodec(TypeCodec<TupleValue> innerCodec) {
163- super(innerCodec, DateTime.class);
164- tupleType = (TupleType)innerCodec.getCqlType();
165- List<DataType> types = tupleType.getComponentTypes();
166- checkArgument(
167- types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()),
168- "Expected tuple<timestamp,varchar>, got %s",
169- tupleType);
170- }
171-
172- @Override
173- protected DateTime deserialize(TupleValue value) {
174- Date date = value.getTimestamp(0);
175- String zoneID = value.getString(1);
176- return new DateTime(date).withZone(DateTimeZone.forID(zoneID));
177- }
178-
179- @Override
180- protected TupleValue serialize(DateTime value) {
181- TupleValue tupleValue = new TupleValue(tupleType);
182- tupleValue.setTimestamp(0, value.toDate());
183- tupleValue.setString(1, value.getZone().getID());
184- return tupleValue;
185- }
186- }
187-
188-}
deleted driver-core/src/test/java/com/datastax/driver/core/JsonCodec.java +0 −95
@@ -1,95 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.io.IOException;
19-import java.nio.ByteBuffer;
20-
21-import com.fasterxml.jackson.core.JsonProcessingException;
22-import com.fasterxml.jackson.databind.JavaType;
23-import com.fasterxml.jackson.databind.ObjectMapper;
24-import com.fasterxml.jackson.databind.type.TypeFactory;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-import com.datastax.driver.core.utils.Bytes;
28-
29-/**
30- * A simple Json codec for TypeCodec tests that uses Jackson to perform serialization and deserialization.
31- */
32-public class JsonCodec<T> extends TypeCodec<T> {
33-
34- private final ObjectMapper objectMapper = new ObjectMapper();
35-
36- public JsonCodec(Class<T> javaType) {
37- super(DataType.varchar(), javaType);
38- }
39-
40- @Override
41- public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
42- if (value == null)
43- return null;
44- try {
45- return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
46- } catch (JsonProcessingException e) {
47- throw new InvalidTypeException(e.getMessage(), e);
48- }
49- }
50-
51- @Override
52- @SuppressWarnings("unchecked")
53- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
54- if (bytes == null)
55- return null;
56- try {
57- return (T)objectMapper.readValue(Bytes.getArray(bytes), toJacksonJavaType());
58- } catch (IOException e) {
59- throw new InvalidTypeException(e.getMessage(), e);
60- }
61- }
62-
63- @Override
64- public String format(T value) throws InvalidTypeException {
65- if (value == null)
66- return "NULL";
67- String json;
68- try {
69- json = objectMapper.writeValueAsString(value);
70- } catch (IOException e) {
71- throw new InvalidTypeException(e.getMessage(), e);
72- }
73- return '\'' + json.replace("\'", "''") + '\'';
74- }
75-
76- @Override
77- @SuppressWarnings("unchecked")
78- public T parse(String value) throws InvalidTypeException {
79- if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
80- return null;
81- if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
82- throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
83- String json = value.substring(1, value.length() - 1).replace("''", "'");
84- try {
85- return (T)objectMapper.readValue(json, toJacksonJavaType());
86- } catch (IOException e) {
87- throw new InvalidTypeException(e.getMessage(), e);
88- }
89- }
90-
91- protected JavaType toJacksonJavaType() {
92- return TypeFactory.defaultInstance().constructType(getJavaType().getType());
93- }
94-
95-}
modified driver-core/src/test/java/com/datastax/driver/core/MappingCodec.java +14 −16
@@ -19,51 +19,49 @@
1919
2020 import com.google.common.reflect.TypeToken;
2121
22+import com.datastax.driver.core.ProtocolVersion;
23+import com.datastax.driver.core.TypeCodec;
2224 import com.datastax.driver.core.exceptions.InvalidTypeException;
2325
2426 /**
25- * An abstract TypeCodec that maps a Java Pojo to another Java object
26- * that can in turn be serialized into a CQL type.
27- * This can serve as a base for libraries dealing with Pojo mappings.
28- *
29- * @param <T> The outer Java type
30- * @param <U> The inner Java type
27+ * This class is a copy of MappingCodec declared in the extras module,
28+ * to avoid circular dependencies between Maven modules.
3129 */
32-public abstract class MappingCodec<T, U> extends TypeCodec<T> {
30+public abstract class MappingCodec<O, I> extends TypeCodec<O> {
3331
34- protected final TypeCodec<U> innerCodec;
32+ protected final TypeCodec<I> innerCodec;
3533
36- public MappingCodec(TypeCodec<U> innerCodec, Class<T> javaType) {
34+ public MappingCodec(TypeCodec<I> innerCodec, Class<O> javaType) {
3735 this(innerCodec, TypeToken.of(javaType));
3836 }
3937
40- public MappingCodec(TypeCodec<U> innerCodec, TypeToken<T> javaType) {
38+ public MappingCodec(TypeCodec<I> innerCodec, TypeToken<O> javaType) {
4139 super(innerCodec.getCqlType(), javaType);
4240 this.innerCodec = innerCodec;
4341 }
4442
4543 @Override
46- public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
44+ public ByteBuffer serialize(O value, ProtocolVersion protocolVersion) throws InvalidTypeException {
4745 return innerCodec.serialize(serialize(value), protocolVersion);
4846 }
4947
5048 @Override
51- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
49+ public O deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
5250 return deserialize(innerCodec.deserialize(bytes, protocolVersion));
5351 }
5452
5553 @Override
56- public T parse(String value) throws InvalidTypeException {
54+ public O parse(String value) throws InvalidTypeException {
5755 return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : deserialize(innerCodec.parse(value));
5856 }
5957
6058 @Override
61- public String format(T value) throws InvalidTypeException {
59+ public String format(O value) throws InvalidTypeException {
6260 return value == null ? null : innerCodec.format(serialize(value));
6361 }
6462
65- protected abstract T deserialize(U value);
63+ protected abstract O deserialize(I value);
6664
67- protected abstract U serialize(T value);
65+ protected abstract I serialize(O value);
6866
6967 }
deleted driver-core/src/test/java/com/datastax/driver/core/OptionalCodec.java +0 −72
@@ -1,72 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.util.Collection;
19-import java.util.Map;
20-
21-import com.google.common.base.Optional;
22-import com.google.common.base.Predicate;
23-import com.google.common.reflect.TypeParameter;
24-import com.google.common.reflect.TypeToken;
25-
26-import static com.google.common.base.Predicates.isNull;
27-import static com.google.common.base.Predicates.or;
28-
29-public class OptionalCodec<T> extends MappingCodec<Optional<T>, T> {
30-
31- private final Predicate<T> isAbsent;
32-
33- @SuppressWarnings("unchecked")
34- public OptionalCodec(TypeCodec<T> codec) {
35- this(codec, (Predicate<T>) isAbsent());
36- }
37-
38- private static <T> Predicate<T> isAbsent() {
39- return or(isNull(), new Predicate<T>() {
40- @Override
41- public boolean apply(T input) {
42- return (input instanceof Collection && ((Collection)input).isEmpty()) ||
43- (input instanceof Map && ((Map)input).isEmpty());
44- }
45- });
46- }
47-
48- public OptionalCodec(TypeCodec<T> codec, Predicate<T> isAbsent) {
49- super(codec, new TypeToken<Optional<T>>(){}.where(new TypeParameter<T>(){}, codec.getJavaType()));
50- this.isAbsent = isAbsent;
51- }
52-
53- @Override
54- protected Optional<T> deserialize(T value) {
55- return isAbsent(value) ? Optional.<T>absent() : Optional.of(value);
56- }
57-
58- @Override
59- protected T serialize(Optional<T> value) {
60- return value.isPresent() ? value.get() : absentValue();
61- }
62-
63- protected T absentValue() {
64- return null;
65- }
66-
67- protected boolean isAbsent(T value) {
68- return isAbsent.apply(value);
69- }
70-
71-
72-}
deleted driver-core/src/test/java/com/datastax/driver/core/StringParsingCodec.java +0 −94
@@ -1,94 +0,0 @@
1-package com.datastax.driver.core;
2-
3-import java.nio.ByteBuffer;
4-
5-import com.google.common.reflect.TypeToken;
6-
7-/*
8- * Copyright (C) 2012-2015 DataStax Inc.
9- *
10- * Licensed under the Apache License, Version 2.0 (the "License");
11- * you may not use this file except in compliance with the License.
12- * You may obtain a copy of the License at
13- *
14- * http://www.apache.org/licenses/LICENSE-2.0
15- *
16- * Unless required by applicable law or agreed to in writing, software
17- * distributed under the License is distributed on an "AS IS" BASIS,
18- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19- * See the License for the specific language governing permissions and
20- * limitations under the License.
21- */
22-import com.datastax.driver.core.exceptions.InvalidTypeException;
23-
24-/**
25- * An abstract TypeCodec that actually stores objects as serialized strings.
26- * This can serve as a base for codecs dealing with XML or JSON formats.
27- *
28- * @param <T> The Java type this codec serializes from and deserializes to.
29- */
30-public abstract class StringParsingCodec<T> extends TypeCodec<T> {
31-
32- private final TypeCodec<String> innerCodec;
33-
34- public StringParsingCodec(Class<T> javaType) {
35- this(TypeToken.of(javaType));
36- }
37-
38- public StringParsingCodec(TypeToken<T> javaType) {
39- this(TypeCodec.varchar(), javaType);
40- }
41-
42- public StringParsingCodec(TypeCodec<String> innerCodec, Class<T> javaType) {
43- this(innerCodec, TypeToken.of(javaType));
44- }
45-
46- public StringParsingCodec(TypeCodec<String> innerCodec, TypeToken<T> javaType) {
47- super(innerCodec.getCqlType(), javaType);
48- this.innerCodec = innerCodec;
49- }
50-
51- @Override
52- public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
53- return value == null ? null : innerCodec.serialize(toString(value), protocolVersion);
54- }
55-
56- @Override
57- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
58- String value = innerCodec.deserialize(bytes, protocolVersion);
59- return value == null ? null : fromString(value);
60- }
61-
62- @Override
63- public String format(T value) throws InvalidTypeException {
64- return value == null ? null : innerCodec.format(toString(value));
65- }
66-
67- @Override
68- public T parse(String value) throws InvalidTypeException {
69- return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : fromString(innerCodec.parse(value));
70- }
71-
72- /**
73- * Return the String representation of the given object;
74- * no special CQL quoting should be applied here.
75- * Null values should be accepted; in most cases, implementors
76- * should return null for null inputs.
77- *
78- * @param value the value to convert into a string
79- * @return the String representation of the given object
80- */
81- protected abstract String toString(T value);
82-
83- /**
84- * Parse the given string into an object;
85- * no special CQL unquoting should be applied here.
86- * Null values should be accepted; in most cases, implementors
87- * should return null for null inputs.
88- *
89- * @param value the string to parse
90- * @return the parsed object.
91- */
92- protected abstract T fromString(String value);
93-
94-}
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +1 −1
@@ -55,7 +55,7 @@
5555 assertEquals(v.getString(1), "a");
5656 assertEquals(v.getFloat(2), 1.0f);
5757
58- assertEquals(TypeCodec.tuple(t).format(v), "(1, 'a', 1.0)");
58+ assertEquals(TypeCodec.tuple(t).format(v), "(1,'a',1.0)");
5959 }
6060
6161 @Test(groups = "short")
deleted driver-core/src/test/java/com/datastax/driver/core/TypeCodecArraysIntegrationTest.java +0 −233
@@ -1,233 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.nio.ByteBuffer;
19-import java.util.Collection;
20-import java.util.List;
21-
22-import com.google.common.collect.Lists;
23-import com.google.common.primitives.Ints;
24-import org.testng.annotations.Test;
25-
26-import static com.google.common.base.Preconditions.checkArgument;
27-import static org.assertj.core.api.Assertions.assertThat;
28-
29-import com.datastax.driver.core.exceptions.InvalidTypeException;
30-
31-/**
32- * Demonstrates how to write custom codecs for high-performance deserialization of CQL collections to primitive arrays.
33- */
34-public class TypeCodecArraysIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35-
36- @Override
37- protected Collection<String> getTableDefinitions() {
38- return Lists.newArrayList(
39- "CREATE TABLE lists(i int PRIMARY KEY, l list<int>)",
40- "INSERT INTO lists (i, l) VALUES (1, [1, 2, 3])"
41- );
42- }
43-
44- @Override
45- protected Cluster.Builder configure(Cluster.Builder builder) {
46- return builder.withCodecRegistry(
47- new CodecRegistry().register(new IntArrayCodec())
48- );
49- }
50-
51- @Test(groups = "short")
52- public void should_read_list_column_as_array() {
53- Row row = session.execute("SELECT l FROM lists WHERE i = 1").one();
54-
55- int[] ints = row.get("l", int[].class);
56-
57- assertThat(ints).containsExactly(1, 2, 3);
58- }
59-
60- @Test(groups = "short")
61- public void should_set_list_column_with_array() {
62- PreparedStatement pst = session.prepare("INSERT INTO lists (i, l) VALUES (?, ?)");
63- BoundStatement bs = pst.bind()
64- .setInt(0, 2)
65- .set(1, new int[]{ 2, 3, 4 }, int[].class);
66- session.execute(bs);
67-
68- Row row = session.execute("SELECT l FROM lists WHERE i = 2").one();
69- assertThat(row.getList("l", Integer.class)).containsExactly(2, 3, 4);
70- }
71-
72- @Test(groups = "short")
73- public void should_format_array_as_cql_literal() {
74- IntArrayCodec codec = new IntArrayCodec();
75-
76- assertThat(codec.format(new int[]{ 1, 2, 3 }))
77- .isEqualTo("[1,2,3]");
78- assertThat(codec.format(new int[0]))
79- .isEqualTo("[]");
80- assertThat(codec.format(null))
81- .isEqualTo("null");
82- }
83-
84- @Test(groups = "short")
85- public void should_parse_array_from_cql_literal() {
86- IntArrayCodec codec = new IntArrayCodec();
87-
88- assertThat(codec.parse("[1,2,3]"))
89- .containsExactly(1, 2, 3);
90- assertThat(codec.parse("null"))
91- .isNull();
92- assertThat(codec.parse(""))
93- .isNull();
94- assertThat(codec.parse(null))
95- .isNull();
96- }
97-
98- public static class IntArrayCodec extends TypeCodec<int[]> {
99-
100- private static final int SIZE_OF_INT = 4;
101-
102- public IntArrayCodec() {
103- super(DataType.list(DataType.cint()), int[].class);
104- }
105-
106- @Override
107- public ByteBuffer serialize(int[] ints, ProtocolVersion protocolVersion) throws InvalidTypeException {
108- if (ints == null)
109- return null;
110-
111- boolean isProtocolV3OrAbove = protocolVersion.compareTo(ProtocolVersion.V2) > 0;
112-
113- checkArgument(isProtocolV3OrAbove || ints.length < 65536,
114- "Native protocol version %d supports up to 65535 elements in any collection - but collection contains %d elements",
115- protocolVersion.toInt(), ints.length);
116-
117- /*
118- * Encoding of lists in the native protocol:
119- * [size of list] [size of element 1][element1] [size of element 2][element2]...
120- * Sizes are encoded on 2 bytes in protocol v1 and v2, 4 bytes otherwise.
121- * Integers are always encoded on 4 bytes.
122- * (See native_protocol_v*.spec in https://github.com/apache/cassandra/blob/trunk/doc/)
123- */
124-
125- // Number of bytes to encode sizes
126- int sizeOfSize = isProtocolV3OrAbove ? 4 : 2;
127-
128- // Number of bytes to encode each element (preceded by its size)
129- int sizeOfElement = sizeOfSize + SIZE_OF_INT;
130-
131- // Number of bytes to encode the whole collection (size of collection + all elements)
132- int totalSize = sizeOfSize + ints.length * sizeOfElement;
133-
134- ByteBuffer output = ByteBuffer.allocate(totalSize);
135-
136- writeSize(output, ints.length, protocolVersion);
137- for (int i : ints) {
138- writeSize(output, SIZE_OF_INT, protocolVersion);
139- output.putInt(i);
140- }
141- output.flip();
142- return output;
143- }
144-
145- @Override
146- public int[] deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
147- if (bytes == null || bytes.remaining() == 0)
148- return new int[0];
149-
150- boolean isProtocolV3OrAbove = protocolVersion.compareTo(ProtocolVersion.V2) > 0;
151- int sizeOfSize = isProtocolV3OrAbove ? 4 : 2;
152-
153- ByteBuffer input = bytes.duplicate();
154-
155- int size = CodecUtils.readCollectionSize(input, protocolVersion);
156- int[] ints = new int[size];
157- for (int i = 0; i < size; i++) {
158- // Skip size (we know it will always be 4 since the elements are ints)
159- input.position(input.position() + sizeOfSize);
160- ints[i] = input.getInt();
161- }
162- return ints;
163- }
164-
165- @Override
166- public String format(int[] ints) throws InvalidTypeException {
167- if (ints == null)
168- return "null";
169-
170- StringBuilder sb = new StringBuilder();
171- sb.append('[');
172- for (int i = 0; i < ints.length; i++) {
173- if (i != 0)
174- sb.append(",");
175- sb.append(ints[i]);
176- }
177- sb.append(']');
178- return sb.toString();
179- }
180-
181- @Override
182- public int[] parse(String value) throws InvalidTypeException {
183- if (value == null || value.isEmpty() || value.equals("null"))
184- return null;
185-
186- int idx = ParseUtils.skipSpaces(value, 0);
187- if (value.charAt(idx++) != '[')
188- throw new InvalidTypeException(String.format("cannot parse list value from \"%s\", at character %d expecting '[' but got '%c'", value, idx, value.charAt(idx)));
189-
190- idx = ParseUtils.skipSpaces(value, idx);
191-
192- if (value.charAt(idx) == ']')
193- return new int[0];
194-
195- List<Integer> l = Lists.newArrayList();
196- while (idx < value.length()) {
197- int n;
198- try {
199- n = ParseUtils.skipCQLValue(value, idx);
200- } catch (IllegalArgumentException e) {
201- throw new InvalidTypeException(String.format("Cannot parse list value from \"%s\", invalid CQL value at character %d", value, idx), e);
202- }
203-
204- l.add(Integer.parseInt(value.substring(idx, n)));
205- idx = n;
206-
207- idx = ParseUtils.skipSpaces(value, idx);
208- if (value.charAt(idx) == ']')
209- return Ints.toArray(l);
210- if (value.charAt(idx++) != ',')
211- throw new InvalidTypeException(String.format("Cannot parse list value from \"%s\", at character %d expecting ',' but got '%c'", value, idx, value.charAt(idx)));
212-
213- idx = ParseUtils.skipSpaces(value, idx);
214- }
215- throw new InvalidTypeException(String.format("Malformed list value \"%s\", missing closing ']'", value));
216- }
217-
218- private void writeSize(ByteBuffer output, int size, ProtocolVersion protocolVersion) {
219- switch (protocolVersion) {
220- case V1:
221- case V2:
222- output.putShort((short)size);
223- break;
224- case V3:
225- case V4:
226- output.putInt(size);
227- break;
228- default:
229- throw protocolVersion.unsupported();
230- }
231- }
232- }
233-}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecAssert.java +5 −1
@@ -75,7 +75,11 @@
7575 @SuppressWarnings("unchecked")
7676 public TypeCodecAssert canSerialize(Object value) {
7777 if(version == null) fail("ProtocolVersion cannot be null");
78- assertThat(actual.deserialize(actual.serialize(value, version), version)).isEqualTo(value);
78+ try {
79+ assertThat(actual.deserialize(actual.serialize(value, version), version)).isEqualTo(value);
80+ } catch (Exception e) {
81+ fail(String.format("Codec is supposed to serialize this value but it actually doesn't: %s", value), e);
82+ }
7983 return this;
8084 }
8185
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java +21 −21
@@ -35,9 +35,9 @@
3535
3636 import com.datastax.driver.core.querybuilder.BuiltStatement;
3737
38-import static com.datastax.driver.core.CodecUtils.listOf;
39-import static com.datastax.driver.core.CodecUtils.mapOf;
40-import static com.datastax.driver.core.CodecUtils.setOf;
38+import static com.datastax.driver.core.TypeTokens.listOf;
39+import static com.datastax.driver.core.TypeTokens.mapOf;
40+import static com.datastax.driver.core.TypeTokens.setOf;
4141 import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
4242 import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
4343
@@ -128,12 +128,12 @@
128128 public void should_use_collection_codecs_with_prepared_statements_3() {
129129 session.execute(session.prepare(insertQuery).bind()
130130 .setInt(0, n_int)
131- .set(1, l_int, listOf(Integer.class))
132- .set(2, l_bigint, listOf(Long.class))
133- .set(3, s_float, setOf(Float.class))
134- .set(4, s_double, setOf(Double.class))
135- .set(5, m_varint, mapOf(Integer.class, BigInteger.class))
136- .set(6, m_decimal, mapOf(Integer.class, BigDecimal.class))
131+ .set(1, l_int, TypeTokens.listOf(Integer.class))
132+ .set(2, l_bigint, TypeTokens.listOf(Long.class))
133+ .set(3, s_float, TypeTokens.setOf(Float.class))
134+ .set(4, s_double, TypeTokens.setOf(Double.class))
135+ .set(5, m_varint, TypeTokens.mapOf(Integer.class, BigInteger.class))
136+ .set(6, m_decimal, TypeTokens.mapOf(Integer.class, BigDecimal.class))
137137 );
138138 PreparedStatement ps = session.prepare(selectQuery);
139139 ResultSet rows = session.execute(ps.bind()
@@ -147,12 +147,12 @@
147147 public void should_use_collection_codecs_with_built_statements() {
148148 session.execute(session.prepare(insertStmt).bind()
149149 .setInt(0, n_int)
150- .set(1, l_int, listOf(Integer.class))
151- .set(2, l_bigint, listOf(Long.class))
152- .set(3, s_float, setOf(Float.class))
153- .set(4, s_double, setOf(Double.class))
154- .set(5, m_varint, mapOf(Integer.class, BigInteger.class))
155- .set(6, m_decimal, mapOf(Integer.class, BigDecimal.class))
150+ .set(1, l_int, TypeTokens.listOf(Integer.class))
151+ .set(2, l_bigint, TypeTokens.listOf(Long.class))
152+ .set(3, s_float, TypeTokens.setOf(Float.class))
153+ .set(4, s_double, TypeTokens.setOf(Double.class))
154+ .set(5, m_varint, TypeTokens.mapOf(Integer.class, BigInteger.class))
155+ .set(6, m_decimal, TypeTokens.mapOf(Integer.class, BigDecimal.class))
156156 );
157157 PreparedStatement ps = session.prepare(selectStmt);
158158 ResultSet rows = session.execute(ps.bind()
@@ -170,12 +170,12 @@
170170 assertThat(row.getMap(5, Integer.class, BigInteger.class)).isEqualTo(m_varint);
171171 assertThat(row.getMap(6, Integer.class, BigDecimal.class)).isEqualTo(m_decimal);
172172 // with get + type
173- assertThat(row.get(1, listOf(Integer.class))).isEqualTo(l_int);
174- assertThat(row.get(2, listOf(Long.class))).isEqualTo(l_bigint);
175- assertThat(row.get(3, setOf(Float.class))).isEqualTo(s_float);
176- assertThat(row.get(4, setOf(Double.class))).isEqualTo(s_double);
177- assertThat(row.get(5, mapOf(Integer.class, BigInteger.class))).isEqualTo(m_varint);
178- assertThat(row.get(6, mapOf(Integer.class, BigDecimal.class))).isEqualTo(m_decimal);
173+ assertThat(row.get(1, TypeTokens.listOf(Integer.class))).isEqualTo(l_int);
174+ assertThat(row.get(2, TypeTokens.listOf(Long.class))).isEqualTo(l_bigint);
175+ assertThat(row.get(3, TypeTokens.setOf(Float.class))).isEqualTo(s_float);
176+ assertThat(row.get(4, TypeTokens.setOf(Double.class))).isEqualTo(s_double);
177+ assertThat(row.get(5, TypeTokens.mapOf(Integer.class, BigInteger.class))).isEqualTo(m_varint);
178+ assertThat(row.get(6, TypeTokens.mapOf(Integer.class, BigDecimal.class))).isEqualTo(m_decimal);
179179 // with getObject
180180 assertThat(row.getObject(1)).isEqualTo(l_int);
181181 assertThat(row.getObject(2)).isEqualTo(l_bigint);
deleted driver-core/src/test/java/com/datastax/driver/core/TypeCodecEnumIntegrationTest.java +0 −198
@@ -1,198 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.util.Collection;
19-import java.util.List;
20-import java.util.Map;
21-import java.util.Set;
22-
23-import com.google.common.collect.ImmutableMap;
24-import com.google.common.reflect.TypeToken;
25-import org.testng.annotations.BeforeMethod;
26-import org.testng.annotations.Test;
27-
28-import static com.google.common.collect.Lists.newArrayList;
29-import static com.google.common.collect.Sets.newHashSet;
30-import static org.assertj.core.api.Assertions.assertThat;
31-
32-import com.datastax.driver.core.utils.CassandraVersion;
33-
34-import static com.datastax.driver.core.DataType.cint;
35-import static com.datastax.driver.core.DataType.text;
36-import static com.datastax.driver.core.TypeCodecEnumIntegrationTest.Foo.*;
37-import static com.datastax.driver.core.TypeCodecEnumIntegrationTest.Bar.*;
38-
39-/**
40- * A test that validates that Enums are correctly mapped to varchars (with the default EnumStringCodec)
41- * or alternatively to ints (with the alternative EnumIntCodec).
42- * It also validates that both codecs may coexist in the same CodecRegistry.
43- */
44-@CassandraVersion(major=2.1)
45-public class TypeCodecEnumIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
46-
47- private final String insertQuery = "INSERT INTO \"myTable\" (pk, foo, foos, bar, bars, foobars, tup, udt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
48-
49- private final String selectQuery = "SELECT pk, foo, foos, bar, bars, foobars, tup, udt FROM \"myTable\" WHERE pk = ?";
50-
51- private final int pk = 42;
52-
53- private final List<Foo> foos = newArrayList(FOO_1, FOO_2);
54- private final Set<Bar> bars = newHashSet(BAR_1, BAR_2);
55- private final Map<Foo, Bar> foobars = ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2);
56-
57- private TupleValue tupleValue;
58- private UDTValue udtValue;
59-
60- @Override
61- protected Collection<String> getTableDefinitions() {
62- return newArrayList(
63- "CREATE TYPE IF NOT EXISTS \"myType\" ("
64- + "foo int,"
65- + "bar text)",
66- "CREATE TABLE IF NOT EXISTS \"myTable\" ("
67- + "pk int PRIMARY KEY, "
68- + "foo int, "
69- + "foos list<int>, "
70- + "bar text, "
71- + "bars set<text>, "
72- + "foobars map<int,text>, "
73- + "tup frozen<tuple<int,varchar>>, "
74- + "udt frozen<\"myType\">"
75- + ")"
76- );
77- }
78-
79- @Override
80- protected Cluster.Builder configure(Cluster.Builder builder) {
81- return builder.withCodecRegistry(
82- new CodecRegistry()
83- .register(new EnumIntCodec<Foo>(Foo.class))
84- .register(new EnumStringCodec<Bar>(Bar.class))
85- );
86- }
87-
88- @BeforeMethod(groups="short")
89- public void before() {
90- TupleType tup = cluster.getMetadata().newTupleType(cint(), text());
91- tupleValue = tup.newValue()
92- .set(0, FOO_1, Foo.class)
93- .set(1, BAR_1, Bar.class);
94- UserType udt = cluster.getMetadata().getKeyspace(keyspace).getUserType("\"myType\"");
95- udtValue = udt.newValue()
96- .set("foo", FOO_1, Foo.class)
97- .set("bar", BAR_1, Bar.class);
98- }
99-
100- @Test(groups = "short")
101- public void should_use_enum_codecs_with_simple_statements() {
102- session.execute(insertQuery, pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue);
103- ResultSet rows = session.execute(selectQuery, pk);
104- Row row = rows.one();
105- assertRow(row);
106- }
107-
108- @Test(groups = "short")
109- public void should_use_enum_codecs_with_prepared_statements_1() {
110- session.execute(session.prepare(insertQuery).bind(pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue));
111- PreparedStatement ps = session.prepare(selectQuery);
112- ResultSet rows = session.execute(ps.bind(pk));
113- Row row = rows.one();
114- assertRow(row);
115- }
116-
117- @Test(groups = "short")
118- public void should_use_enum_codecs_with_prepared_statements_2() {
119- session.execute(session.prepare(insertQuery).bind()
120- .setInt(0, pk)
121- .set(1, FOO_1, Foo.class)
122- .setList(2, foos, Foo.class)
123- .set(3, BAR_1, Bar.class)
124- .set(4, bars, new TypeToken<Set<Bar>>(){})
125- .setMap(5, foobars, Foo.class, Bar.class)
126- .setTupleValue(6, tupleValue)
127- .setUDTValue(7, udtValue)
128- );
129- PreparedStatement ps = session.prepare(selectQuery);
130- ResultSet rows = session.execute(ps.bind()
131- .setInt(0, pk)
132- );
133- Row row = rows.one();
134- assertRow(row);
135- }
136-
137- private void assertRow(Row row) {
138-
139- assertThat(row.getInt(0)).isEqualTo(pk);
140-
141- assertThat(row.getObject(1)).isEqualTo(FOO_1.ordinal()); // uses the built-in IntCodec because CQL type is int
142- assertThat(row.getInt("foo")).isEqualTo(FOO_1.ordinal()); // uses the built-in IntCodec
143- assertThat(row.get(1, Integer.class)).isEqualTo(FOO_1.ordinal()); // forces IntCodec
144- assertThat(row.get("foo", Foo.class)).isEqualTo(FOO_1); // forces EnumIntCodec
145-
146- assertThat(row.getObject(2)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal())); // uses the built-in ListCodec(IntCodec) because CQL type is list<int>
147- assertThat(row.getList(2, Integer.class)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal()));
148- assertThat(row.getList("foos", Foo.class)).isEqualTo(newArrayList(FOO_1, FOO_2));
149- assertThat(row.get(2, new TypeToken<List<Integer>>(){})).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal()));
150- assertThat(row.get("foos", new TypeToken<List<Foo>>(){})).isEqualTo(newArrayList(FOO_1, FOO_2));
151-
152- assertThat(row.getObject(3)).isEqualTo(BAR_1.name()); // uses the built-in VarcharCodec because CQL type is varchar
153- assertThat(row.getString("bar")).isEqualTo(BAR_1.name()); // forces VarcharCodec
154- assertThat(row.get(3, String.class)).isEqualTo(BAR_1.name()); // forces VarcharCodec
155- assertThat(row.get("bar", Bar.class)).isEqualTo(BAR_1); // forces EnumStringCodec
156-
157- assertThat(row.getObject(4)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name())); // uses the built-in SetCodec(VarcharCodec) because CQL type is set<varchar>
158- assertThat(row.getSet(4, String.class)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name()));
159- assertThat(row.getSet("bars", Bar.class)).isEqualTo(newHashSet(BAR_1, BAR_2));
160- assertThat(row.get(4, new TypeToken<Set<String>>(){})).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name()));
161- assertThat(row.get("bars", new TypeToken<Set<Bar>>(){})).isEqualTo(newHashSet(BAR_1, BAR_2));
162-
163- // uses default built-in codec MapCodec(IntCodec, VarcharCodec) because CQL type is map<int, varchar>
164- assertThat(row.getObject(5)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
165-
166- // getMap with combinations of built-in or EnumX codecs
167- assertThat(row.getMap(5, Integer.class, String.class)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
168- assertThat(row.getMap(5, Foo.class, String.class)).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name()));
169- assertThat(row.getMap(5, Integer.class, Bar.class)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2));
170- assertThat(row.getMap(5, Foo.class, Bar.class)).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2));
171-
172- // get + TypeToken with combinations of built-in or EnumX codecs
173- assertThat(row.get("foobars", new TypeToken<Map<Integer, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
174- assertThat(row.get("foobars", new TypeToken<Map<Foo, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name()));
175- assertThat(row.get("foobars", new TypeToken<Map<Integer, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2));
176- assertThat(row.get("foobars", new TypeToken<Map<Foo, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2));
177-
178- assertThat(row.getTupleValue(6).getInt(0)).isEqualTo(FOO_1.ordinal());
179- assertThat(row.get(6, TupleValue.class).get(0, Foo.class)).isEqualTo(FOO_1);
180- assertThat(row.getTupleValue("tup").getString(1)).isEqualTo(BAR_1.name());
181- assertThat(row.get("tup", TupleValue.class).get(1, Bar.class)).isEqualTo(BAR_1);
182-
183- assertThat(row.getUDTValue(7).getInt("foo")).isEqualTo(FOO_1.ordinal());
184- assertThat(row.get(7, UDTValue.class).get("foo", Foo.class)).isEqualTo(FOO_1);
185- assertThat(row.getUDTValue("udt").getString("bar")).isEqualTo(BAR_1.name());
186- assertThat(row.get("udt", UDTValue.class).get("bar", Bar.class)).isEqualTo(BAR_1);
187-
188- }
189-
190- enum Foo {
191- FOO_1, FOO_2
192- }
193-
194- enum Bar {
195- BAR_1, BAR_2
196- }
197-
198-}
deleted driver-core/src/test/java/com/datastax/driver/core/TypeCodecJodaIntegrationTest.java +0 −175
@@ -1,175 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import com.datastax.driver.core.utils.CassandraVersion;
19-import org.joda.time.DateTime;
20-import org.joda.time.DateTimeZone;
21-import org.joda.time.LocalTime;
22-import org.testng.annotations.Test;
23-
24-import java.util.Collection;
25-import java.util.Collections;
26-import java.util.Date;
27-import java.util.concurrent.TimeUnit;
28-
29-import static org.assertj.core.api.Assertions.assertThat;
30-
31-import static com.datastax.driver.core.DataType.*;
32-
33-@CassandraVersion(major=2.2)
34-public class TypeCodecJodaIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35- @Override
36- protected Collection<String> getTableDefinitions() {
37- return Collections.singletonList(
38- "CREATE TABLE IF NOT EXISTS foo (c1 text PRIMARY KEY, " +
39- "cd date, ctime time, " +
40- "ctimestamp timestamp, " +
41- "ctuple tuple<timestamp,varchar>)");
42- }
43-
44- @Override
45- protected Cluster.Builder configure(Cluster.Builder builder) {
46- return builder.withCodecRegistry(JodaCodecs.withCodecs(new CodecRegistry()));
47- }
48-
49- /**
50- * <p>
51- * Validates that a <code>time</code> column can be mapped to a {@link LocalTime} by using
52- * {@link com.datastax.driver.core.JodaCodecs.LocalTimeCodec}.
53- * </p>
54- *
55- * @test_category data_types:serialization
56- * @expected_result properly maps.
57- * @jira_ticket JAVA-721
58- * @since 2.2.0
59- */
60- @Test(groups="short")
61- public void should_map_time_to_localtime() {
62- long lTime =
63- TimeUnit.HOURS.toNanos(12) +
64- TimeUnit.MINUTES.toNanos(16) +
65- TimeUnit.SECONDS.toNanos(34) +
66- TimeUnit.MILLISECONDS.toNanos(999);
67- LocalTime time = new LocalTime(12, 16, 34, 999);
68-
69- session.execute("insert into foo (c1, ctime) values (?, ?)", "should_map_time_to_localtime", time);
70-
71- ResultSet result = session.execute("select ctime from foo where c1=?", "should_map_time_to_localtime");
72-
73- assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
74-
75- Row row = result.one();
76- assertThat(row.get("ctime", LocalTime.class)).isEqualTo(time);
77- assertThat(row.getTime("ctime")).isEqualTo(lTime);
78- }
79-
80- /**
81- * <p>
82- * Validates that a <code>date</code> column can be mapped to a {@link org.joda.time.LocalDate} by using
83- * {@link com.datastax.driver.core.JodaCodecs.LocalDateCodec}.
84- * </p>
85- *
86- * @test_category data_types:serialization
87- * @expected_result properly maps.
88- * @jira_ticket JAVA-721
89- * @since 2.2.0
90- */
91- @Test(groups="short")
92- public void should_map_date_to_localdate() {
93- org.joda.time.LocalDate date = new org.joda.time.LocalDate(2015, 1, 1);
94- LocalDate lDate = LocalDate.fromYearMonthDay(2015, 1, 1);
95-
96- session.execute("insert into foo (c1, cd) values (?, ?)", "should_map_date_to_localdate", date);
97-
98- ResultSet result = session.execute("select cd from foo where c1=?", "should_map_date_to_localdate");
99-
100- assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
101-
102- Row row = result.one();
103- assertThat(row.get("cd", org.joda.time.LocalDate.class)).isEqualTo(date);
104- assertThat(row.getDate("cd")).isEqualTo(lDate);
105- }
106-
107-
108- /**
109- * <p>
110- * Validates that a <code>timestamp</code> column can be mapped to a {@link DateTime} by using
111- * {@link com.datastax.driver.core.JodaCodecs.DateTimeCodec}.
112- * </p>
113- *
114- * @test_category data_types:serialization
115- * @expected_result properly maps.
116- * @jira_ticket JAVA-721
117- * @since 2.2.0
118- */
119- @Test(groups="short")
120- public void should_map_timestamp_to_datetime() {
121- DateTime dateTime = DateTime.parse("2010-06-30T01:20+05:00");
122- Date date = dateTime.toDate();
123- DateTimeZone timeZone = dateTime.getZone();
124-
125- session.execute("insert into foo (c1, ctimestamp) values (?, ?)", "should_map_timestamp_to_datetime", dateTime);
126-
127- ResultSet result = session.execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_datetime");
128-
129- assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
130-
131- Row row = result.one();
132- // Since timezone is not preserved in timestamp type, set it.
133- DateTime rDateTime = row.get("ctimestamp", DateTime.class).withZone(timeZone);
134- assertThat(rDateTime).isEqualTo(dateTime);
135- assertThat(row.getTimestamp("ctimestamp")).isEqualTo(date);
136- }
137-
138-
139- /**
140- * <p>
141- * Validates that a <code>tuple&lt;timestamp,text&gt;</code> column can be mapped to a {@link DateTime} by using
142- * {@link com.datastax.driver.core.JodaCodecs.TimeZonePreservingDateTimeCodec}.
143- * </p>
144- *
145- * @test_category data_types:serialization
146- * @expected_result properly maps.
147- * @jira_ticket JAVA-721
148- * @since 2.2.0
149- */
150- @Test(groups="short")
151- public void should_map_tuple_to_datetime() {
152- // Register codec that maps DateTime <-> tuple<timestamp,varchar>
153- TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
154- JodaCodecs.TimeZonePreservingDateTimeCodec dateTimeCodec = new JodaCodecs.TimeZonePreservingDateTimeCodec(TypeCodec.tuple(dateWithTimeZoneType));
155- cluster.getConfiguration().getCodecRegistry().register(dateTimeCodec);
156-
157- DateTime dateTime = DateTime.parse("2010-06-30T01:20+05:30");
158- DateTimeZone timeZone = dateTime.getZone();
159-
160- PreparedStatement insertStmt = session.prepare("insert into foo (c1, ctuple) values (?, ?)");
161- session.execute(insertStmt.bind("should_map_tuple_to_datetime", dateTime));
162-
163- ResultSet result = session.execute("select ctuple from foo where c1=?", "should_map_tuple_to_datetime");
164-
165- assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
166-
167- Row row = result.one();
168- DateTime rDateTime = row.get("ctuple", DateTime.class);
169- // Since timezone is preserved in the tuple, the date times should match perfectly.
170- assertThat(rDateTime).isEqualTo(dateTime);
171- // Ensure the timezones match as well.
172- // (This is just a safety check as the previous assert would have failed otherwise).
173- assertThat(rDateTime.getZone()).isEqualTo(timeZone);
174- }
175-}
deleted driver-core/src/test/java/com/datastax/driver/core/TypeCodecJsonIntegrationTest.java +0 −154
@@ -1,154 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.util.ArrayList;
19-import java.util.Collection;
20-
21-import com.google.common.collect.Lists;
22-import org.testng.annotations.Test;
23-
24-import static org.assertj.core.api.Assertions.assertThat;
25-
26-import com.datastax.driver.core.TypeCodecTest.User;
27-import com.datastax.driver.core.querybuilder.BuiltStatement;
28-import com.datastax.driver.core.querybuilder.QueryBuilder;
29-import com.datastax.driver.core.utils.CassandraVersion;
30-
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
32-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
33-
34-public class TypeCodecJsonIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35-
36- private static final JsonCodec<User> jsonCodec = new JsonCodec<User>(User.class);
37-
38- private static final User alice = new User(1, "Alice");
39- private static final User bob = new User(2, "Bob");
40- private static final User charlie = new User(3, "Charlie");
41-
42- private static final String bobJson = "{\"id\":2,\"name\":\"Bob\"}";
43- private static final String charlieJson = "{\"id\":3,\"name\":\"Charlie\"}";
44- private static final String aliceJson = "{\"id\":1,\"name\":\"Alice\"}";
45-
46- private static final ArrayList<User> bobAndCharlie = Lists.newArrayList(bob, charlie);
47-
48- private static final String insertQuery = "INSERT INTO \"myTable\" (c1, c2, c3) VALUES (?, ?, ?)";
49- private static final String selectQuery = "SELECT c1, c2, c3 FROM \"myTable\" WHERE c1 = ? and c2 = ?";
50-
51- private static final String notAJsonString = "this text is not json";
52-
53- @Override
54- protected Collection<String> getTableDefinitions() {
55- return Lists.newArrayList(
56- "CREATE TABLE \"myTable\" (c1 text, c2 text, c3 list<text>, PRIMARY KEY (c1, c2))"
57- );
58- }
59-
60- @Override
61- protected Cluster.Builder configure(Cluster.Builder builder) {
62- return builder.withCodecRegistry(
63- new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
64- );
65- }
66-
67- @Test(groups = "short")
68- @CassandraVersion(major=2.0)
69- public void should_use_custom_codec_with_simple_statements() {
70- session.execute(insertQuery, notAJsonString, alice, bobAndCharlie);
71- ResultSet rows = session.execute(selectQuery, notAJsonString, alice);
72- Row row = rows.one();
73- assertRow(row);
74- }
75-
76- @Test(groups = "short")
77- public void should_use_custom_codec_with_built_statements_1() {
78- BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
79- .value("c1", bindMarker())
80- .value("c2", bindMarker())
81- .value("c3", bindMarker());
82- BuiltStatement selectStmt = new QueryBuilder(cluster).select("c1", "c2", "c3")
83- .from("\"myTable\"")
84- .where(eq("c1", bindMarker()))
85- .and(eq("c2", bindMarker()));
86- session.execute(session.prepare(insertStmt).bind(notAJsonString, alice, bobAndCharlie));
87- ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, alice));
88- Row row = rows.one();
89- assertRow(row);
90- }
91-
92- @Test(groups = "short")
93- public void should_use_custom_codec_with_built_statements_2() {
94- BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
95- .value("c1", notAJsonString)
96- .value("c2", alice)
97- .value("c3", bobAndCharlie);
98- BuiltStatement selectStmt =
99- new QueryBuilder(cluster).select("c1", "c2", "c3")
100- .from("\"myTable\"")
101- .where(eq("c1", notAJsonString))
102- .and(eq("c2", alice));
103- session.execute(insertStmt);
104- ResultSet rows = session.execute(selectStmt);
105- Row row = rows.one();
106- assertRow(row);
107- }
108-
109- @Test(groups = "short")
110- public void should_use_custom_codec_with_prepared_statements_1() {
111- session.execute(session.prepare(insertQuery).bind(notAJsonString, alice, bobAndCharlie));
112- PreparedStatement ps = session.prepare(selectQuery);
113- // this bind() method does not convey information about the java type of alice
114- // so the registry will look for a codec accepting varchar <-> ANY
115- // and will find jsonCodec because it is the first registered
116- ResultSet rows = session.execute(ps.bind(notAJsonString, alice));
117- Row row = rows.one();
118- assertRow(row);
119- }
120-
121- @Test(groups = "short")
122- public void should_use_custom_codec_with_prepared_statements_2() {
123- session.execute(session.prepare(insertQuery).bind()
124- .setString(0, notAJsonString)
125- .set(1, alice, User.class)
126- .setList(2, bobAndCharlie, User.class)
127- );
128- PreparedStatement ps = session.prepare(selectQuery);
129- ResultSet rows = session.execute(ps.bind()
130- .setString(0, notAJsonString)
131- // this set() method conveys information about the java type of alice
132- // so the registry will look for a codec accepting varchar <-> User
133- // and will find jsonCodec because it is the only matching one
134- .set(1, alice, User.class)
135- );
136- Row row = rows.one();
137- assertRow(row);
138- }
139-
140- private void assertRow(Row row) {
141- // getString requires a codec accepting varchar <-> String, so VarcharCodec is used
142- assertThat(row.getString(0)).isEqualTo(notAJsonString);
143- // getObject requires a codec accepting varchar <-> ANY;
144- // the first codec that accepts that is jsonCodec, so it is used
145- assertThat(row.getObject(1)).isEqualTo(aliceJson);
146- // getObject uses the default codec VarcharCodec
147- assertThat(row.get(1, User.class)).isEqualTo(alice);
148- // we still can get the column as a string using VarcharCodec.instance behind the scenes
149- assertThat(row.getString(1)).isEqualTo(aliceJson);
150- assertThat(row.getList(2, User.class)).containsExactly(bob, charlie);
151- // we still can get the column as a List<String>
152- assertThat(row.getList(2, String.class)).containsExactly(bobJson, charlieJson);
153- }
154-}
deleted driver-core/src/test/java/com/datastax/driver/core/TypeCodecOptionalIntegrationTest.java +0 −209
@@ -1,209 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import com.datastax.driver.core.querybuilder.BuiltStatement;
19-import com.datastax.driver.core.querybuilder.QueryBuilder;
20-import com.datastax.driver.core.utils.CassandraVersion;
21-import com.google.common.base.Optional;
22-import com.google.common.collect.Lists;
23-import org.testng.annotations.BeforeMethod;
24-import org.testng.annotations.Test;
25-
26-import java.math.BigDecimal;
27-import java.util.Collection;
28-import java.util.Collections;
29-import java.util.List;
30-
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
32-import static org.assertj.core.api.Assertions.assertThat;
33-
34-public class TypeCodecOptionalIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35-
36- private BuiltStatement insertStmt;
37- private BuiltStatement selectStmt;
38-
39- TypeCodec<List<String>> codec = new CodecRegistry().codecFor(DataType.list(DataType.text()));
40- OptionalCodec<List<String>> optionalCodec = new OptionalCodec<List<String>>(codec);
41- CodecRegistry registry = new CodecRegistry().register(optionalCodec);
42-
43- @Override
44- protected Collection<String> getTableDefinitions() {
45- return Collections.singletonList("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
46- }
47-
48- @Override
49- protected Cluster.Builder configure(Cluster.Builder builder) {
50- return builder.withCodecRegistry(registry);
51- }
52-
53- @BeforeMethod(groups = "short")
54- public void createBuiltStatements() throws Exception {
55- insertStmt = new QueryBuilder(cluster).insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker());
56- selectStmt = new QueryBuilder(cluster).select("c2", "c3").from("foo").where(eq("c1", bindMarker()));
57- }
58-
59- /**
60- * <p>
61- * Validates that if a column is unset, that retrieving the value using {@link OptionalCodec} should return
62- * an {@link Optional#absent()} value. Since CQL Lists can't differentiate between null and empty lists, the
63- * OptionalCodec should be smart enough to map an empty list to absent.
64- * </p>
65- *
66- * @test_category data_types:serialization
67- * @expected_result an absent value.
68- * @jira_ticket JAVA-721
69- * @since 2.2.0
70- */
71- @Test(groups="short")
72- @CassandraVersion(major=2.2)
73- public void should_map_unset_value_to_absent() {
74- PreparedStatement insertPrep = session.prepare(this.insertStmt);
75- PreparedStatement selectPrep = session.prepare(this.selectStmt);
76-
77- BoundStatement bs = insertPrep.bind();
78- bs.setString(0, "should_map_unset_value_to_absent");
79- bs.setString(1, "1");
80- session.execute(bs);
81-
82- ResultSet results = session.execute(selectPrep.bind("should_map_unset_value_to_absent"));
83- assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
84-
85- Row row = results.one();
86- assertThat(row.getString("c2")).isEqualTo("1");
87- assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.absent());
88- }
89-
90- /**
91- * <p>
92- * Validates that if a column is set to {@link Optional#absent()} using {@link OptionalCodec} that it should be
93- * stored as null and that retrieving it should return {@link Optional#absent()} using {@link OptionalCodec}.
94- * </p>
95- *
96- * @test_category data_types:serialization
97- * @expected_result an absent value.
98- * @jira_ticket JAVA-721
99- * @since 2.2.0
100- */
101- @Test(groups="short")
102- public void should_map_absent_null_value_to_absent() {
103- PreparedStatement insertPrep = session.prepare(this.insertStmt);
104- PreparedStatement selectPrep = session.prepare(this.selectStmt);
105-
106- BoundStatement bs = insertPrep.bind();
107- bs.setString(0, "should_map_absent_null_value_to_absent");
108- bs.setString(1, "1");
109- bs.set(2, Optional.<List<String>>absent(), optionalCodec.javaType);
110- session.execute(bs);
111-
112- ResultSet results = session.execute(selectPrep.bind("should_map_absent_null_value_to_absent"));
113- assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
114-
115- Row row = results.one();
116- assertThat(row.getString("c2")).isEqualTo("1");
117- assertThat(row.getList("c3", String.class)).isEmpty();
118- assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.absent());
119- }
120-
121- /**
122- * <p>
123- * Validates that if a column is set to an {@link Optional} value using {@link OptionalCodec} that it should be
124- * stored as the option's value and that retrieving it should return an {@link Optional} using {@link OptionalCodec}
125- * and its actual value without using it.
126- * </p>
127- *
128- * @test_category data_types:serialization
129- * @expected_result The options value is stored appropriately and is retrievable with and without OptionalCodec.
130- * @jira_ticket JAVA-721
131- * @since 2.2.0
132- */
133- @Test(groups="short")
134- public void should_map_some_back_to_itself() {
135- PreparedStatement insertPrep = session.prepare(this.insertStmt);
136- PreparedStatement selectPrep = session.prepare(this.selectStmt);
137-
138- List<String> data = Lists.newArrayList("1", "2", "3");
139-
140- BoundStatement bs = insertPrep.bind();
141- bs.setString(0, "should_map_some_back_to_itself");
142- bs.setString(1, "1");
143- bs.set(2, Optional.of(data), optionalCodec.javaType);
144- session.execute(bs);
145-
146- ResultSet results = session.execute(selectPrep.bind("should_map_some_back_to_itself"));
147- assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
148-
149- Row row = results.one();
150- assertThat(row.getString("c2")).isEqualTo("1");
151-
152- // Ensure data stored correctly.
153- assertThat(row.getList("c3", String.class)).isEqualTo(data);
154-
155- // Ensure data retrievable using Option codec.
156- Optional<List<String>> returnData = row.get("c3", optionalCodec.getJavaType());
157- assertThat(returnData.isPresent()).isTrue();
158- assertThat(returnData.get()).isEqualTo(data);
159- }
160-
161- @Test(groups="short")
162- public void should_map_a_primitive_type_to_absent() {
163- TypeCodec<Long> bigintCodec = registry.codecFor(DataType.bigint());
164- OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigintCodec);
165- cluster.getConfiguration().getCodecRegistry().register(optionalLongCodec);
166-
167- PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c4) values (?,?,?)");
168-
169- BoundStatement bs = stmt.bind();
170- bs.setString(0, "should_map_a_primitive_type_to_absent");
171- bs.setString(1, "1");
172- bs.set(2, Optional.<Long>absent(), optionalLongCodec.javaType);
173- session.execute(bs);
174-
175- PreparedStatement selectBigint = session.prepare("select c1, c4 from foo where c1=?");
176- ResultSet results = session.execute(selectBigint.bind("should_map_a_primitive_type_to_absent"));
177-
178- assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
179-
180- Row row = results.one();
181- assertThat(row.get("c4", optionalLongCodec.getJavaType())).isEqualTo(Optional.<Long>absent());
182- assertThat(row.getLong("c4")).isEqualTo(0L); // This will return a 0L since it returns the primitive value.
183- assertThat(row.get("c4", Long.class)).isNull();
184- }
185-
186- @Test(groups="short")
187- public void should_map_a_nullable_type_to_absent() {
188- TypeCodec<BigDecimal> decimalCodec = registry.codecFor(DataType.decimal());
189- OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimalCodec);
190- cluster.getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
191-
192- PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c5) values (?,?,?)");
193-
194- BoundStatement bs = stmt.bind();
195- bs.setString(0, "should_map_a_nullable_type_to_absent");
196- bs.setString(1, "1");
197- bs.set(2, Optional.<BigDecimal>absent(), optionalDecimalCodec.javaType);
198- session.execute(bs);
199-
200- PreparedStatement selectDecimal = session.prepare("select c1, c5 from foo where c1=?");
201- ResultSet results = session.execute(selectDecimal.bind("should_map_a_nullable_type_to_absent"));
202-
203- assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
204-
205- Row row = results.one();
206- assertThat(row.get("c5", optionalDecimalCodec.getJavaType())).isEqualTo(Optional.<BigDecimal>absent());
207- assertThat(row.getDecimal("c5")).isNull(); // Since BigDecimal is not a primitive it is nullable so expect null.
208- }
209-}
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +5 −77
@@ -18,11 +18,8 @@
1818 import java.nio.ByteBuffer;
1919 import java.util.*;
2020
21-import com.fasterxml.jackson.annotation.JsonCreator;
22-import com.fasterxml.jackson.annotation.JsonProperty;
2321 import com.google.common.base.Function;
2422 import com.google.common.base.Joiner;
25-import com.google.common.base.Objects;
2623 import com.google.common.base.Strings;
2724 import com.google.common.collect.Lists;
2825 import com.google.common.reflect.TypeToken;
@@ -36,7 +33,7 @@
3633 import com.datastax.driver.core.exceptions.InvalidTypeException;
3734
3835 import static com.datastax.driver.core.Assertions.assertThat;
39-import static com.datastax.driver.core.CodecUtils.listOf;
36+import static com.datastax.driver.core.TypeTokens.listOf;
4037 import static com.datastax.driver.core.DataType.*;
4138 import static com.datastax.driver.core.ProtocolVersion.V3;
4239
@@ -90,18 +87,6 @@
9087 codec.serialize(list, ProtocolVersion.V2);
9188 }
9289
93- @Test(groups = "unit")
94- public void test_cql_text_to_json() {
95- JsonCodec<User> codec = new JsonCodec<User>(User.class);
96- // the codec is expected to format json objects as json strings enclosed in single quotes,
97- // as it is required for CQL literals of varchar type.
98- String json = "'{\"id\":1,\"name\":\"John Doe\"}'";
99- User user = new User(1, "John Doe");
100- assertThat(codec.format(user)).isEqualTo(json);
101- assertThat(codec.parse(json)).isEqualToComparingFieldByField(user);
102- assertThat(codec).canSerialize(user);
103- }
104-
10590 @Test(groups = "unit")
10691 public void test_cql_list_varchar_to_list_list_integer() {
10792 ListVarcharToListListInteger codec = new ListVarcharToListListInteger();
@@ -171,13 +156,6 @@
171156 .accepts(u4);
172157 }
173158
174- @Test(groups = "unit")
175- public void test_enum() {
176- EnumStringCodec<FooBarQix> codec = new EnumStringCodec<FooBarQix>(FooBarQix.class);
177- assertThat(codec)
178- .canSerialize(FooBarQix.FOO);
179- }
180-
181159 @Test(groups = "unit")
182160 public void test_inheritance() {
183161 CodecRegistry codecRegistry = new CodecRegistry();
@@ -227,7 +205,7 @@
227205
228206 @Test(groups = "unit")
229207 public void should_deserialize_empty_buffer_as_tuple_with_null_values() {
230- CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
208+ CodecRegistry codecRegistry = new CodecRegistry();
231209 TupleType tupleType = new TupleType(newArrayList(DataType.cint(), DataType.varchar(), DataType.cfloat()), ProtocolVersion.NEWEST_SUPPORTED, codecRegistry);
232210 TupleValue expected = tupleType.newValue(null, null, null);
233211
@@ -238,7 +216,7 @@
238216
239217 @Test(groups = "unit")
240218 public void should_deserialize_empty_buffer_as_udt_with_null_values() {
241- CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE;
219+ CodecRegistry codecRegistry = new CodecRegistry();
242220 UserType udt = new UserType("ks", "t", Arrays.asList(
243221 new UserType.Field("t", DataType.text()),
244222 new UserType.Field("i", DataType.cint()),
@@ -278,7 +256,7 @@
278256 private final TypeCodec<List<String>> codec = TypeCodec.list(TypeCodec.varchar());
279257
280258 protected ListVarcharToListListInteger() {
281- super(DataType.list(DataType.varchar()), listOf(listOf(Integer.class)));
259+ super(DataType.list(DataType.varchar()), TypeTokens.listOf(TypeTokens.listOf(Integer.class)));
282260 }
283261
284262 @Override
@@ -316,57 +294,7 @@
316294 throw new UnsupportedOperationException();
317295 }
318296 }
319-
320- @SuppressWarnings("unused")
321- public static class User {
322-
323- private int id;
324-
325- private String name;
326-
327- @JsonCreator
328- public User(@JsonProperty("id") int id, @JsonProperty("name") String name) {
329- this.id = id;
330- this.name = name;
331- }
332-
333- public int getId() {
334- return id;
335- }
336-
337- public void setId(int id) {
338- this.id = id;
339- }
340-
341- public String getName() {
342- return name;
343- }
344-
345- public void setName(String name) {
346- this.name = name;
347- }
348-
349- @Override
350- public boolean equals(Object o) {
351- if (this == o)
352- return true;
353- if (o == null || getClass() != o.getClass())
354- return false;
355- User user = (User)o;
356- return Objects.equal(id, user.id) &&
357- Objects.equal(name, user.name);
358- }
359-
360- @Override
361- public int hashCode() {
362- return Objects.hashCode(id, name);
363- }
364- }
365-
366- enum FooBarQix {
367- FOO, BAR, QIX
368- }
369-
297+
370298 class A {
371299
372300 int i = 0;
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java +1 −1
@@ -55,7 +55,7 @@
5555 public void should_handle_collections_of_tuples() {
5656 String query;
5757 BuiltStatement statement;
58- query = "UPDATE foo SET l=[(1, 2)] WHERE k=1;";
58+ query = "UPDATE foo SET l=[(1,2)] WHERE k=1;";
5959 TupleType tupleType = cluster.getMetadata().newTupleType(cint(), cint());
6060 List<TupleValue> list = ImmutableList.of(tupleType.newValue(1, 2));
6161 statement = new QueryBuilder(cluster).update("foo").with(set("l", list)).where(eq("k", 1));
modified driver-examples/osgi/pom.xml +0 −8
@@ -207,14 +207,6 @@
207207 <skip>true</skip>
208208 </configuration>
209209 </plugin>
210- <plugin>
211- <artifactId>maven-compiler-plugin</artifactId>
212- <configuration>
213- <compilerArgument>-Xlint:all</compilerArgument>
214- <showWarnings>true</showWarnings>
215- <showDeprecation>true</showDeprecation>
216- </configuration>
217- </plugin>
218210 </plugins>
219211 </build>
220212 </profile>
added driver-extras/pom.xml +268 −0
@@ -0,0 +1,268 @@
1+<!--
2+
3+ Copyright (C) 2012-2015 DataStax Inc.
4+
5+ Licensed under the Apache License, Version 2.0 (the "License");
6+ you may not use this file except in compliance with the License.
7+ You may obtain a copy of the License at
8+
9+ http://www.apache.org/licenses/LICENSE-2.0
10+
11+ Unless required by applicable law or agreed to in writing, software
12+ distributed under the License is distributed on an "AS IS" BASIS,
13+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+ See the License for the specific language governing permissions and
15+ limitations under the License.
16+
17+-->
18+<project xmlns="http://maven.apache.org/POM/4.0.0"
19+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
20+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
21+ <parent>
22+ <artifactId>cassandra-driver-parent</artifactId>
23+ <groupId>com.datastax.cassandra</groupId>
24+ <version>3.0.0-beta1-SNAPSHOT</version>
25+ </parent>
26+ <modelVersion>4.0.0</modelVersion>
27+
28+ <artifactId>cassandra-driver-extras</artifactId>
29+
30+ <name>DataStax Java Driver for Apache Cassandra - Extras</name>
31+ <description>Extended functionality for the Java driver.</description>
32+ <url>https://github.com/datastax/java-driver</url>
33+
34+ <properties>
35+ <main.basedir>${project.parent.basedir}</main.basedir>
36+ <test.groups>unit</test.groups>
37+ <jdk8.excludes>none</jdk8.excludes>
38+ </properties>
39+
40+ <dependencies>
41+
42+ <dependency>
43+ <groupId>com.datastax.cassandra</groupId>
44+ <artifactId>cassandra-driver-core</artifactId>
45+ <version>${project.parent.version}</version>
46+ </dependency>
47+
48+ <dependency>
49+ <groupId>com.google.guava</groupId>
50+ <artifactId>guava</artifactId>
51+ <version>${guava.version}</version>
52+ </dependency>
53+
54+ <dependency>
55+ <groupId>com.fasterxml.jackson.core</groupId>
56+ <artifactId>jackson-databind</artifactId>
57+ <version>2.5.3</version>
58+ <optional>true</optional>
59+ </dependency>
60+
61+ <dependency>
62+ <groupId>joda-time</groupId>
63+ <artifactId>joda-time</artifactId>
64+ <version>2.8.1</version>
65+ <optional>true</optional>
66+ </dependency>
67+
68+ <dependency>
69+ <groupId>javax.json</groupId>
70+ <artifactId>javax.json-api</artifactId>
71+ <version>1.0</version>
72+ <optional>true</optional>
73+ </dependency>
74+
75+ <dependency>
76+ <groupId>com.datastax.cassandra</groupId>
77+ <artifactId>cassandra-driver-core</artifactId>
78+ <version>${project.parent.version}</version>
79+ <type>test-jar</type>
80+ <scope>test</scope>
81+ </dependency>
82+
83+ <dependency>
84+ <groupId>com.datastax.cassandra</groupId>
85+ <artifactId>cassandra-driver-mapping</artifactId>
86+ <version>${project.parent.version}</version>
87+ <scope>test</scope>
88+ </dependency>
89+
90+ <dependency>
91+ <groupId>org.testng</groupId>
92+ <artifactId>testng</artifactId>
93+ <version>${testng.version}</version>
94+ <scope>test</scope>
95+ </dependency>
96+
97+ <dependency>
98+ <groupId>org.assertj</groupId>
99+ <artifactId>assertj-core</artifactId>
100+ <version>${assertj.version}</version>
101+ <scope>test</scope>
102+ </dependency>
103+
104+ <dependency>
105+ <groupId>org.mockito</groupId>
106+ <artifactId>mockito-all</artifactId>
107+ <version>${mockito.version}</version>
108+ <scope>test</scope>
109+ </dependency>
110+
111+ <dependency>
112+ <groupId>org.apache.commons</groupId>
113+ <artifactId>commons-exec</artifactId>
114+ <version>${commons-exec.version}</version>
115+ <scope>test</scope>
116+ </dependency>
117+
118+ <dependency>
119+ <groupId>org.glassfish</groupId>
120+ <artifactId>javax.json</artifactId>
121+ <version>1.0.4</version>
122+ <scope>test</scope>
123+ </dependency>
124+
125+ </dependencies>
126+
127+ <build>
128+
129+ <plugins>
130+
131+ <plugin>
132+ <groupId>org.apache.maven.plugins</groupId>
133+ <artifactId>maven-compiler-plugin</artifactId>
134+ <configuration>
135+ <excludes>
136+ <exclude>${jdk8.excludes}</exclude>
137+ </excludes>
138+ <testExcludes>
139+ <exclude>${jdk8.excludes}</exclude>
140+ </testExcludes>
141+ </configuration>
142+ </plugin>
143+
144+ <plugin>
145+ <groupId>org.codehaus.mojo</groupId>
146+ <artifactId>animal-sniffer-maven-plugin</artifactId>
147+ <configuration>
148+ <!--
149+ There is no support for JDK 8 yet, see
150+ https://github.com/mojohaus/animal-sniffer/issues/1
151+ -->
152+ <skip>true</skip>
153+ <signature>
154+ <groupId>org.codehaus.mojo.signature</groupId>
155+ <artifactId>java18</artifactId>
156+ <version>1.0</version>
157+ </signature>
158+ </configuration>
159+ </plugin>
160+
161+ <plugin>
162+ <groupId>org.apache.maven.plugins</groupId>
163+ <artifactId>maven-surefire-plugin</artifactId>
164+ <version>2.16</version>
165+ <configuration>
166+ <groups>${test.groups}</groups>
167+ <useFile>false</useFile>
168+ <systemPropertyVariables>
169+ <cassandra.version>${cassandra.version}</cassandra.version>
170+ <ipprefix>${ipprefix}</ipprefix>
171+ </systemPropertyVariables>
172+ <classpathDependencyExcludes>
173+ <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes>
174+ </classpathDependencyExcludes>
175+ <excludes>
176+ <exclude>${jdk8.excludes}</exclude>
177+ </excludes>
178+ </configuration>
179+ </plugin>
180+
181+ <plugin>
182+ <groupId>org.apache.felix</groupId>
183+ <artifactId>maven-bundle-plugin</artifactId>
184+ <extensions>true</extensions>
185+ <version>2.4.0</version>
186+ <executions>
187+ <execution>
188+ <id>bundle-manifest</id>
189+ <phase>process-classes</phase>
190+ <goals>
191+ <goal>manifest</goal>
192+ </goals>
193+ </execution>
194+ </executions>
195+ <configuration>
196+ <instructions>
197+ <Bundle-SymbolicName>com.datastax.driver.extras</Bundle-SymbolicName>
198+ <Bundle-Version>${project.version}</Bundle-Version>
199+ <_include>-osgi.bnd</_include>
200+ </instructions>
201+ <supportedProjectTypes>
202+ <supportedProjectType>jar</supportedProjectType>
203+ <supportedProjectType>bundle</supportedProjectType>
204+ <supportedProjectType>pom</supportedProjectType>
205+ </supportedProjectTypes>
206+ </configuration>
207+ </plugin>
208+
209+ </plugins>
210+
211+ </build>
212+
213+ <profiles>
214+
215+ <profile>
216+ <id>short</id>
217+ <properties>
218+ <test.groups>unit,short</test.groups>
219+ </properties>
220+ </profile>
221+
222+ <profile>
223+ <id>long</id>
224+ <properties>
225+ <test.groups>unit,short,long</test.groups>
226+ </properties>
227+ </profile>
228+
229+ <!--
230+ This profile excludes all JDK 8 dependent classes from
231+ compilation. Use this when running tests with a legacy JDK (6 or 7)
232+ -->
233+ <profile>
234+ <id>legacy-jdks</id>
235+ <activation>
236+ <jdk>[,1.8)</jdk>
237+ </activation>
238+ <properties>
239+ <jdk8.excludes>**/jdk8/*.java</jdk8.excludes>
240+ </properties>
241+ </profile>
242+
243+ </profiles>
244+
245+ <licenses>
246+ <license>
247+ <name>Apache 2</name>
248+ <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
249+ <distribution>repo</distribution>
250+ <comments>Apache License Version 2.0</comments>
251+ </license>
252+ </licenses>
253+
254+ <scm>
255+ <connection>scm:git:git@github.com:datastax/java-driver.git</connection>
256+ <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection>
257+ <url>https://github.com/datastax/java-driver</url>
258+ <tag>HEAD</tag>
259+ </scm>
260+
261+ <developers>
262+ <developer>
263+ <name>Various</name>
264+ <organization>DataStax</organization>
265+ </developer>
266+ </developers>
267+
268+</project>
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/MappingCodec.java +82 −0
@@ -0,0 +1,82 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.google.common.reflect.TypeToken;
21+
22+import com.datastax.driver.core.ProtocolVersion;
23+import com.datastax.driver.core.TypeCodec;
24+import com.datastax.driver.core.exceptions.InvalidTypeException;
25+
26+/**
27+ * An abstract TypeCodec that maps a Java Pojo to another Java object
28+ * that can in turn be serialized into a CQL type.
29+ * This can serve as a base for libraries dealing with Pojo mappings.
30+ * <p>
31+ * This codec can be seen as a convenience base class for libraries
32+ * dealing with Pojo-to-Pojo mappings, but it comes
33+ * with a performance penalty: each Java object is serialized
34+ * in two steps: first to an intermediary object, and then to a ByteBuffer,
35+ * which means that each serialization actually incurs in two potentially
36+ * expensive operations being carried.
37+ * <p>
38+ * If such operations are really expensive, and your mapping library is capable
39+ * of serializing objects directly to ByteBuffers,
40+ * consider writing your own codec instead of using this one.
41+ *
42+ * @param <O> The "outer" (user-facing) Java type
43+ * @param <I> The "inner" (Cassandra-facing, intermediary) Java type
44+ */
45+public abstract class MappingCodec<O, I> extends TypeCodec<O> {
46+
47+ protected final TypeCodec<I> innerCodec;
48+
49+ public MappingCodec(TypeCodec<I> innerCodec, Class<O> javaType) {
50+ this(innerCodec, TypeToken.of(javaType));
51+ }
52+
53+ public MappingCodec(TypeCodec<I> innerCodec, TypeToken<O> javaType) {
54+ super(innerCodec.getCqlType(), javaType);
55+ this.innerCodec = innerCodec;
56+ }
57+
58+ @Override
59+ public ByteBuffer serialize(O value, ProtocolVersion protocolVersion) throws InvalidTypeException {
60+ return innerCodec.serialize(serialize(value), protocolVersion);
61+ }
62+
63+ @Override
64+ public O deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
65+ return deserialize(innerCodec.deserialize(bytes, protocolVersion));
66+ }
67+
68+ @Override
69+ public O parse(String value) throws InvalidTypeException {
70+ return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : deserialize(innerCodec.parse(value));
71+ }
72+
73+ @Override
74+ public String format(O value) throws InvalidTypeException {
75+ return value == null ? null : innerCodec.format(serialize(value));
76+ }
77+
78+ protected abstract O deserialize(I value);
79+
80+ protected abstract I serialize(O value);
81+
82+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/ParsingCodec.java +107 −0
@@ -0,0 +1,107 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.google.common.reflect.TypeToken;
21+
22+import com.datastax.driver.core.ProtocolVersion;
23+import com.datastax.driver.core.TypeCodec;
24+import com.datastax.driver.core.exceptions.InvalidTypeException;
25+
26+/**
27+ * An abstract TypeCodec that stores JAVA objects as serialized strings.
28+ * This can serve as a base for codecs dealing with XML or JSON formats.
29+ * <p>
30+ * This codec can be seen as a convenience base class to help
31+ * implementing Java-to-XML or Java-to-JSON mappings, but it comes
32+ * with a performance penalty: each Java object is serialized
33+ * in two steps: first to a String, and then to a ByteBuffer,
34+ * which means that each serialization actually incurs in two potentially
35+ * expensive operations being carried.
36+ * <p>
37+ * If you are using an XML or JSON library that supports writing Java objects
38+ * directly to ByteBuffers, consider writing your own codec instead of
39+ * using this one.
40+ *
41+ * @param <T> The Java type this codec serializes from and deserializes to.
42+ */
43+public abstract class ParsingCodec<T> extends TypeCodec<T> {
44+
45+ private final TypeCodec<String> innerCodec;
46+
47+ public ParsingCodec(Class<T> javaType) {
48+ this(TypeToken.of(javaType));
49+ }
50+
51+ public ParsingCodec(TypeToken<T> javaType) {
52+ this(TypeCodec.varchar(), javaType);
53+ }
54+
55+ public ParsingCodec(TypeCodec<String> innerCodec, Class<T> javaType) {
56+ this(innerCodec, TypeToken.of(javaType));
57+ }
58+
59+ public ParsingCodec(TypeCodec<String> innerCodec, TypeToken<T> javaType) {
60+ super(innerCodec.getCqlType(), javaType);
61+ this.innerCodec = innerCodec;
62+ }
63+
64+ @Override
65+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
66+ return value == null ? null : innerCodec.serialize(toString(value), protocolVersion);
67+ }
68+
69+ @Override
70+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
71+ String value = innerCodec.deserialize(bytes, protocolVersion);
72+ return value == null ? null : fromString(value);
73+ }
74+
75+ @Override
76+ public String format(T value) throws InvalidTypeException {
77+ return value == null ? null : innerCodec.format(toString(value));
78+ }
79+
80+ @Override
81+ public T parse(String value) throws InvalidTypeException {
82+ return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : fromString(innerCodec.parse(value));
83+ }
84+
85+ /**
86+ * Return the String representation of the given object;
87+ * no special CQL quoting should be applied here.
88+ * Null values should be accepted; in most cases, implementors
89+ * should return null for null inputs.
90+ *
91+ * @param value the value to convert into a string
92+ * @return the String representation of the given object
93+ */
94+ protected abstract String toString(T value);
95+
96+ /**
97+ * Parse the given string into an object;
98+ * no special CQL unquoting should be applied here.
99+ * Null values should be accepted; in most cases, implementors
100+ * should return null for null inputs.
101+ *
102+ * @param value the string to parse
103+ * @return the parsed object.
104+ */
105+ protected abstract T fromString(String value);
106+
107+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/AbstractArrayCodec.java +149 −0
@@ -0,0 +1,149 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.arrays;
17+
18+import java.lang.reflect.Array;
19+
20+import static com.google.common.base.Preconditions.checkArgument;
21+
22+import com.datastax.driver.core.DataType;
23+import com.datastax.driver.core.ParseUtils;
24+import com.datastax.driver.core.TypeCodec;
25+import com.datastax.driver.core.exceptions.InvalidTypeException;
26+
27+import static com.datastax.driver.core.ParseUtils.skipSpaces;
28+
29+/**
30+ * Base class for all codecs dealing with Java arrays.
31+ * This class aims to reduce the amount of code required to create such codecs.
32+ *
33+ * @param <T> The Java array type this codec handles
34+ */
35+public abstract class AbstractArrayCodec<T> extends TypeCodec<T> {
36+
37+ /**
38+ * @param cqlType The CQL type. Must be a list type.
39+ * @param javaClass The Java type. Must be an array class.
40+ */
41+ public AbstractArrayCodec(DataType.CollectionType cqlType, Class<T> javaClass) {
42+ super(cqlType, javaClass);
43+ checkArgument(cqlType.getName() == DataType.Name.LIST, "Expecting CQL list type, got %s", cqlType);
44+ checkArgument(javaClass.isArray(), "Expecting Java array class, got %s", javaClass);
45+ }
46+
47+ @Override
48+ public String format(T array) throws InvalidTypeException {
49+ if (array == null)
50+ return "NULL";
51+ int length = Array.getLength(array);
52+ StringBuilder sb = new StringBuilder();
53+ sb.append('[');
54+ for (int i = 0; i < length; i++) {
55+ if (i != 0)
56+ sb.append(",");
57+ formatElement(sb, array, i);
58+ }
59+ sb.append(']');
60+ return sb.toString();
61+ }
62+
63+ @Override
64+ public T parse(String value) throws InvalidTypeException {
65+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
66+ return null;
67+
68+ int idx = skipSpaces(value, 0);
69+ if (value.charAt(idx++) != '[')
70+ throw new InvalidTypeException(String.format("cannot parse list value from \"%s\", at character %d expecting '[' but got '%c'", value, idx, value.charAt(idx)));
71+
72+ idx = skipSpaces(value, idx);
73+
74+ if (value.charAt(idx) == ']')
75+ return newInstance(0);
76+
77+ // first pass: determine array length
78+ int length = getArrayLength(value, idx);
79+
80+ // second pass: parse elements
81+ T array = newInstance(length);
82+ int i = 0;
83+ for( ; idx < value.length(); i++) {
84+ int n = skipLiteral(value, idx);
85+ parseElement(value.substring(idx, n), array, i);
86+ idx = skipSpaces(value, n);
87+ if (value.charAt(idx) == ']')
88+ return array;
89+ idx = skipComma(value, idx);
90+ idx = skipSpaces(value, idx);
91+ }
92+
93+ throw new InvalidTypeException(String.format("Malformed list value \"%s\", missing closing ']'", value));
94+ }
95+
96+ /**
97+ * Create a new array instance with the given size.
98+ *
99+ * @param size The size of the array to instantiate.
100+ * @return a new array instance with the given size.
101+ */
102+ protected abstract T newInstance(int size);
103+
104+ /**
105+ * Format the {@code index}th element of {@code array} to {@code output}.
106+ *
107+ * @param output The StringBuilder to write to.
108+ * @param array The array to read from.
109+ * @param index The element index.
110+ */
111+ protected abstract void formatElement(StringBuilder output, T array, int index);
112+
113+ /**
114+ * Parse the {@code index}th element of {@code array} from {@code input}.
115+ *
116+ * @param input The String to read from.
117+ * @param array The array to write to.
118+ * @param index The element index.
119+ */
120+ protected abstract void parseElement(String input, T array, int index);
121+
122+ private int getArrayLength(String value, int idx) {
123+ int length = 1;
124+ for( ; idx < value.length(); length++) {
125+ idx = skipLiteral(value, idx);
126+ idx = skipSpaces(value, idx);
127+ if (value.charAt(idx) == ']')
128+ break;
129+ idx = skipComma(value, idx);
130+ idx = skipSpaces(value, idx);
131+ }
132+ return length;
133+ }
134+
135+ private int skipComma(String value, int idx) {
136+ if (value.charAt(idx) != ',')
137+ throw new InvalidTypeException(String.format("Cannot parse list value from \"%s\", at character %d expecting ',' but got '%c'", value, idx, value.charAt(idx)));
138+ return idx + 1;
139+ }
140+
141+ private int skipLiteral(String value, int idx) {
142+ try {
143+ return ParseUtils.skipCQLValue(value, idx);
144+ } catch (IllegalArgumentException e) {
145+ throw new InvalidTypeException(String.format("Cannot parse list value from \"%s\", invalid CQL value at character %d", value, idx), e);
146+ }
147+ }
148+
149+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/AbstractPrimitiveArrayCodec.java +120 −0
@@ -0,0 +1,120 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.arrays;
17+
18+import java.lang.reflect.Array;
19+import java.nio.ByteBuffer;
20+
21+import static com.google.common.base.Preconditions.checkArgument;
22+
23+import com.datastax.driver.core.CodecUtils;
24+import com.datastax.driver.core.DataType;
25+import com.datastax.driver.core.ProtocolVersion;
26+import com.datastax.driver.core.exceptions.InvalidTypeException;
27+
28+/**
29+ * Base class for all codecs dealing with Java primitive arrays.
30+ * This class provides a more efficient implementation of {@link #serialize(Object, ProtocolVersion)}
31+ * and {@link #deserialize(ByteBuffer, ProtocolVersion)} for primitive arrays.
32+ *
33+ * @param <T> The Java primitive array type this codec handles
34+ */
35+public abstract class AbstractPrimitiveArrayCodec<T> extends AbstractArrayCodec<T> {
36+
37+ /**
38+ * @param cqlType The CQL type. Must be a list type.
39+ * @param javaClass The Java type. Must be an array class.
40+ */
41+ public AbstractPrimitiveArrayCodec(DataType.CollectionType cqlType, Class<T> javaClass) {
42+ super(cqlType, javaClass);
43+ checkArgument(javaClass.getComponentType().isPrimitive(), "Expecting primitive array component type, got %s", javaClass.getComponentType());
44+ }
45+
46+ @Override
47+ public ByteBuffer serialize(T array, ProtocolVersion protocolVersion) throws InvalidTypeException {
48+ if (array == null)
49+ return null;
50+ boolean isProtocolV3OrAbove = protocolVersion.compareTo(ProtocolVersion.V2) > 0;
51+ // native method
52+ int length = Array.getLength(array);
53+ checkArgument(isProtocolV3OrAbove || length < 65536,
54+ "Native protocol version %d supports up to 65535 elements in any collection - but collection contains %d elements",
55+ protocolVersion.toInt(), length);
56+ /*
57+ * Encoding of lists in the native protocol:
58+ * [size of list] [size of element 1][element1] [size of element 2][element2]...
59+ * Sizes are encoded on 2 bytes in protocol v1 and v2, 4 bytes otherwise.
60+ * (See native_protocol_v*.spec in https://github.com/apache/cassandra/blob/trunk/doc/)
61+ */
62+ // Number of bytes to encode sizes
63+ int sizeOfSize = isProtocolV3OrAbove ? 4 : 2;
64+ // Number of bytes to encode each element (preceded by its size)
65+ int sizeOfElement = sizeOfSize + sizeOfComponentType();
66+ // Number of bytes to encode the whole collection (size of collection + all elements)
67+ int totalSize = sizeOfSize + length * sizeOfElement;
68+ ByteBuffer output = ByteBuffer.allocate(totalSize);
69+ CodecUtils.writeSize(output, length, protocolVersion);
70+ for (int i = 0; i < length; i++) {
71+ CodecUtils.writeSize(output, sizeOfComponentType(), protocolVersion);
72+ serializeElement(output, array, i, protocolVersion);
73+ }
74+ output.flip();
75+ return output;
76+ }
77+
78+ @Override
79+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
80+ if (bytes == null || bytes.remaining() == 0)
81+ return newInstance(0);
82+ boolean isProtocolV3OrAbove = protocolVersion.compareTo(ProtocolVersion.V2) > 0;
83+ int sizeOfSize = isProtocolV3OrAbove ? 4 : 2;
84+ ByteBuffer input = bytes.duplicate();
85+ int size = CodecUtils.readSize(input, protocolVersion);
86+ T array = newInstance(size);
87+ for (int i = 0; i < size; i++) {
88+ // Skip size (we know it will always be 4 since the elements are ints)
89+ input.position(input.position() + sizeOfSize);
90+ deserializeElement(input, array, i, protocolVersion);
91+ }
92+ return array;
93+ }
94+
95+ /**
96+ * Return the size in bytes of the array component type.
97+ *
98+ * @return the size in bytes of the array component type.
99+ */
100+ protected abstract int sizeOfComponentType();
101+
102+ /**
103+ * Write the {@code index}th element of {@code array} to {@code output}.
104+ * @param output The ByteBuffer to write to.
105+ * @param array The array to read from.
106+ * @param index The element index.
107+ * @param protocolVersion The protocol version to use.
108+ */
109+ protected abstract void serializeElement(ByteBuffer output, T array, int index, ProtocolVersion protocolVersion);
110+
111+ /**
112+ * Read the {@code index}th element of {@code array} from {@code input}.
113+ * @param input The ByteBuffer to read from.
114+ * @param array The array to write to.
115+ * @param index The element index.
116+ * @param protocolVersion The protocol version to use.
117+ */
118+ protected abstract void deserializeElement(ByteBuffer input, T array, int index, ProtocolVersion protocolVersion);
119+
120+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/DoubleArrayCodec.java +70 −0
@@ -0,0 +1,70 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.arrays;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.datastax.driver.core.DataType;
21+import com.datastax.driver.core.ProtocolVersion;
22+
23+/**
24+ * A codec that maps the CQL type {@code list<double>} to the Java type {@code double[]}.
25+ * <p>
26+ * Note that this codec is designed for performance and converts CQL lists
27+ * <em>directly</em> to {@code double[]}, thus avoiding any unnecessary
28+ * boxing and unboxing of Java primitive {@code double} values;
29+ * it also instantiates arrays without the need for an intermediary
30+ * Java {@code List} object.
31+ */
32+public class DoubleArrayCodec extends AbstractPrimitiveArrayCodec<double[]> {
33+
34+ public static final DoubleArrayCodec instance = new DoubleArrayCodec();
35+
36+ public DoubleArrayCodec() {
37+ super(DataType.list(DataType.cdouble()), double[].class);
38+ }
39+
40+ @Override
41+ protected int sizeOfComponentType() {
42+ return 8;
43+ }
44+
45+ @Override
46+ protected void serializeElement(ByteBuffer output, double[] array, int index, ProtocolVersion protocolVersion) {
47+ output.putDouble(array[index]);
48+ }
49+
50+ @Override
51+ protected void deserializeElement(ByteBuffer input, double[] array, int index, ProtocolVersion protocolVersion) {
52+ array[index] = input.getDouble();
53+ }
54+
55+ @Override
56+ protected void formatElement(StringBuilder output, double[] array, int index) {
57+ output.append(array[index]);
58+ }
59+
60+ @Override
61+ protected void parseElement(String input, double[] array, int index) {
62+ array[index] = Double.parseDouble(input);
63+ }
64+
65+ @Override
66+ protected double[] newInstance(int size) {
67+ return new double[size];
68+ }
69+
70+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/FloatArrayCodec.java +70 −0
@@ -0,0 +1,70 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.arrays;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.datastax.driver.core.DataType;
21+import com.datastax.driver.core.ProtocolVersion;
22+
23+/**
24+ * A codec that maps the CQL type {@code list<float>} to the Java type {@code float[]}.
25+ * <p>
26+ * Note that this codec is designed for performance and converts CQL lists
27+ * <em>directly</em> to {@code float[]}, thus avoiding any unnecessary
28+ * boxing and unboxing of Java primitive {@code float} values;
29+ * it also instantiates arrays without the need for an intermediary
30+ * Java {@code List} object.
31+ */
32+public class FloatArrayCodec extends AbstractPrimitiveArrayCodec<float[]> {
33+
34+ public static final FloatArrayCodec instance = new FloatArrayCodec();
35+
36+ public FloatArrayCodec() {
37+ super(DataType.list(DataType.cfloat()), float[].class);
38+ }
39+
40+ @Override
41+ protected int sizeOfComponentType() {
42+ return 4;
43+ }
44+
45+ @Override
46+ protected void serializeElement(ByteBuffer output, float[] array, int index, ProtocolVersion protocolVersion) {
47+ output.putFloat(array[index]);
48+ }
49+
50+ @Override
51+ protected void deserializeElement(ByteBuffer input, float[] array, int index, ProtocolVersion protocolVersion) {
52+ array[index] = input.getFloat();
53+ }
54+
55+ @Override
56+ protected void formatElement(StringBuilder output, float[] array, int index) {
57+ output.append(array[index]);
58+ }
59+
60+ @Override
61+ protected void parseElement(String input, float[] array, int index) {
62+ array[index] = Float.parseFloat(input);
63+ }
64+
65+ @Override
66+ protected float[] newInstance(int size) {
67+ return new float[size];
68+ }
69+
70+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/IntArrayCodec.java +70 −0
@@ -0,0 +1,70 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.arrays;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.datastax.driver.core.DataType;
21+import com.datastax.driver.core.ProtocolVersion;
22+
23+/**
24+ * A codec that maps the CQL type {@code list<int>} to the Java type {@code int[]}.
25+ * <p>
26+ * Note that this codec is designed for performance and converts CQL lists
27+ * <em>directly</em> to {@code int[]}, thus avoiding any unnecessary
28+ * boxing and unboxing of Java primitive {@code int} values;
29+ * it also instantiates arrays without the need for an intermediary
30+ * Java {@code List} object.
31+ */
32+public class IntArrayCodec extends AbstractPrimitiveArrayCodec<int[]> {
33+
34+ public static final IntArrayCodec instance = new IntArrayCodec();
35+
36+ public IntArrayCodec() {
37+ super(DataType.list(DataType.cint()), int[].class);
38+ }
39+
40+ @Override
41+ protected int sizeOfComponentType() {
42+ return 4;
43+ }
44+
45+ @Override
46+ protected void serializeElement(ByteBuffer output, int[] array, int index, ProtocolVersion protocolVersion) {
47+ output.putInt(array[index]);
48+ }
49+
50+ @Override
51+ protected void deserializeElement(ByteBuffer input, int[] array, int index, ProtocolVersion protocolVersion) {
52+ array[index] = input.getInt();
53+ }
54+
55+ @Override
56+ protected void formatElement(StringBuilder output, int[] array, int index) {
57+ output.append(array[index]);
58+ }
59+
60+ @Override
61+ protected void parseElement(String input, int[] array, int index) {
62+ array[index] = Integer.parseInt(input);
63+ }
64+
65+ @Override
66+ protected int[] newInstance(int size) {
67+ return new int[size];
68+ }
69+
70+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/LongArrayCodec.java +70 −0
@@ -0,0 +1,70 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.arrays;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.datastax.driver.core.DataType;
21+import com.datastax.driver.core.ProtocolVersion;
22+
23+/**
24+ * A codec that maps the CQL type {@code list<long>} to the Java type {@code long[]}.
25+ * <p>
26+ * Note that this codec is designed for performance and converts CQL lists
27+ * <em>directly</em> to {@code long[]}, thus avoiding any unnecessary
28+ * boxing and unboxing of Java primitive {@code long} values;
29+ * it also instantiates arrays without the need for an intermediary
30+ * Java {@code List} object.
31+ */
32+public class LongArrayCodec extends AbstractPrimitiveArrayCodec<long[]> {
33+
34+ public static final LongArrayCodec instance = new LongArrayCodec();
35+
36+ public LongArrayCodec() {
37+ super(DataType.list(DataType.bigint()), long[].class);
38+ }
39+
40+ @Override
41+ protected int sizeOfComponentType() {
42+ return 8;
43+ }
44+
45+ @Override
46+ protected void serializeElement(ByteBuffer output, long[] array, int index, ProtocolVersion protocolVersion) {
47+ output.putLong(array[index]);
48+ }
49+
50+ @Override
51+ protected void deserializeElement(ByteBuffer input, long[] array, int index, ProtocolVersion protocolVersion) {
52+ array[index] = input.getLong();
53+ }
54+
55+ @Override
56+ protected void formatElement(StringBuilder output, long[] array, int index) {
57+ output.append(array[index]);
58+ }
59+
60+ @Override
61+ protected void parseElement(String input, long[] array, int index) {
62+ array[index] = Long.parseLong(input);
63+ }
64+
65+ @Override
66+ protected long[] newInstance(int size) {
67+ return new long[size];
68+ }
69+
70+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/ObjectArrayCodec.java +109 −0
@@ -0,0 +1,109 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.arrays;
17+
18+import java.lang.reflect.Array;
19+import java.nio.BufferUnderflowException;
20+import java.nio.ByteBuffer;
21+
22+import com.datastax.driver.core.CodecUtils;
23+import com.datastax.driver.core.DataType;
24+import com.datastax.driver.core.ProtocolVersion;
25+import com.datastax.driver.core.TypeCodec;
26+import com.datastax.driver.core.exceptions.InvalidTypeException;
27+
28+/**
29+ * Codec dealing with Java object arrays.
30+ * Serialization and deserialization of elements in the array is
31+ * delegated to the provided element codec.
32+ * <p>
33+ * For example, to create a codec that maps {@code list<text>} to {@code String[]},
34+ * declare the following:
35+ * <pre>{@code
36+ * ObjectArrayCodec<String> stringArrayCodec = new ObjectArrayCodec<>(
37+ * DataType.list(DataType.varchar()),
38+ * String[].class,
39+ * TypeCodec.varchar());
40+ * }</pre>
41+ *
42+ * @param <E> The Java array component type this codec handles
43+ */
44+public class ObjectArrayCodec<E> extends AbstractArrayCodec<E[]> {
45+
46+ protected final TypeCodec<E> eltCodec;
47+
48+ public ObjectArrayCodec(DataType.CollectionType cqlType, Class<E[]> javaClass, TypeCodec<E> eltCodec) {
49+ super(cqlType, javaClass);
50+ this.eltCodec = eltCodec;
51+ }
52+
53+ @Override
54+ public ByteBuffer serialize(E[] value, ProtocolVersion protocolVersion) {
55+ if (value == null)
56+ return null;
57+ int i = 0;
58+ ByteBuffer[] bbs = new ByteBuffer[value.length];
59+ for (E elt : value) {
60+ if (elt == null) {
61+ throw new NullPointerException("Collection elements cannot be null");
62+ }
63+ ByteBuffer bb;
64+ try {
65+ bb = eltCodec.serialize(elt, protocolVersion);
66+ } catch (ClassCastException e) {
67+ throw new InvalidTypeException(
68+ String.format("Invalid type for %s element, expecting %s but got %s",
69+ cqlType, eltCodec.getJavaType(), elt.getClass()), e);
70+ }
71+ bbs[i++] = bb;
72+ }
73+ return CodecUtils.pack(bbs, value.length, protocolVersion);
74+ }
75+
76+ @Override
77+ public E[] deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
78+ if (bytes == null || bytes.remaining() == 0)
79+ return newInstance(0);
80+ try {
81+ ByteBuffer input = bytes.duplicate();
82+ int n = CodecUtils.readSize(input, protocolVersion);
83+ E[] array = newInstance(n);
84+ for (int i = 0; i < n; i++) {
85+ ByteBuffer databb = CodecUtils.readValue(input, protocolVersion);
86+ array[i] = eltCodec.deserialize(databb, protocolVersion);
87+ }
88+ return array;
89+ } catch (BufferUnderflowException e) {
90+ throw new InvalidTypeException("Not enough bytes to deserialize list");
91+ }
92+ }
93+
94+ @Override
95+ protected void formatElement(StringBuilder output, E[] array, int index) {
96+ output.append(eltCodec.format(array[index]));
97+ }
98+
99+ @Override
100+ protected void parseElement(String input, E[] array, int index) {
101+ array[index] = eltCodec.parse(input);
102+ }
103+
104+ @Override
105+ @SuppressWarnings("unchecked")
106+ protected E[] newInstance(int size) {
107+ return (E[])Array.newInstance(getJavaType().getRawType().getComponentType(), size);
108+ }
109+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/arrays/package-info.java +57 −0
@@ -0,0 +1,57 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+/**
18+ * This package contains a collection of convenience
19+ * {@link com.datastax.driver.core.TypeCodec TypeCodec} instances useful for
20+ * serializing between CQL lists and Java arrays.
21+ * <p>
22+ * The codecs in this package provide the following mappings:
23+ *
24+ * <table summary="Supported Mappings">
25+ * <tr>
26+ * <th>Codec</th>
27+ * <th>CQL type</th>
28+ * <th>Java type</th>
29+ * </tr>
30+ * <tr>
31+ * <td>{@link com.datastax.driver.extras.codecs.arrays.ObjectArrayCodec}</td>
32+ * <td>{@code list<?>}</td>
33+ * <td>{@code T[]}</td>
34+ * </tr>
35+ * <tr>
36+ * <td>{@link com.datastax.driver.extras.codecs.arrays.IntArrayCodec}</td>
37+ * <td>{@code list<int>}</td>
38+ * <td>{@code int[]}</td>
39+ * </tr>
40+ * <tr>
41+ * <td>{@link com.datastax.driver.extras.codecs.arrays.LongArrayCodec}</td>
42+ * <td>{@code list<long>}</td>
43+ * <td>{@code long[]}</td>
44+ * </tr>
45+ * <tr>
46+ * <td>{@link com.datastax.driver.extras.codecs.arrays.FloatArrayCodec}</td>
47+ * <td>{@code list<float>}</td>
48+ * <td>{@code float[]}</td>
49+ * </tr>
50+ * <tr>
51+ * <td>{@link com.datastax.driver.extras.codecs.arrays.DoubleArrayCodec}</td>
52+ * <td>{@code list<double>}</td>
53+ * <td>{@code double[]}</td>
54+ * </tr>
55+ * </table>
56+ */
57+package com.datastax.driver.extras.codecs.arrays;
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/date/SimpleDateCodec.java +113 −0
@@ -0,0 +1,113 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.date;
17+
18+import java.nio.ByteBuffer;
19+import java.text.ParseException;
20+import java.util.Date;
21+
22+import static java.util.concurrent.TimeUnit.MILLISECONDS;
23+
24+import com.datastax.driver.core.*;
25+import com.datastax.driver.core.exceptions.InvalidTypeException;
26+
27+import static com.datastax.driver.core.CodecUtils.fromCqlDateToDaysSinceEpoch;
28+import static com.datastax.driver.core.CodecUtils.fromDaysSinceEpochToCqlDate;
29+import static com.datastax.driver.core.CodecUtils.fromSignedToUnsignedInt;
30+import static com.datastax.driver.core.CodecUtils.fromUnsignedToSignedInt;
31+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
32+import static com.datastax.driver.core.ParseUtils.isQuoted;
33+import static com.datastax.driver.core.ParseUtils.parseDate;
34+import static com.datastax.driver.core.ParseUtils.quote;
35+import static com.datastax.driver.core.ParseUtils.unquote;
36+
37+/**
38+ * A {@link TypeCodec} that maps CQL dates to Java primitive ints,
39+ * representing the number of days since the Epoch.
40+ * <p>
41+ * This codec can serve as a replacement for the driver's built-in
42+ * {@link TypeCodec#date() date} codec,
43+ * when application code prefers to deal with raw days than with
44+ * {@link LocalDate} instances.
45+ * <p>
46+ * <strong>Important</strong>: this codec cannot work with {@link SimpleStatement}s!
47+ * If you try to insert CQL date values as {@code int}s in a {@link SimpleStatement},
48+ * the insertion would succeed but the values wouldn't be properly encoded.
49+ * Always use {@link PreparedStatement}s when using this codec.
50+ */
51+public class SimpleDateCodec extends TypeCodec.PrimitiveIntCodec {
52+
53+ public static final SimpleDateCodec instance = new SimpleDateCodec();
54+
55+ private static final String pattern = "yyyy-MM-dd";
56+
57+ public SimpleDateCodec() {
58+ super(DataType.date());
59+ }
60+
61+ @Override
62+ public ByteBuffer serializeNoBoxing(int value, ProtocolVersion protocolVersion) {
63+ return cint().serializeNoBoxing(fromSignedToUnsignedInt(value), protocolVersion);
64+ }
65+
66+ @Override
67+ public int deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
68+ if (bytes == null || bytes.remaining() == 0)
69+ return 0;
70+ return fromUnsignedToSignedInt(cint().deserializeNoBoxing(bytes, protocolVersion));
71+ }
72+
73+ @Override
74+ public Integer parse(String value) {
75+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
76+ return null;
77+
78+ // single quotes are optional for long literals, mandatory for date patterns
79+ // strip enclosing single quotes, if any
80+ if (isQuoted(value))
81+ value = unquote(value);
82+
83+ if (isLongLiteral(value)) {
84+ long unsigned;
85+ try {
86+ unsigned = Long.parseLong(value);
87+ } catch (NumberFormatException e) {
88+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value), e);
89+ }
90+ try {
91+ return fromCqlDateToDaysSinceEpoch(unsigned);
92+ } catch (IllegalArgumentException e) {
93+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value), e);
94+ }
95+ }
96+
97+ try {
98+ Date date = parseDate(value, pattern);
99+ return (int)MILLISECONDS.toDays(date.getTime());
100+ } catch (ParseException e) {
101+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value), e);
102+ }
103+ }
104+
105+ @Override
106+ public String format(Integer value) {
107+ if (value == null)
108+ return "NULL";
109+ long raw = fromDaysSinceEpochToCqlDate(value);
110+ return quote(Long.toString(raw));
111+ }
112+
113+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/date/SimpleTimestampCodec.java +95 −0
@@ -0,0 +1,95 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.date;
17+
18+import java.nio.ByteBuffer;
19+import java.text.ParseException;
20+
21+import static java.lang.Long.parseLong;
22+
23+import com.datastax.driver.core.DataType;
24+import com.datastax.driver.core.ProtocolVersion;
25+import com.datastax.driver.core.TypeCodec;
26+import com.datastax.driver.core.exceptions.InvalidTypeException;
27+
28+import static com.datastax.driver.core.ParseUtils.*;
29+
30+/**
31+ * A {@link TypeCodec} that maps CQL timestamps to Java primitive longs,
32+ * representing the number of milliseconds since the Epoch.
33+ * <p>
34+ * This codec can serve as a replacement for the driver's built-in
35+ * {@link TypeCodec#timestamp() timestamp} codec,
36+ * when application code prefers to deal with raw milliseconds than with
37+ * {@link java.util.Date} instances.
38+ */
39+public class SimpleTimestampCodec extends TypeCodec.PrimitiveLongCodec {
40+
41+ public static final SimpleTimestampCodec instance = new SimpleTimestampCodec();
42+
43+ public SimpleTimestampCodec() {
44+ super(DataType.timestamp());
45+ }
46+
47+ @Override
48+ public ByteBuffer serializeNoBoxing(long value, ProtocolVersion protocolVersion) {
49+ ByteBuffer bb = ByteBuffer.allocate(8);
50+ bb.putLong(0, value);
51+ return bb;
52+ }
53+
54+ @Override
55+ public long deserializeNoBoxing(ByteBuffer bytes, ProtocolVersion protocolVersion) {
56+ if (bytes == null || bytes.remaining() == 0)
57+ return 0;
58+ if (bytes.remaining() != 8)
59+ throw new InvalidTypeException("Invalid 64-bits long value, expecting 8 bytes but got " + bytes.remaining());
60+ return bytes.getLong(bytes.position());
61+ }
62+
63+ @Override
64+ public Long parse(String value) {
65+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
66+ return null;
67+
68+ // single quotes are optional for long literals, mandatory for date patterns
69+ // strip enclosing single quotes, if any
70+ if (isQuoted(value))
71+ value = unquote(value);
72+
73+ if (isLongLiteral(value)) {
74+ try {
75+ return parseLong(value);
76+ } catch (NumberFormatException e) {
77+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value), e);
78+ }
79+ }
80+
81+ try {
82+ return parseDate(value).getTime();
83+ } catch (ParseException e) {
84+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value), e);
85+ }
86+ }
87+
88+ @Override
89+ public String format(Long value) {
90+ if (value == null)
91+ return "NULL";
92+ return quote(Long.toString(value));
93+ }
94+
95+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/date/package-info.java +42 −0
@@ -0,0 +1,42 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+/**
18+ * This package contains a collection of convenience
19+ * {@link com.datastax.driver.core.TypeCodec} instances useful for
20+ * serializing between CQL temporal types and Java primitive types.
21+ * <p>
22+ * The codecs in this class provide the following mappings:
23+ *
24+ * <table summary="Supported Mappings">
25+ * <tr>
26+ * <th>Codec</th>
27+ * <th>CQL type</th>
28+ * <th>Java type</th>
29+ * </tr>
30+ * <tr>
31+ * <td>{@link com.datastax.driver.extras.codecs.date.SimpleTimestampCodec}</td>
32+ * <td>{@link com.datastax.driver.core.DataType#timestamp() timestamp}</td>
33+ * <td>{@code long} (representing milliseconds since the Epoch)</td>
34+ * </tr>
35+ * <tr>
36+ * <td>{@link com.datastax.driver.extras.codecs.date.SimpleDateCodec}</td>
37+ * <td>{@link com.datastax.driver.core.DataType#date() date}</td>
38+ * <td>{@code int} (representing days since the Epoch)</td>
39+ * </tr>
40+ * </table>
41+ */
42+package com.datastax.driver.extras.codecs.date;
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/enums/EnumNameCodec.java +53 −0
@@ -0,0 +1,53 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.enums;
17+
18+import com.datastax.driver.core.TypeCodec;
19+import com.datastax.driver.extras.codecs.ParsingCodec;
20+
21+/**
22+ * A codec that serializes {@link Enum} instances as CQL {@code varchar}s
23+ * representing their programmatic names as returned by {@link Enum#name()}.
24+ * <p>
25+ * <strong>Note that this codec relies on the enum constant names;
26+ * it is therefore vital that enum names never change.</strong>
27+ *
28+ * @param <E> The Enum class this codec serializes from and deserializes to.
29+ */
30+public class EnumNameCodec<E extends Enum<E>> extends ParsingCodec<E> {
31+
32+ private final Class<E> enumClass;
33+
34+ public EnumNameCodec(Class<E> enumClass) {
35+ this(TypeCodec.varchar(), enumClass);
36+ }
37+
38+ public EnumNameCodec(TypeCodec<String> innerCodec, Class<E> enumClass) {
39+ super(innerCodec, enumClass);
40+ this.enumClass = enumClass;
41+ }
42+
43+ @Override
44+ protected String toString(E value) {
45+ return value == null ? null : value.name();
46+ }
47+
48+ @Override
49+ protected E fromString(String value) {
50+ return value == null ? null : Enum.valueOf(enumClass, value);
51+ }
52+
53+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/enums/EnumOrdinalCodec.java +73 −0
@@ -0,0 +1,73 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.enums;
17+
18+import java.nio.ByteBuffer;
19+
20+import com.datastax.driver.core.ProtocolVersion;
21+import com.datastax.driver.core.TypeCodec;
22+import com.datastax.driver.core.exceptions.InvalidTypeException;
23+
24+/**
25+ * A codec that serializes {@link Enum} instances as CQL {@code int}s
26+ * representing their ordinal values as returned by {@link Enum#ordinal()}.
27+ * <p>
28+ * <strong>Note that this codec relies on the enum constants declaration order;
29+ * it is therefore vital that this order remains immutable.</strong>
30+ *
31+ * @param <E> The Enum class this codec serializes from and deserializes to.
32+ */
33+public class EnumOrdinalCodec<E extends Enum<E>> extends TypeCodec<E> {
34+
35+ private final E[] enumConstants;
36+
37+ private final TypeCodec<Integer> innerCodec;
38+
39+ public EnumOrdinalCodec(Class<E> enumClass) {
40+ this(TypeCodec.cint(), enumClass);
41+ }
42+
43+ public EnumOrdinalCodec(TypeCodec<Integer> innerCodec, Class<E> enumClass) {
44+ super(innerCodec.getCqlType(), enumClass);
45+ this.enumConstants = enumClass.getEnumConstants();
46+ this.innerCodec = innerCodec;
47+ }
48+
49+ @Override
50+ public ByteBuffer serialize(E value, ProtocolVersion protocolVersion) throws InvalidTypeException {
51+ return innerCodec.serialize(value == null ? null : value.ordinal(), protocolVersion);
52+ }
53+
54+ @Override
55+ public E deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
56+ Integer ordinal = innerCodec.deserialize(bytes, protocolVersion);
57+ if (ordinal == null)
58+ return null;
59+ return enumConstants[ordinal];
60+ }
61+
62+ @Override
63+ public E parse(String value) throws InvalidTypeException {
64+ return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : enumConstants[Integer.parseInt(value)];
65+ }
66+
67+ @Override
68+ public String format(E value) throws InvalidTypeException {
69+ if (value == null)
70+ return "NULL";
71+ return Integer.toString(value.ordinal());
72+ }
73+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/enums/package-info.java +22 −0
@@ -0,0 +1,22 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+/**
18+ * This package contains a collection of convenience
19+ * {@link com.datastax.driver.core.TypeCodec TypeCodec} instances useful for
20+ * serializing between CQL types and Java enums.
21+ */
22+package com.datastax.driver.extras.codecs.enums;
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/guava/OptionalCodec.java +72 −0
@@ -0,0 +1,72 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.guava;
17+
18+import java.util.Collection;
19+import java.util.Map;
20+
21+import com.google.common.base.Optional;
22+import com.google.common.base.Predicate;
23+import com.google.common.reflect.TypeParameter;
24+import com.google.common.reflect.TypeToken;
25+
26+import com.datastax.driver.core.TypeCodec;
27+import com.datastax.driver.extras.codecs.MappingCodec;
28+
29+/**
30+ * A codec that wraps other codecs around Guava's {@link Optional} API.
31+ *
32+ * @param <T> The wrapped Java type
33+ */
34+public class OptionalCodec<T> extends MappingCodec<Optional<T>, T> {
35+
36+ private final Predicate<T> isAbsent;
37+
38+ public OptionalCodec(TypeCodec<T> codec) {
39+ this(codec, new Predicate<T>() {
40+ @Override
41+ public boolean apply(T input) {
42+ return input == null
43+ || input instanceof Collection && ((Collection)input).isEmpty()
44+ || input instanceof Map && ((Map)input).isEmpty();
45+ }
46+ });
47+ }
48+
49+ public OptionalCodec(TypeCodec<T> codec, Predicate<T> isAbsent) {
50+ super(codec, new TypeToken<Optional<T>>(){}.where(new TypeParameter<T>(){}, codec.getJavaType()));
51+ this.isAbsent = isAbsent;
52+ }
53+
54+ @Override
55+ protected Optional<T> deserialize(T value) {
56+ return isAbsent(value) ? Optional.<T>absent() : Optional.fromNullable(value);
57+ }
58+
59+ @Override
60+ protected T serialize(Optional<T> value) {
61+ return value.isPresent() ? value.get() : absentValue();
62+ }
63+
64+ protected T absentValue() {
65+ return null;
66+ }
67+
68+ protected boolean isAbsent(T value) {
69+ return isAbsent.apply(value);
70+ }
71+
72+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/guava/package-info.java +25 −0
@@ -0,0 +1,25 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+/**
18+ * This package contains a collection of convenience
19+ * {@link com.datastax.driver.core.TypeCodec TypeCodec} instances useful for
20+ * serializing between CQL types and Guava-specific Java types.
21+ *
22+ * Currently only {@link com.datastax.driver.extras.codecs.guava.OptionalCodec OptionalCodec}
23+ * is provided.
24+ */
25+package com.datastax.driver.extras.codecs.guava;
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/InstantCodec.java +135 −0
@@ -0,0 +1,135 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.nio.ByteBuffer;
19+import java.time.Instant;
20+import java.time.format.DateTimeFormatter;
21+import java.time.format.DateTimeFormatterBuilder;
22+import java.time.format.DateTimeParseException;
23+import java.util.Date;
24+
25+import static java.lang.Long.parseLong;
26+import static java.time.Instant.ofEpochMilli;
27+import static java.time.ZoneOffset.UTC;
28+import static java.time.temporal.ChronoField.HOUR_OF_DAY;
29+import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
30+import static java.time.temporal.ChronoField.NANO_OF_SECOND;
31+import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
32+
33+import com.datastax.driver.core.DataType;
34+import com.datastax.driver.core.ProtocolVersion;
35+import com.datastax.driver.core.TypeCodec;
36+import com.datastax.driver.core.exceptions.InvalidTypeException;
37+
38+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
39+import static com.datastax.driver.core.ParseUtils.isQuoted;
40+import static com.datastax.driver.core.ParseUtils.quote;
41+import static com.datastax.driver.core.ParseUtils.unquote;
42+
43+/**
44+ * <p>
45+ * {@link TypeCodec} that maps {@link Instant} <-> {@link Date}
46+ * allowing the setting and retrieval of <code>timestamp</code>
47+ * columns as {@link Instant} instances.
48+ * </p>
49+ *
50+ * <p>
51+ * Since C* <code>timestamp</code> columns do not preserve timezones
52+ * any attached timezone information will be lost.
53+ * </p>
54+ *
55+ * @see ZonedDateTimeCodec
56+ * @see "https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps"
57+ */
58+public class InstantCodec extends TypeCodec<Instant> {
59+
60+ public static final InstantCodec instance = new InstantCodec();
61+
62+ /**
63+ * A {@link DateTimeFormatter} that parses (most) of
64+ * the ISO formats accepted in CQL.
65+ */
66+ private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
67+ .parseCaseSensitive()
68+ .parseStrict()
69+ .append(DateTimeFormatter.ISO_LOCAL_DATE)
70+ .optionalStart()
71+ .appendLiteral('T')
72+ .appendValue(HOUR_OF_DAY, 2)
73+ .appendLiteral(':')
74+ .appendValue(MINUTE_OF_HOUR, 2)
75+ .optionalEnd()
76+ .optionalStart()
77+ .appendLiteral(':')
78+ .appendValue(SECOND_OF_MINUTE, 2)
79+ .optionalEnd()
80+ .optionalStart()
81+ .appendFraction(NANO_OF_SECOND, 0, 9, true)
82+ .optionalEnd()
83+ .optionalStart()
84+ .appendZoneId()
85+ .optionalEnd()
86+ .toFormatter()
87+ .withZone(UTC);
88+
89+ private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
90+ .withZone(UTC);
91+
92+
93+ private InstantCodec() {
94+ super(DataType.timestamp(), Instant.class);
95+ }
96+
97+ @Override
98+ public ByteBuffer serialize(Instant value, ProtocolVersion protocolVersion) {
99+ return value == null ? null : bigint().serializeNoBoxing(value.toEpochMilli(), protocolVersion);
100+ }
101+
102+ @Override
103+ public Instant deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
104+ return bytes == null || bytes.remaining() == 0 ? null : ofEpochMilli(bigint().deserializeNoBoxing(bytes, protocolVersion));
105+ }
106+
107+ @Override
108+ public String format(Instant value) {
109+ if (value == null)
110+ return "NULL";
111+ return quote(FORMATTER.format(value));
112+ }
113+
114+ @Override
115+ public Instant parse(String value) {
116+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
117+ return null;
118+ // strip enclosing single quotes, if any
119+ if (isQuoted(value))
120+ value = unquote(value);
121+ if (isLongLiteral(value)) {
122+ try {
123+ return ofEpochMilli(parseLong(value));
124+ } catch (NumberFormatException e) {
125+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value));
126+ }
127+ }
128+ try {
129+ return Instant.from(PARSER.parse(value));
130+ } catch (DateTimeParseException e) {
131+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value));
132+ }
133+ }
134+
135+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/LocalDateCodec.java +108 −0
@@ -0,0 +1,108 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.nio.ByteBuffer;
19+import java.time.LocalDate;
20+import java.time.temporal.ChronoUnit;
21+
22+import static java.lang.Long.parseLong;
23+import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;
24+
25+import com.datastax.driver.core.*;
26+import com.datastax.driver.core.exceptions.InvalidTypeException;
27+
28+import static com.datastax.driver.core.CodecUtils.fromCqlDateToDaysSinceEpoch;
29+import static com.datastax.driver.core.CodecUtils.fromSignedToUnsignedInt;
30+import static com.datastax.driver.core.CodecUtils.fromUnsignedToSignedInt;
31+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
32+import static com.datastax.driver.core.ParseUtils.isQuoted;
33+import static com.datastax.driver.core.ParseUtils.quote;
34+import static com.datastax.driver.core.ParseUtils.unquote;
35+
36+/**
37+ * {@link TypeCodec} that maps
38+ * {@link java.time.LocalDate} to CQL <code>date</code> columns.
39+ */
40+public class LocalDateCodec extends TypeCodec<LocalDate> {
41+
42+ public static final LocalDateCodec instance = new LocalDateCodec();
43+
44+ private static final LocalDate EPOCH = LocalDate.of(1970, 1, 1);
45+
46+ private LocalDateCodec() {
47+ super(DataType.date(), LocalDate.class);
48+ }
49+
50+ @Override
51+ public ByteBuffer serialize(LocalDate value, ProtocolVersion protocolVersion) {
52+ if (value == null)
53+ return null;
54+ long days = ChronoUnit.DAYS.between(EPOCH, value);
55+ int unsigned = fromSignedToUnsignedInt((int) days);
56+ return cint().serializeNoBoxing(unsigned, protocolVersion);
57+ }
58+
59+ @Override
60+ public LocalDate deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
61+ if (bytes == null || bytes.remaining() == 0)
62+ return null;
63+ int unsigned = cint().deserializeNoBoxing(bytes, protocolVersion);
64+ int signed = fromUnsignedToSignedInt(unsigned);
65+ return EPOCH.plusDays(signed);
66+ }
67+
68+ @Override
69+ public String format(LocalDate value) {
70+ if (value == null)
71+ return "NULL";
72+ return quote(ISO_LOCAL_DATE.format(value));
73+ }
74+
75+ @Override
76+ public LocalDate parse(String value) {
77+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
78+ return null;
79+
80+ // single quotes are optional for long literals, mandatory for date patterns
81+ // strip enclosing single quotes, if any
82+ if (isQuoted(value))
83+ value = unquote(value);
84+
85+ if (isLongLiteral(value)) {
86+ long raw;
87+ try {
88+ raw = parseLong(value);
89+ } catch (NumberFormatException e) {
90+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
91+ }
92+ int days;
93+ try {
94+ days = fromCqlDateToDaysSinceEpoch(raw);
95+ } catch (IllegalArgumentException e) {
96+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
97+ }
98+ return EPOCH.plusDays(days);
99+ }
100+
101+ try {
102+ return LocalDate.parse(value, ISO_LOCAL_DATE);
103+ } catch (RuntimeException e) {
104+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
105+ }
106+ }
107+
108+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodec.java +94 −0
@@ -0,0 +1,94 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.nio.ByteBuffer;
19+import java.time.LocalTime;
20+import java.time.format.DateTimeFormatter;
21+
22+import com.datastax.driver.core.DataType;
23+import com.datastax.driver.core.ParseUtils;
24+import com.datastax.driver.core.ProtocolVersion;
25+import com.datastax.driver.core.TypeCodec;
26+import com.datastax.driver.core.exceptions.InvalidTypeException;
27+
28+import static com.datastax.driver.core.ParseUtils.quote;
29+
30+/**
31+ * {@link TypeCodec} that maps {@link LocalTime} <-> CQL time (long representing nanoseconds since midnight)
32+ * allowing the setting and retrieval of <code>time</code> columns as {@link LocalTime}
33+ * instances.
34+ */
35+public class LocalTimeCodec extends TypeCodec<LocalTime> {
36+
37+ public static final LocalTimeCodec instance = new LocalTimeCodec();
38+
39+ private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
40+
41+ private LocalTimeCodec() {
42+ super(DataType.time(), LocalTime.class);
43+ }
44+
45+ @Override
46+ public ByteBuffer serialize(LocalTime value, ProtocolVersion protocolVersion) throws InvalidTypeException {
47+ if (value == null)
48+ return null;
49+ return bigint().serializeNoBoxing(value.toNanoOfDay(), protocolVersion);
50+ }
51+
52+ @Override
53+ public LocalTime deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
54+ if (bytes == null || bytes.remaining() == 0)
55+ return null;
56+ long nanosOfDay = bigint().deserializeNoBoxing(bytes, protocolVersion);
57+ return LocalTime.ofNanoOfDay(nanosOfDay);
58+ }
59+
60+ @Override
61+ public String format(LocalTime value) {
62+ if (value == null)
63+ return "NULL";
64+ return quote(FORMATTER.format(value));
65+ }
66+
67+ @Override
68+ public LocalTime parse(String value) {
69+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
70+ return null;
71+
72+ // enclosing single quotes required, even for long literals
73+ if (!ParseUtils.isQuoted(value))
74+ throw new InvalidTypeException("time values must be enclosed by single quotes");
75+ value = value.substring(1, value.length() - 1);
76+
77+ if (ParseUtils.isLongLiteral(value)) {
78+ long nanosOfDay;
79+ try {
80+ nanosOfDay = Long.parseLong(value);
81+ } catch (NumberFormatException e) {
82+ throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e);
83+ }
84+ return LocalTime.ofNanoOfDay(nanosOfDay);
85+ }
86+
87+ try {
88+ return LocalTime.parse(value);
89+ } catch (RuntimeException e) {
90+ throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e);
91+ }
92+ }
93+
94+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodec.java +73 −0
@@ -0,0 +1,73 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.util.Collection;
19+import java.util.Map;
20+import java.util.Optional;
21+import java.util.function.Predicate;
22+
23+import com.google.common.reflect.TypeParameter;
24+import com.google.common.reflect.TypeToken;
25+
26+import com.datastax.driver.core.TypeCodec;
27+import com.datastax.driver.extras.codecs.MappingCodec;
28+
29+/**
30+ * A codec that wraps other codecs around JDK 8's {@link Optional} API.
31+ *
32+ * @param <T> The wrapped Java type
33+ */
34+public class OptionalCodec<T> extends MappingCodec<Optional<T>, T> {
35+
36+ private final Predicate<T> isAbsent;
37+
38+ public OptionalCodec(TypeCodec<T> codec) {
39+ this(codec, new Predicate<T>() {
40+ @Override
41+ public boolean test(T input) {
42+ return input == null
43+ || input instanceof Collection && ((Collection)input).isEmpty()
44+ || input instanceof Map && ((Map)input).isEmpty();
45+
46+ }
47+ });
48+ }
49+
50+ public OptionalCodec(TypeCodec<T> codec, Predicate<T> isAbsent) {
51+ super(codec, new TypeToken<Optional<T>>(){}.where(new TypeParameter<T>(){}, codec.getJavaType()));
52+ this.isAbsent = isAbsent;
53+ }
54+
55+ @Override
56+ protected Optional<T> deserialize(T value) {
57+ return isAbsent(value) ? Optional.<T>empty() : Optional.of(value);
58+ }
59+
60+ @Override
61+ protected T serialize(Optional<T> value) {
62+ return value.isPresent() ? value.get() : absentValue();
63+ }
64+
65+ protected T absentValue() {
66+ return null;
67+ }
68+
69+ protected boolean isAbsent(T value) {
70+ return isAbsent.test(value);
71+ }
72+
73+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodec.java +164 −0
@@ -0,0 +1,164 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.nio.ByteBuffer;
19+import java.time.Instant;
20+import java.time.ZoneId;
21+import java.time.ZoneOffset;
22+import java.time.ZonedDateTime;
23+import java.time.format.DateTimeFormatter;
24+import java.time.format.DateTimeFormatterBuilder;
25+import java.time.format.DateTimeParseException;
26+import java.util.List;
27+
28+import static java.time.temporal.ChronoField.HOUR_OF_DAY;
29+import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
30+import static java.time.temporal.ChronoField.NANO_OF_SECOND;
31+import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
32+
33+import static com.google.common.base.Preconditions.checkArgument;
34+
35+import com.datastax.driver.core.*;
36+import com.datastax.driver.core.exceptions.InvalidTypeException;
37+
38+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
39+import static com.datastax.driver.core.ParseUtils.quote;
40+
41+/**
42+ * <p>
43+ * {@link TypeCodec} that maps
44+ * {@link ZonedDateTime} <-> <code>tuple&lt;timestamp,varchar&gt;</code>
45+ * providing a pattern for maintaining timezone information in
46+ * Cassandra.
47+ *
48+ * <p>
49+ * Since Cassandra's <code>timestamp</code> type preserves only
50+ * milliseconds since epoch, any timezone information
51+ * would normally be lost. By using a
52+ * <code>tuple&lt;timestamp,varchar&gt;</code> a timezone ID can be
53+ * persisted in the <code>varchar</code> field such that when the
54+ * value is deserialized the timezone is
55+ * preserved.
56+ */
57+public class ZonedDateTimeCodec extends TypeCodec.AbstractTupleCodec<ZonedDateTime> {
58+
59+ /**
60+ * A {@link DateTimeFormatter} that parses (most) of
61+ * the ISO formats accepted in CQL.
62+ */
63+ private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
64+ .parseCaseSensitive()
65+ .parseStrict()
66+ .append(DateTimeFormatter.ISO_LOCAL_DATE)
67+ .optionalStart()
68+ .appendLiteral('T')
69+ .appendValue(HOUR_OF_DAY, 2)
70+ .appendLiteral(':')
71+ .appendValue(MINUTE_OF_HOUR, 2)
72+ .optionalEnd()
73+ .optionalStart()
74+ .appendLiteral(':')
75+ .appendValue(SECOND_OF_MINUTE, 2)
76+ .optionalEnd()
77+ .optionalStart()
78+ .appendFraction(NANO_OF_SECOND, 0, 9, true)
79+ .optionalEnd()
80+ .optionalStart()
81+ .appendZoneOrOffsetId()
82+ .optionalEnd()
83+ .toFormatter()
84+ .withZone(ZoneOffset.UTC);
85+
86+ private static final DateTimeFormatter ZONE_FORMATTER = DateTimeFormatter.ofPattern("xxx");
87+
88+ public ZonedDateTimeCodec(TupleType tupleType) {
89+ super(tupleType, ZonedDateTime.class);
90+ List<DataType> types = tupleType.getComponentTypes();
91+ checkArgument(
92+ types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()),
93+ "Expected tuple<timestamp,varchar>, got %s",
94+ tupleType);
95+ }
96+
97+ @Override
98+ protected ZonedDateTime newInstance() {
99+ return null;
100+ }
101+
102+ @Override
103+ protected ByteBuffer serializeField(ZonedDateTime source, int index, ProtocolVersion protocolVersion) {
104+ if(index == 0) {
105+ long millis = source.toInstant().toEpochMilli();
106+ return bigint().serializeNoBoxing(millis, protocolVersion);
107+ }
108+ if(index == 1) {
109+ return varchar().serialize(ZONE_FORMATTER.format(source.getOffset()), protocolVersion);
110+ }
111+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
112+ }
113+
114+ @Override
115+ protected ZonedDateTime deserializeAndSetField(ByteBuffer input, ZonedDateTime target, int index, ProtocolVersion protocolVersion) {
116+ if(index == 0) {
117+ long millis = bigint().deserializeNoBoxing(input, protocolVersion);
118+ return Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC);
119+ }
120+ if(index == 1) {
121+ String zoneId = varchar().deserialize(input, protocolVersion);
122+ return target.withZoneSameInstant(ZoneId.of(zoneId));
123+ }
124+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
125+ }
126+
127+ @Override
128+ protected String formatField(ZonedDateTime value, int index) {
129+ if(index == 0) {
130+ return quote(FORMATTER.format(value));
131+ }
132+ if(index == 1) {
133+ return quote(ZONE_FORMATTER.format(value.getOffset()));
134+ }
135+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
136+ }
137+
138+ @Override
139+ protected ZonedDateTime parseAndSetField(String input, ZonedDateTime target, int index) {
140+ if(index == 0) {
141+ // strip enclosing single quotes, if any
142+ if (ParseUtils.isQuoted(input))
143+ input = ParseUtils.unquote(input);
144+ if (isLongLiteral(input)) {
145+ try {
146+ long millis = Long.parseLong(input);
147+ return ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneOffset.UTC);
148+ } catch (NumberFormatException e) {
149+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", input));
150+ }
151+ }
152+ try {
153+ return ZonedDateTime.from(FORMATTER.parse(input));
154+ } catch (DateTimeParseException e) {
155+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", target));
156+ }
157+ }
158+ if(index == 1) {
159+ String zoneId = varchar().parse(input);
160+ return target.withZoneSameInstant(ZoneId.of(zoneId));
161+ }
162+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
163+ }
164+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/package-info.java +61 −0
@@ -0,0 +1,61 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+/**
18+ * This package contains a collection of convenience
19+ * {@link com.datastax.driver.core.TypeCodec TypeCodec} instances useful for
20+ * serializing between CQL types and JDK 8 types, such as the ones from the
21+ * {@code java.time} API and {@link java.util.Optional}.
22+ * <p>
23+ * The codecs in this class provide the following mappings:
24+ *
25+ * <table summary="Supported Mappings">
26+ * <tr>
27+ * <th>Codec</th>
28+ * <th>CQL type</th>
29+ * <th>JDK 8 type</th>
30+ * </tr>
31+ * <tr>
32+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.OptionalCodec}</td>
33+ * <td>Any</td>
34+ * <td>{@link java.util.Optional Optional}</td>
35+ * </tr>
36+ * <tr>
37+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.LocalTimeCodec}</td>
38+ * <td>{@link com.datastax.driver.core.DataType#time() time}</td>
39+ * <td>{@link java.time.LocalTime LocalTime}</td>
40+ * </tr>
41+ * <tr>
42+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.LocalDateCodec}</td>
43+ * <td>{@link com.datastax.driver.core.DataType#date() date}</td>
44+ * <td>{@link java.time.LocalDate LocalDate}</td>
45+ * </tr>
46+ * <tr>
47+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.InstantCodec}</td>
48+ * <td>{@link com.datastax.driver.core.DataType#timestamp() timestamp}</td>
49+ * <td>{@link java.time.Instant Instant}</td>
50+ * </tr>
51+ * <tr>
52+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.ZonedDateTimeCodec}</td>
53+ * <td>{@link com.datastax.driver.core.TupleType tuple} of
54+ * ({@link com.datastax.driver.core.DataType#timestamp() timestamp},
55+ * {@link com.datastax.driver.core.DataType#varchar() varchar})</td>
56+ * <td>{@link java.time.ZonedDateTime ZonedDateTime}</td>
57+ * </tr>
58+ * </table>
59+ *
60+ */
61+package com.datastax.driver.extras.codecs.jdk8;
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/DateTimeCodec.java +147 −0
@@ -0,0 +1,147 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.joda;
17+
18+import java.nio.ByteBuffer;
19+import java.util.List;
20+
21+import org.joda.time.DateTime;
22+import org.joda.time.DateTimeZone;
23+import org.joda.time.format.DateTimeFormat;
24+import org.joda.time.format.DateTimeFormatter;
25+import org.joda.time.format.DateTimeFormatterBuilder;
26+import org.joda.time.format.ISODateTimeFormat;
27+
28+import static com.google.common.base.Preconditions.checkArgument;
29+import static org.joda.time.DateTimeZone.UTC;
30+
31+import com.datastax.driver.core.*;
32+import com.datastax.driver.core.exceptions.InvalidTypeException;
33+
34+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
35+import static com.datastax.driver.core.ParseUtils.quote;
36+
37+/**
38+ * <p>
39+ * {@link TypeCodec} that maps
40+ * {@link DateTime} <-> <code>tuple&lt;timestamp,varchar&gt;</code>
41+ * providing a pattern for maintaining timezone information in
42+ * Cassandra.
43+ *
44+ * <p>
45+ * Since Cassandra's <code>timestamp</code> type preserves only
46+ * milliseconds since epoch, any timezone information
47+ * would normally be lost. By using a
48+ * <code>tuple&lt;timestamp,varchar&gt;</code> a timezone ID can be
49+ * persisted in the <code>varchar</code> field such that when the
50+ * value is deserialized the timezone is
51+ * preserved.
52+ */
53+public class DateTimeCodec extends TypeCodec.AbstractTupleCodec<DateTime> {
54+
55+ /**
56+ * A {@link DateTimeFormatter} that parses (most) of
57+ * the ISO formats accepted in CQL.
58+ */
59+ private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
60+ .append(ISODateTimeFormat.dateOptionalTimeParser().getParser())
61+ .appendOptional(
62+ new DateTimeFormatterBuilder()
63+ .appendTimeZoneOffset("Z", true, 2, 4)
64+ .toParser())
65+ .toFormatter()
66+ .withZoneUTC();
67+
68+ private static final DateTimeFormatter ZONE_FORMATTER = DateTimeFormat.forPattern("ZZ");
69+
70+ public DateTimeCodec(TupleType tupleType) {
71+ super(tupleType, DateTime.class);
72+ List<DataType> types = tupleType.getComponentTypes();
73+ checkArgument(
74+ types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()),
75+ "Expected tuple<timestamp,varchar>, got %s",
76+ tupleType);
77+ }
78+
79+ @Override
80+ protected DateTime newInstance() {
81+ return null;
82+ }
83+
84+ @Override
85+ protected ByteBuffer serializeField(DateTime source, int index, ProtocolVersion protocolVersion) {
86+ if(index == 0) {
87+ long millis = source.getMillis();
88+ return bigint().serializeNoBoxing(millis, protocolVersion);
89+ }
90+ if(index == 1) {
91+ return varchar().serialize(ZONE_FORMATTER.print(source), protocolVersion);
92+ }
93+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
94+ }
95+
96+ @Override
97+ protected DateTime deserializeAndSetField(ByteBuffer input, DateTime target, int index, ProtocolVersion protocolVersion) {
98+ if(index == 0) {
99+ long millis = bigint().deserializeNoBoxing(input, protocolVersion);
100+ return new DateTime(millis);
101+ }
102+ if(index == 1) {
103+ String zoneId = varchar().deserialize(input, protocolVersion);
104+ return target.withZone(DateTimeZone.forID(zoneId));
105+ }
106+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
107+ }
108+
109+ @Override
110+ protected String formatField(DateTime value, int index) {
111+ if(index == 0) {
112+ return quote(value.withZone(UTC).toString());
113+ }
114+ if(index == 1) {
115+ return quote(ZONE_FORMATTER.print(value));
116+ }
117+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
118+ }
119+
120+ @Override
121+ protected DateTime parseAndSetField(String input, DateTime target, int index) {
122+ if(index == 0) {
123+ // strip enclosing single quotes, if any
124+ if (ParseUtils.isQuoted(input))
125+ input = ParseUtils.unquote(input);
126+ if (isLongLiteral(input)) {
127+ try {
128+ long millis = Long.parseLong(input);
129+ return new DateTime(millis);
130+ } catch (NumberFormatException e) {
131+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", input));
132+ }
133+ }
134+ try {
135+ return FORMATTER.parseDateTime(input);
136+ } catch (RuntimeException e) {
137+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", target));
138+ }
139+ }
140+ if(index == 1) {
141+ String zoneId = varchar().parse(input);
142+ return target.withZone(DateTimeZone.forID(zoneId));
143+ }
144+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
145+ }
146+
147+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/InstantCodec.java +108 −0
@@ -0,0 +1,108 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.joda;
17+
18+import java.nio.ByteBuffer;
19+
20+import static java.lang.Long.parseLong;
21+
22+import org.joda.time.Instant;
23+import org.joda.time.format.DateTimeFormat;
24+import org.joda.time.format.DateTimeFormatter;
25+import org.joda.time.format.DateTimeFormatterBuilder;
26+import org.joda.time.format.ISODateTimeFormat;
27+
28+import com.datastax.driver.core.DataType;
29+import com.datastax.driver.core.ProtocolVersion;
30+import com.datastax.driver.core.TypeCodec;
31+import com.datastax.driver.core.exceptions.InvalidTypeException;
32+
33+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
34+import static com.datastax.driver.core.ParseUtils.isQuoted;
35+import static com.datastax.driver.core.ParseUtils.quote;
36+import static com.datastax.driver.core.ParseUtils.unquote;
37+
38+/**
39+ * {@link TypeCodec} that maps {@link Instant} to CQL <code>timestamp</code>.
40+ *
41+ * @see DateTimeCodec
42+ * @see "https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps"
43+ */
44+public class InstantCodec extends TypeCodec<Instant> {
45+
46+ public static final InstantCodec instance = new InstantCodec();
47+
48+ /**
49+ * A {@link DateTimeFormatter} that parses (most) of
50+ * the ISO formats accepted in CQL.
51+ */
52+ private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
53+ .append(ISODateTimeFormat.dateOptionalTimeParser().getParser())
54+ .appendOptional(
55+ new DateTimeFormatterBuilder()
56+ .appendTimeZoneOffset("Z", true, 2, 4)
57+ .toParser())
58+ .toFormatter()
59+ .withZoneUTC();
60+
61+ private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ").withZoneUTC();
62+
63+ private InstantCodec() {
64+ super(DataType.timestamp(), Instant.class);
65+ }
66+
67+ @Override
68+ public ByteBuffer serialize(Instant value, ProtocolVersion protocolVersion) {
69+ return value == null ? null : bigint().serializeNoBoxing(value.getMillis(), protocolVersion);
70+ }
71+
72+ @Override
73+ public Instant deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
74+ if (bytes == null || bytes.remaining() == 0)
75+ return null;
76+ long millis = bigint().deserializeNoBoxing(bytes, protocolVersion);
77+ return new Instant(millis);
78+ }
79+
80+ @Override
81+ public String format(Instant value) {
82+ if (value == null)
83+ return "NULL";
84+ return quote(FORMATTER.print(value));
85+ }
86+
87+ @Override
88+ public Instant parse(String value) {
89+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
90+ return null;
91+ // strip enclosing single quotes, if any
92+ if (isQuoted(value))
93+ value = unquote(value);
94+ if (isLongLiteral(value)) {
95+ try {
96+ return new Instant(parseLong(value));
97+ } catch (NumberFormatException e) {
98+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value));
99+ }
100+ }
101+ try {
102+ return new Instant(PARSER.parseMillis(value));
103+ } catch (RuntimeException e) {
104+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value));
105+ }
106+ }
107+
108+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/LocalDateCodec.java +115 −0
@@ -0,0 +1,115 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.joda;
17+
18+import java.nio.ByteBuffer;
19+
20+import static java.lang.Long.parseLong;
21+
22+import org.joda.time.Days;
23+import org.joda.time.LocalDate;
24+import org.joda.time.format.DateTimeFormat;
25+import org.joda.time.format.DateTimeFormatter;
26+
27+import static org.joda.time.Days.daysBetween;
28+
29+import com.datastax.driver.core.*;
30+import com.datastax.driver.core.exceptions.InvalidTypeException;
31+
32+import static com.datastax.driver.core.CodecUtils.fromCqlDateToDaysSinceEpoch;
33+import static com.datastax.driver.core.CodecUtils.fromSignedToUnsignedInt;
34+import static com.datastax.driver.core.CodecUtils.fromUnsignedToSignedInt;
35+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
36+import static com.datastax.driver.core.ParseUtils.isQuoted;
37+import static com.datastax.driver.core.ParseUtils.quote;
38+import static com.datastax.driver.core.ParseUtils.unquote;
39+
40+/**
41+ * {@link TypeCodec} that maps
42+ * {@link org.joda.time.LocalDate} to CQL <code>date</code> columns.
43+ */
44+public class LocalDateCodec extends TypeCodec<LocalDate> {
45+
46+ public static final LocalDateCodec instance = new LocalDateCodec();
47+
48+ private static final LocalDate EPOCH = new LocalDate(1970, 1, 1);
49+
50+ private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC();
51+
52+ private LocalDateCodec() {
53+ super(DataType.date(), LocalDate.class);
54+ }
55+
56+ @Override
57+ public ByteBuffer serialize(LocalDate value, ProtocolVersion protocolVersion) {
58+ if (value == null)
59+ return null;
60+ Days days = daysBetween(EPOCH, value);
61+ int unsigned = fromSignedToUnsignedInt(days.getDays());
62+ return cint().serializeNoBoxing(unsigned, protocolVersion);
63+ }
64+
65+ @Override
66+ public LocalDate deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
67+ if (bytes == null || bytes.remaining() == 0)
68+ return null;
69+ int unsigned = cint().deserializeNoBoxing(bytes, protocolVersion);
70+ int signed = fromUnsignedToSignedInt(unsigned);
71+ return EPOCH.plusDays(signed);
72+ }
73+
74+ @Override
75+ public String format(LocalDate value) {
76+ if (value == null)
77+ return "NULL";
78+ return quote(FORMATTER.print(value));
79+ }
80+
81+ @Override
82+ public LocalDate parse(String value) {
83+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
84+ return null;
85+
86+ // single quotes are optional for long literals, mandatory for date patterns
87+ // strip enclosing single quotes, if any
88+ if (isQuoted(value)) {
89+ value = unquote(value);
90+ }
91+
92+ if (isLongLiteral(value)) {
93+ long raw;
94+ try {
95+ raw = parseLong(value);
96+ } catch (NumberFormatException e) {
97+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
98+ }
99+ int days;
100+ try {
101+ days = fromCqlDateToDaysSinceEpoch(raw);
102+ } catch (IllegalArgumentException e) {
103+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
104+ }
105+ return EPOCH.plusDays(days);
106+ }
107+
108+ try {
109+ return LocalDate.parse(value, FORMATTER);
110+ } catch (RuntimeException e) {
111+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
112+ }
113+ }
114+
115+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/LocalTimeCodec.java +103 −0
@@ -0,0 +1,103 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.joda;
17+
18+import java.nio.ByteBuffer;
19+
20+import static java.util.concurrent.TimeUnit.MILLISECONDS;
21+import static java.util.concurrent.TimeUnit.NANOSECONDS;
22+
23+import org.joda.time.LocalTime;
24+import org.joda.time.format.DateTimeFormat;
25+import org.joda.time.format.DateTimeFormatter;
26+
27+import com.datastax.driver.core.DataType;
28+import com.datastax.driver.core.ParseUtils;
29+import com.datastax.driver.core.ProtocolVersion;
30+import com.datastax.driver.core.TypeCodec;
31+import com.datastax.driver.core.exceptions.InvalidTypeException;
32+
33+import static com.datastax.driver.core.ParseUtils.quote;
34+
35+/**
36+ * {@link TypeCodec} that maps {@link LocalTime} <-> CQL time (long representing nanoseconds since midnight)
37+ * allowing the setting and retrieval of <code>time</code> columns as {@link LocalTime}
38+ * instances.
39+ *
40+ * <p>
41+ * IMPORTANT: {@link LocalTime} as millisecond precision; nanoseconds below one millisecond will be lost
42+ * during deserialization.
43+ */
44+public class LocalTimeCodec extends TypeCodec<LocalTime> {
45+
46+ public static final LocalTimeCodec instance = new LocalTimeCodec();
47+
48+ private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("HH:mm:ss.SSS");
49+
50+ private LocalTimeCodec() {
51+ super(DataType.time(), LocalTime.class);
52+ }
53+
54+ @Override
55+ public ByteBuffer serialize(LocalTime value, ProtocolVersion protocolVersion) throws InvalidTypeException {
56+ if (value == null)
57+ return null;
58+ return bigint().serializeNoBoxing(MILLISECONDS.toNanos(value.getMillisOfDay()), protocolVersion);
59+ }
60+
61+ @Override
62+ public LocalTime deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
63+ if (bytes == null || bytes.remaining() == 0)
64+ return null;
65+ long nanosOfDay = bigint().deserializeNoBoxing(bytes, protocolVersion);
66+ return LocalTime.fromMillisOfDay(NANOSECONDS.toMillis(nanosOfDay));
67+ }
68+
69+ @Override
70+ public String format(LocalTime value) {
71+ if (value == null)
72+ return "NULL";
73+ return quote(FORMATTER.print(value));
74+ }
75+
76+ @Override
77+ public LocalTime parse(String value) {
78+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
79+ return null;
80+
81+ // enclosing single quotes required, even for long literals
82+ if (!ParseUtils.isQuoted(value))
83+ throw new InvalidTypeException("time values must be enclosed by single quotes");
84+ value = value.substring(1, value.length() - 1);
85+
86+ if (ParseUtils.isLongLiteral(value)) {
87+ long nanosOfDay;
88+ try {
89+ nanosOfDay = Long.parseLong(value);
90+ } catch (NumberFormatException e) {
91+ throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e);
92+ }
93+ return LocalTime.fromMillisOfDay(NANOSECONDS.toMillis(nanosOfDay));
94+ }
95+
96+ try {
97+ return LocalTime.parse(value);
98+ } catch (RuntimeException e) {
99+ throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e);
100+ }
101+ }
102+
103+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/joda/package-info.java +54 −0
@@ -0,0 +1,54 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+/**
18+ * This package contains a collection of convenience
19+ * {@link com.datastax.driver.core.TypeCodec} instances useful for
20+ * serializing between CQL types and Joda Time types like {@link org.joda.time.DateTime}.
21+ * <p>
22+ * The codecs in this class provide the following mappings:
23+ *
24+ * <table summary="Supported Mappings">
25+ * <tr>
26+ * <th>Codec</th>
27+ * <th>CQL type</th>
28+ * <th>Joda Time</th>
29+ * </tr>
30+ * <tr>
31+ * <td>{@link com.datastax.driver.extras.codecs.joda.LocalTimeCodec}</td>
32+ * <td>{@link com.datastax.driver.core.DataType#time() time}</td>
33+ * <td>{@link org.joda.time.LocalTime LocalTime}</td>
34+ * </tr>
35+ * <tr>
36+ * <td>{@link com.datastax.driver.extras.codecs.joda.LocalDateCodec}</td>
37+ * <td>{@link com.datastax.driver.core.DataType#date() date}</td>
38+ * <td>{@link org.joda.time.LocalDate LocalDate}</td>
39+ * </tr>
40+ * <tr>
41+ * <td>{@link com.datastax.driver.extras.codecs.joda.InstantCodec}</td>
42+ * <td>{@link com.datastax.driver.core.DataType#timestamp() timestamp}</td>
43+ * <td>{@link org.joda.time.Instant Instant}</td>
44+ * </tr>
45+ * <tr>
46+ * <td>{@link com.datastax.driver.extras.codecs.joda.DateTimeCodec}</td>
47+ * <td>{@link com.datastax.driver.core.TupleType tuple} of
48+ * ({@link com.datastax.driver.core.DataType#timestamp() timestamp},
49+ * {@link com.datastax.driver.core.DataType#varchar() varchar})</td>
50+ * <td>{@link org.joda.time.DateTime DateTime}</td>
51+ * </tr>
52+ * </table>
53+ */
54+package com.datastax.driver.extras.codecs.joda;
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodec.java +109 −0
@@ -0,0 +1,109 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.json;
17+
18+import java.io.IOException;
19+import java.nio.ByteBuffer;
20+
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import com.fasterxml.jackson.databind.JavaType;
23+import com.fasterxml.jackson.databind.ObjectMapper;
24+import com.fasterxml.jackson.databind.type.TypeFactory;
25+
26+import com.datastax.driver.core.DataType;
27+import com.datastax.driver.core.ParseUtils;
28+import com.datastax.driver.core.ProtocolVersion;
29+import com.datastax.driver.core.TypeCodec;
30+import com.datastax.driver.core.exceptions.InvalidTypeException;
31+import com.datastax.driver.core.utils.Bytes;
32+
33+/**
34+ * A JSON codec that uses the <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a>
35+ * library to perform serialization and deserialization of JSON objects.
36+ * <p>
37+ * Note that this codec maps a single object to a single JSON structure at a time;
38+ * mapping of arrays or collections to root-level JSON arrays is not supported,
39+ * but such a codec can be easily crafted after this one.
40+ */
41+public class JacksonJsonCodec<T> extends TypeCodec<T> {
42+
43+ private final ObjectMapper objectMapper = new ObjectMapper();
44+
45+ public JacksonJsonCodec(Class<T> javaType) {
46+ super(DataType.varchar(), javaType);
47+ }
48+
49+ @Override
50+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
51+ if (value == null)
52+ return null;
53+ try {
54+ return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
55+ } catch (JsonProcessingException e) {
56+ throw new InvalidTypeException(e.getMessage(), e);
57+ }
58+ }
59+
60+ @Override
61+ @SuppressWarnings("unchecked")
62+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
63+ if (bytes == null)
64+ return null;
65+ try {
66+ return (T)objectMapper.readValue(Bytes.getArray(bytes), toJacksonJavaType());
67+ } catch (IOException e) {
68+ throw new InvalidTypeException(e.getMessage(), e);
69+ }
70+ }
71+
72+ @Override
73+ public String format(T value) throws InvalidTypeException {
74+ if (value == null)
75+ return "NULL";
76+ String json;
77+ try {
78+ json = objectMapper.writeValueAsString(value);
79+ } catch (IOException e) {
80+ throw new InvalidTypeException(e.getMessage(), e);
81+ }
82+ return ParseUtils.quote(json);
83+ }
84+
85+ @Override
86+ @SuppressWarnings("unchecked")
87+ public T parse(String value) throws InvalidTypeException {
88+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
89+ return null;
90+ if (!ParseUtils.isQuoted(value))
91+ throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
92+ String json = ParseUtils.unquote(value);
93+ try {
94+ return (T)objectMapper.readValue(json, toJacksonJavaType());
95+ } catch (IOException e) {
96+ throw new InvalidTypeException(e.getMessage(), e);
97+ }
98+ }
99+
100+ /**
101+ * This method acts as a bridge between Guava's {@link com.google.common.reflect.TypeToken TypeToken} API, which is used
102+ * by the driver, and Jackson's {@link JavaType} API.
103+ * @return A {@link JavaType} instance corresponding to the codec's {@link #getJavaType() Java type}.
104+ */
105+ protected JavaType toJacksonJavaType() {
106+ return TypeFactory.defaultInstance().constructType(getJavaType().getType());
107+ }
108+
109+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodec.java +162 −0
@@ -0,0 +1,162 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.json;
17+
18+import java.io.*;
19+import java.nio.ByteBuffer;
20+import java.util.Map;
21+
22+import javax.json.*;
23+
24+import com.datastax.driver.core.DataType;
25+import com.datastax.driver.core.ParseUtils;
26+import com.datastax.driver.core.ProtocolVersion;
27+import com.datastax.driver.core.TypeCodec;
28+import com.datastax.driver.core.exceptions.InvalidTypeException;
29+import com.datastax.driver.core.utils.Bytes;
30+
31+/**
32+ * A JSON codec that uses the
33+ * <a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a>
34+ * to perform serialization and deserialization of JSON structures.
35+ * <p>
36+ * More specifically, this codec maps an arbitrary {@link JsonStructure} to
37+ * a CQL {@code varchar} column.
38+ * <p>
39+ * Note that this codec handles the Java type {@link JsonStructure}.
40+ * It is therefore required that values are set and retrieved using that exact Java type;
41+ * users should manually downcast to either {@link JsonObject} or {@link JsonArray},
42+ * as in the example below:
43+ * <pre>{@code
44+ *
45+ * // setting values
46+ * JsonObject myObject = ...
47+ * PreparedStatement ps = ...
48+ * // set values using JsonStructure
49+ * BoundStatement bs = ps.bind().set(1, myObject, JsonStructure.class);
50+ *
51+ * // retrieving values
52+ * Row row = session.execute(bs).one();
53+ * // use JsonStructure to retrieve values
54+ * JsonStructure json = row.get(0, JsonStructure.class);
55+ * if (json instanceof JsonObject) {
56+ * myObject = (JsonObject) json;
57+ * ...
58+ * }
59+ * }</pre>
60+ *
61+ */
62+public class Jsr353JsonCodec extends TypeCodec<JsonStructure> {
63+
64+ private final JsonReaderFactory readerFactory;
65+
66+ private final JsonWriterFactory writerFactory;
67+
68+ public Jsr353JsonCodec() {
69+ this(null);
70+ }
71+
72+ public Jsr353JsonCodec(Map<String, ?> config) {
73+ super(DataType.varchar(), JsonStructure.class);
74+ readerFactory = Json.createReaderFactory(config);
75+ writerFactory = Json.createWriterFactory(config);
76+ }
77+
78+ @Override
79+ public ByteBuffer serialize(JsonStructure value, ProtocolVersion protocolVersion) throws InvalidTypeException {
80+ if (value == null)
81+ return null;
82+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
83+ try {
84+ JsonWriter writer = writerFactory.createWriter(baos);
85+ writer.write(value);
86+ return ByteBuffer.wrap(baos.toByteArray());
87+ } catch (JsonException e) {
88+ throw new InvalidTypeException(e.getMessage(), e);
89+ } finally {
90+ try {
91+ baos.close();
92+ } catch (IOException e) {
93+ // cannot happen
94+ throw new InvalidTypeException(e.getMessage(), e);
95+ }
96+ }
97+ }
98+
99+ @Override
100+ @SuppressWarnings("unchecked")
101+ public JsonStructure deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
102+ if (bytes == null)
103+ return null;
104+ ByteArrayInputStream bais = new ByteArrayInputStream(Bytes.getArray(bytes));
105+ try {
106+ JsonReader reader = readerFactory.createReader(bais);
107+ return reader.read();
108+ } catch (JsonException e) {
109+ throw new InvalidTypeException(e.getMessage(), e);
110+ } finally {
111+ try {
112+ bais.close();
113+ } catch (IOException e) {
114+ // cannot happen
115+ throw new InvalidTypeException(e.getMessage(), e);
116+ }
117+ }
118+ }
119+
120+ @Override
121+ public String format(JsonStructure value) throws InvalidTypeException {
122+ if (value == null)
123+ return "NULL";
124+ String json;
125+ StringWriter sw = new StringWriter();
126+ try {
127+ JsonWriter writer = writerFactory.createWriter(sw);
128+ writer.write(value);
129+ json = sw.toString();
130+ } catch (JsonException e) {
131+ throw new InvalidTypeException(e.getMessage(), e);
132+ } finally {
133+ try {
134+ sw.close();
135+ } catch (IOException e) {
136+ // cannot happen
137+ throw new InvalidTypeException(e.getMessage(), e);
138+ }
139+ }
140+ return ParseUtils.quote(json);
141+ }
142+
143+ @Override
144+ @SuppressWarnings("unchecked")
145+ public JsonStructure parse(String value) throws InvalidTypeException {
146+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
147+ return null;
148+ if (!ParseUtils.isQuoted(value))
149+ throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
150+ String json = ParseUtils.unquote(value);
151+ StringReader sr = new StringReader(json);
152+ try {
153+ JsonReader reader = readerFactory.createReader(sr);
154+ return reader.read();
155+ } catch (JsonException e) {
156+ throw new InvalidTypeException(e.getMessage(), e);
157+ } finally {
158+ sr.close();
159+ }
160+ }
161+
162+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/package-info.java +46 −0
@@ -0,0 +1,46 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+/**
18+ * This package contains a collection of convenience
19+ * {@link com.datastax.driver.core.TypeCodec} instances useful for
20+ * serializing JSON structures.
21+ * <p>
22+ * The codecs in this class provide support for the following mappings
23+ * and frameworks:
24+ *
25+ * <table summary="Supported Mappings">
26+ * <tr>
27+ * <th>Codec</th>
28+ * <th>CQL type</th>
29+ * <th>Java type</th>
30+ * <th>JSON Framework</th>
31+ * </tr>
32+ * <tr>
33+ * <td>{@link com.datastax.driver.extras.codecs.json.JacksonJsonCodec}</td>
34+ * <td>{@link com.datastax.driver.core.DataType#varchar() varchar}</td>
35+ * <td>Any</td>
36+ * <td><a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a></td>
37+ * </tr>
38+ * <tr>
39+ * <td>{@link com.datastax.driver.extras.codecs.json.Jsr353JsonCodec}</td>
40+ * <td>{@link com.datastax.driver.core.DataType#varchar() varchar}</td>
41+ * <td>{@link javax.json.JsonStructure JsonStructure}</td>
42+ * <td><a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a> (JSR 353)</td>
43+ * </tr>
44+ * </table>
45+ */
46+package com.datastax.driver.extras.codecs.json;
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/arrays/ArrayCodecsTest.java +224 −0
@@ -0,0 +1,224 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.arrays;
17+
18+import java.util.Collection;
19+import java.util.List;
20+
21+import com.google.common.collect.Lists;
22+import com.google.common.primitives.Primitives;
23+import org.testng.annotations.DataProvider;
24+import org.testng.annotations.Test;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+
28+import com.datastax.driver.core.*;
29+import com.datastax.driver.mapping.Mapper;
30+import com.datastax.driver.mapping.MappingManager;
31+import com.datastax.driver.mapping.annotations.Column;
32+import com.datastax.driver.mapping.annotations.PartitionKey;
33+import com.datastax.driver.mapping.annotations.Table;
34+
35+public class ArrayCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
36+
37+ private static final ObjectArrayCodec<String> stringArrayCodec = new ObjectArrayCodec<String>(
38+ DataType.list(DataType.varchar()),
39+ String[].class,
40+ TypeCodec.varchar());
41+
42+ @Override
43+ protected Collection<String> getTableDefinitions() {
44+ return Lists.newArrayList(
45+ "CREATE TABLE lists ("
46+ + "pk int PRIMARY KEY, "
47+ + "l_int list<int>, "
48+ + "l_bigint list<bigint>, "
49+ + "l_float list<float>, "
50+ + "l_double list<double>, "
51+ + "l_string list<text> "
52+ + ")",
53+ "INSERT INTO lists (pk, l_int, l_bigint, l_float, l_double, l_string) VALUES (1, "
54+ + "[1, 2, 3], "
55+ + "[4, 5, 6], "
56+ + "[1.0, 2.0, 3.0], "
57+ + "[4.0, 5.0, 6.0], "
58+ + "['a', 'b', 'c'] "
59+ + ")"
60+ );
61+ }
62+
63+ @Override
64+ protected Cluster.Builder configure(Cluster.Builder builder) {
65+ return builder.withCodecRegistry(
66+ new CodecRegistry()
67+ .register(IntArrayCodec.instance)
68+ .register(LongArrayCodec.instance)
69+ .register(FloatArrayCodec.instance)
70+ .register(DoubleArrayCodec.instance)
71+ .register(stringArrayCodec)
72+ );
73+ }
74+
75+ @DataProvider(name = "ArrayCodecsTest-serializing")
76+ public static Object[][] parametersForSerializationTests() {
77+ return new Object[][]{
78+ { "l_int", int[].class, new int[]{ 1, 2, 3 } },
79+ { "l_bigint", long[].class, new long[]{ 4, 5, 6 } },
80+ { "l_float", float[].class, new float[]{ 1, 2, 3 } },
81+ { "l_double", double[].class, new double[]{ 4, 5, 6 } },
82+ { "l_string", String[].class, new String[]{ "a", "b", "c" } }
83+ };
84+ }
85+
86+ @DataProvider(name = "ArrayCodecsTest-formatting")
87+ public static Object[][] parametersForFormattingTests() {
88+ return new Object[][]{
89+ { new IntArrayCodec(), new int[]{ 1, 2, 3 }, new int[0], "[1,2,3]" },
90+ { new LongArrayCodec(), new long[]{ 4, 5, 6 }, new long[0], "[4,5,6]" },
91+ { new FloatArrayCodec(), new float[]{ 1, 2, 3 }, new float[0], "[1.0,2.0,3.0]" },
92+ { new DoubleArrayCodec(), new double[]{ 4, 5, 6 }, new double[0], "[4.0,5.0,6.0]" },
93+ { stringArrayCodec, new String[]{ "a", "b", "c" }, new String[0], "['a','b','c']" }
94+ };
95+ }
96+
97+ @Test(groups = "short", dataProvider = "ArrayCodecsTest-serializing")
98+ public <A> void should_read_list_column_as_array(String columnName, Class<A> arrayClass, A expected) {
99+ Row row = session.execute(String.format("SELECT %s FROM lists WHERE pk = 1", columnName)).one();
100+ A actual = row.get(columnName, arrayClass);
101+ assertThat(actual).isEqualTo(expected);
102+ }
103+
104+ @Test(groups = "short", dataProvider = "ArrayCodecsTest-serializing")
105+ public <A> void should_set_list_column_with_array(String columnName, Class<A> arrayClass, A expected) {
106+ PreparedStatement ps = session.prepare(String.format("INSERT INTO lists (pk, %s) VALUES (?, ?)", columnName));
107+ BoundStatement bs = ps.bind()
108+ .setInt(0, 2)
109+ .set(columnName, expected, arrayClass);
110+ session.execute(bs);
111+ Row row = session.execute(String.format("SELECT %s FROM lists WHERE pk = 2", columnName)).one();
112+ List<?> list = row.getList(columnName, Primitives.wrap(arrayClass.getComponentType()));
113+ assertThat(list.toArray()).isEqualTo(expected);
114+ }
115+
116+ @Test(groups = "unit", dataProvider = "ArrayCodecsTest-formatting")
117+ public <A> void should_format_array_as_cql_literal(TypeCodec<A> codec, A array, A emptyArray, String cql) {
118+ assertThat(codec.format(array)).isEqualTo(cql);
119+ assertThat(codec.format(emptyArray)).isEqualTo("[]");
120+ assertThat(codec.format(null)).isEqualToIgnoringCase("NULL");
121+ }
122+
123+ @Test(groups = "unit", dataProvider = "ArrayCodecsTest-formatting")
124+ public <A> void should_parse_array_from_cql_literal(TypeCodec<A> codec, A array, A emptyArray, String cql) {
125+ assertThat(codec.parse(cql)).isEqualTo(array);
126+ assertThat(codec.parse("[]")).isEqualTo(emptyArray);
127+ assertThat(codec.parse("NULL")).isNull();
128+ assertThat(codec.parse("")).isNull();
129+ assertThat(codec.parse(null)).isNull();
130+ }
131+
132+ @Test(groups = "short")
133+ public void should_use_mapper_to_store_and_retrieve_values_with_custom_joda_codecs() {
134+ // given
135+ MappingManager manager = new MappingManager(session);
136+ Mapper<Mapped> mapper = manager.mapper(Mapped.class);
137+ // when
138+ Mapped pojo = new Mapped();
139+ mapper.save(pojo);
140+ Mapped actual = mapper.get(42);
141+ // then
142+ assertThat(actual).isEqualToComparingFieldByField(pojo);
143+ }
144+
145+ @SuppressWarnings("unused")
146+ @Table(name = "lists")
147+ public static class Mapped {
148+
149+ @PartitionKey
150+ private int pk;
151+
152+ @Column(name = "l_string")
153+ private String[] strings;
154+
155+ @Column(name = "l_int")
156+ private int[] ints;
157+
158+ @Column(name = "l_bigint")
159+ private long[] longs;
160+
161+ @Column(name = "l_float")
162+ private float[] floats;
163+
164+ @Column(name = "l_double")
165+ private double[] doubles;
166+
167+ public Mapped() {
168+ pk = 42;
169+ strings = new String[]{ "a", "b", "c" };
170+ ints = new int[]{ 1, 2, 3 };
171+ longs = new long[]{ 4, 5, 6 };
172+ floats = new float[]{ 1, 2, 3 };
173+ doubles = new double[]{ 4, 5, 6 };
174+ }
175+
176+ public int getPk() {
177+ return pk;
178+ }
179+
180+ public void setPk(int pk) {
181+ this.pk = pk;
182+ }
183+
184+ public String[] getStrings() {
185+ return strings;
186+ }
187+
188+ public void setStrings(String[] strings) {
189+ this.strings = strings;
190+ }
191+
192+ public int[] getInts() {
193+ return ints;
194+ }
195+
196+ public void setInts(int[] ints) {
197+ this.ints = ints;
198+ }
199+
200+ public long[] getLongs() {
201+ return longs;
202+ }
203+
204+ public void setLongs(long[] longs) {
205+ this.longs = longs;
206+ }
207+
208+ public float[] getFloats() {
209+ return floats;
210+ }
211+
212+ public void setFloats(float[] floats) {
213+ this.floats = floats;
214+ }
215+
216+ public double[] getDoubles() {
217+ return doubles;
218+ }
219+
220+ public void setDoubles(double[] doubles) {
221+ this.doubles = doubles;
222+ }
223+ }
224+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/date/SimpleDateCodecTest.java +76 −0
@@ -0,0 +1,76 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.date;
17+
18+import java.text.ParseException;
19+
20+import static java.util.concurrent.TimeUnit.MILLISECONDS;
21+
22+import org.testng.annotations.DataProvider;
23+import org.testng.annotations.Test;
24+
25+import static com.datastax.driver.core.Assertions.assertThat;
26+import static com.datastax.driver.core.CodecUtils.fromCqlDateToDaysSinceEpoch;
27+import static com.datastax.driver.core.ParseUtils.parseDate;
28+import static com.datastax.driver.core.ProtocolVersion.V4;
29+
30+public class SimpleDateCodecTest {
31+
32+ @DataProvider(name = "SimpleDateCodecTest.parse")
33+ public Object[][] parseParameters() throws ParseException {
34+ int _2014_01_01 = (int)MILLISECONDS.toDays(parseDate("2014-01-01", "yyyy-MM-dd").getTime());
35+ return new Object[][]{
36+ { null , null },
37+ { "" , null },
38+ { "NULL" , null },
39+ { "0" , fromCqlDateToDaysSinceEpoch(0) },
40+ { "'2147483648'" , 0 },
41+ // SimpleDateFormat is unable to parse year -5877641
42+ //{ "'-5877641-06-23'" , fromCqlDateToDaysSinceEpoch(0) },
43+ { "'1970-01-01'" , 0 },
44+ { "'2014-01-01'" , _2014_01_01 }
45+ };
46+ }
47+
48+ @DataProvider(name = "SimpleDateCodecTest.format")
49+ public Object[][] formatParameters() throws ParseException {
50+ int _2014_01_01 = (int)MILLISECONDS.toDays(parseDate("2014-01-01", "yyyy-MM-dd").getTime());
51+ return new Object[][]{
52+ { null , "NULL" },
53+ { fromCqlDateToDaysSinceEpoch(0), "'0'" },
54+ { 0 , "'2147483648'" },
55+ { _2014_01_01 , "'2147499719'" }
56+ };
57+ }
58+
59+ @Test(groups = "unit", dataProvider = "SimpleDateCodecTest.parse")
60+ public void should_parse_valid_formats(String input, Integer expected) {
61+ // when
62+ Integer actual = SimpleDateCodec.instance.parse(input);
63+ // then
64+ assertThat(actual).isEqualTo(expected);
65+ }
66+
67+ @Test(groups = "unit", dataProvider = "SimpleDateCodecTest.format")
68+ public void should_serialize_and_format_valid_object(Integer input, String expected) {
69+ // when
70+ String actual = SimpleDateCodec.instance.format(input);
71+ // then
72+ assertThat(SimpleDateCodec.instance).withProtocolVersion(V4).canSerialize(input);
73+ assertThat(actual).isEqualTo(expected);
74+ }
75+
76+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/date/SimpleDateCodecsTest.java +199 −0
@@ -0,0 +1,199 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.date;
17+
18+import java.util.*;
19+
20+import com.google.common.collect.ImmutableMap;
21+import org.testng.annotations.BeforeClass;
22+import org.testng.annotations.Test;
23+
24+import static com.google.common.collect.Lists.newArrayList;
25+import static org.assertj.core.api.Assertions.assertThat;
26+
27+import com.datastax.driver.core.*;
28+import com.datastax.driver.core.LocalDate;
29+import com.datastax.driver.core.utils.CassandraVersion;
30+import com.datastax.driver.mapping.Mapper;
31+import com.datastax.driver.mapping.MappingManager;
32+import com.datastax.driver.mapping.annotations.Column;
33+import com.datastax.driver.mapping.annotations.PartitionKey;
34+import com.datastax.driver.mapping.annotations.Table;
35+
36+@CassandraVersion(major = 2.2)
37+public class SimpleDateCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
38+
39+ @Override
40+ protected Collection<String> getTableDefinitions() {
41+ return Collections.singletonList(
42+ "CREATE TABLE IF NOT EXISTS foo ("
43+ + "c1 text PRIMARY KEY, "
44+ + "cdate date, "
45+ + "ctimestamp timestamp, "
46+ + "cdates frozen<list<date>>, "
47+ + "ctimestamps frozen<map<text,timestamp>> "
48+ + ")");
49+ }
50+
51+ @BeforeClass(groups = "short")
52+ public void registerCodecs() throws Exception {
53+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
54+ codecRegistry
55+ .register(SimpleDateCodec.instance)
56+ .register(SimpleTimestampCodec.instance);
57+ }
58+
59+
60+ /**
61+ * <p>
62+ * Validates that a <code>date</code> column can be mapped to an int by using
63+ * {@link SimpleDateCodec}.
64+ * </p>
65+ *
66+ * @test_category data_types:serialization
67+ * @expected_result properly maps.
68+ * @since 2.2.0
69+ */
70+ @Test(groups="short")
71+ public void should_map_date_to_days_since_epoch() {
72+ // given
73+ int days = 12345;
74+ LocalDate localDate = LocalDate.fromDaysSinceEpoch(days);
75+ // when
76+ // note: these codecs cannot work with simple statements!
77+ BoundStatement bs = session.prepare("insert into foo (c1, cdate) values (?, ?)").bind("should_map_date_to_days_since_epoch", days);
78+ session.execute(bs);
79+ ResultSet result = session.execute("select cdate from foo where c1=?", "should_map_date_to_days_since_epoch");
80+ // then
81+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
82+ Row row = result.one();
83+ assertThat(row.getInt("cdate")).isEqualTo(days);
84+ assertThat(row.get("cdate", Integer.class)).isEqualTo(days);
85+ assertThat(row.getDate("cdate")).isEqualTo(localDate);
86+ assertThat(row.get("cdate", LocalDate.class)).isEqualTo(localDate);
87+ }
88+
89+ /**
90+ * <p>
91+ * Validates that a <code>timestamp</code> column can be mapped to a long by using
92+ * {@link SimpleTimestampCodec}.
93+ * </p>
94+ *
95+ * @test_category data_types:serialization
96+ * @expected_result properly maps.
97+ * @since 2.2.0
98+ */
99+ @Test(groups="short")
100+ public void should_map_timestamp_to_millis_since_epoch() {
101+ // given
102+ long millis = new Date().getTime();
103+ Date date = new Date(millis);
104+ // when
105+ // note: these codecs cannot work with simple statements!
106+ BoundStatement bs = session.prepare("insert into foo (c1, ctimestamp) values (?, ?)").bind("should_map_timestamp_to_millis_since_epoch", millis);
107+ session.execute(bs);
108+ ResultSet result = session.execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_millis_since_epoch");
109+ // then
110+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
111+ Row row = result.one();
112+ assertThat(row.getLong("ctimestamp")).isEqualTo(millis);
113+ assertThat(row.get("ctimestamp", Long.class)).isEqualTo(millis);
114+ assertThat(row.getTimestamp("ctimestamp")).isEqualTo(date);
115+ assertThat(row.get("ctimestamp", Date.class)).isEqualTo(date);
116+ }
117+
118+ @Test(groups = "short")
119+ public void should_use_mapper_to_store_and_retrieve_values_with_simple_date_codecs() {
120+ // given
121+ MappingManager manager = new MappingManager(session);
122+ Mapper<Mapped> mapper = manager.mapper(Mapped.class);
123+ // when
124+ Mapped pojo = new Mapped();
125+ mapper.save(pojo);
126+ Mapped actual = mapper.get("mapper");
127+ // then
128+ assertThat(actual).isEqualToComparingFieldByField(pojo);
129+ }
130+
131+ @SuppressWarnings("unused")
132+ @Table(name = "foo")
133+ public static class Mapped {
134+
135+ @PartitionKey
136+ private String c1;
137+
138+ @Column(name = "ctimestamp")
139+ private long millis;
140+
141+ @Column(name = "cdate")
142+ private int days;
143+
144+ @Column(name = "ctimestamps")
145+ private Map<String,Long> mapOfMillis;
146+
147+ @Column(name = "cdates")
148+ private List<Integer> listOfDays;
149+
150+ public Mapped(){
151+ c1 = "mapper";
152+ millis = 123456;
153+ days = 123;
154+ mapOfMillis = ImmutableMap.of("foo", 123456L);
155+ listOfDays = newArrayList(123,456);
156+ }
157+
158+ public String getC1() {
159+ return c1;
160+ }
161+
162+ public void setC1(String c1) {
163+ this.c1 = c1;
164+ }
165+
166+ public long getMillis() {
167+ return millis;
168+ }
169+
170+ public void setMillis(long millis) {
171+ this.millis = millis;
172+ }
173+
174+ public int getDays() {
175+ return days;
176+ }
177+
178+ public void setDays(int days) {
179+ this.days = days;
180+ }
181+
182+ public Map<String, Long> getMapOfMillis() {
183+ return mapOfMillis;
184+ }
185+
186+ public void setMapOfMillis(Map<String, Long> mapOfMillis) {
187+ this.mapOfMillis = mapOfMillis;
188+ }
189+
190+ public List<Integer> getListOfDays() {
191+ return listOfDays;
192+ }
193+
194+ public void setListOfDays(List<Integer> listOfDays) {
195+ this.listOfDays = listOfDays;
196+ }
197+ }
198+
199+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/date/SimpleTimestampCodecTest.java +71 −0
@@ -0,0 +1,71 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.date;
17+
18+import java.text.ParseException;
19+
20+import org.testng.annotations.DataProvider;
21+import org.testng.annotations.Test;
22+
23+import static com.datastax.driver.core.Assertions.assertThat;
24+import static com.datastax.driver.core.ParseUtils.parseDate;
25+import static com.datastax.driver.core.ProtocolVersion.V4;
26+
27+public class SimpleTimestampCodecTest {
28+
29+ @DataProvider(name = "SimpleTimestampCodecTest.parse")
30+ public Object[][] parseParameters() throws ParseException {
31+ return new Object[][]{
32+ { null , null },
33+ { "" , null },
34+ { "NULL" , null },
35+ { "0" , 0L },
36+ { "'2010-06-30T01:20'" , parseDate("2010-06-30T01:20:00.000Z").getTime() },
37+ { "'2010-06-30T01:20Z'" , parseDate("2010-06-30T01:20:00.000Z").getTime() },
38+ { "'2010-06-30T01:20:47'" , parseDate("2010-06-30T01:20:47.000Z").getTime() },
39+ { "'2010-06-30T01:20:47+01:00'" , parseDate("2010-06-30T00:20:47.000Z").getTime() },
40+ { "'2010-06-30T01:20:47.999'" , parseDate("2010-06-30T01:20:47.999Z").getTime() },
41+ { "'2010-06-30T01:20:47.999+01:00'" , parseDate("2010-06-30T00:20:47.999Z").getTime() }
42+ };
43+ }
44+
45+ @DataProvider(name = "SimpleTimestampCodecTest.format")
46+ public Object[][] formatParameters() throws ParseException {
47+ return new Object[][]{
48+ { null , "NULL" },
49+ { 0L , "'0'" },
50+ { 123456L, "'123456'" }
51+ };
52+ }
53+
54+ @Test(groups = "unit", dataProvider = "SimpleTimestampCodecTest.parse")
55+ public void should_parse_valid_formats(String input, Long expected) {
56+ // when
57+ Long actual = SimpleTimestampCodec.instance.parse(input);
58+ // then
59+ assertThat(actual).isEqualTo(expected);
60+ }
61+
62+ @Test(groups = "unit", dataProvider = "SimpleTimestampCodecTest.format")
63+ public void should_serialize_and_format_valid_object(Long input, String expected) {
64+ // when
65+ String actual = SimpleTimestampCodec.instance.format(input);
66+ // then
67+ assertThat(SimpleTimestampCodec.instance).withProtocolVersion(V4).canSerialize(input);
68+ assertThat(actual).isEqualTo(expected);
69+ }
70+
71+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/enums/EnumCodecsTest.java +331 −0
@@ -0,0 +1,331 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.enums;
17+
18+import java.util.Collection;
19+import java.util.List;
20+import java.util.Map;
21+import java.util.Set;
22+
23+import com.google.common.collect.ImmutableMap;
24+import com.google.common.reflect.TypeToken;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
27+
28+import static com.google.common.collect.Lists.newArrayList;
29+import static com.google.common.collect.Sets.newHashSet;
30+import static org.assertj.core.api.Assertions.assertThat;
31+
32+import com.datastax.driver.core.*;
33+import com.datastax.driver.core.utils.CassandraVersion;
34+import com.datastax.driver.mapping.Mapper;
35+import com.datastax.driver.mapping.MappingManager;
36+import com.datastax.driver.mapping.annotations.*;
37+
38+import static com.datastax.driver.core.DataType.cint;
39+import static com.datastax.driver.core.DataType.text;
40+import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Bar.BAR_1;
41+import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Bar.BAR_2;
42+import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Foo.FOO_1;
43+import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Foo.FOO_2;
44+
45+/**
46+ * A test that validates that Enums are correctly mapped to varchars (with EnumNameCodec)
47+ * and ints (with EnumOrdinalCodec).
48+ * It also validates that both codecs may coexist in the same CodecRegistry.
49+ */
50+@CassandraVersion(major=2.1)
51+public class EnumCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
52+
53+ private final String insertQuery = "INSERT INTO t1 (pk, foo, foos, bar, bars, foobars, tup, udt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
54+ private final String selectQuery = "SELECT pk, foo, foos, bar, bars, foobars, tup, udt FROM t1 WHERE pk = ?";
55+
56+ private final int pk = 42;
57+
58+ private final List<Foo> foos = newArrayList(FOO_1, FOO_2);
59+ private final Set<Bar> bars = newHashSet(BAR_1, BAR_2);
60+ private final Map<Foo, Bar> foobars = ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2);
61+
62+ private TupleValue tupleValue;
63+ private UDTValue udtValue;
64+
65+ @Override
66+ protected Collection<String> getTableDefinitions() {
67+ return newArrayList(
68+ "CREATE TYPE IF NOT EXISTS udt1 ("
69+ + "foo int,"
70+ + "bar text)",
71+ "CREATE TABLE IF NOT EXISTS t1 ("
72+ + "pk int, "
73+ + "foo int, "
74+ + "foos list<int>, "
75+ + "bar text, "
76+ + "bars set<text>, "
77+ + "foobars map<int,text>, "
78+ + "tup frozen<tuple<int,varchar>>, "
79+ + "udt frozen<udt1>,"
80+ + "primary key (pk, foo))"
81+ );
82+ }
83+
84+ @Override
85+ protected Cluster.Builder configure(Cluster.Builder builder) {
86+ return builder.withCodecRegistry(
87+ new CodecRegistry()
88+ .register(new EnumOrdinalCodec<Foo>(Foo.class))
89+ .register(new EnumNameCodec<Bar>(Bar.class))
90+ );
91+ }
92+
93+ @BeforeMethod(groups="short")
94+ public void before() {
95+ TupleType tup = cluster.getMetadata().newTupleType(cint(), text());
96+ tupleValue = tup.newValue()
97+ .set(0, FOO_1, Foo.class)
98+ .set(1, BAR_1, Bar.class);
99+ UserType udt = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt1");
100+ udtValue = udt.newValue()
101+ .set("foo", FOO_1, Foo.class)
102+ .set("bar", BAR_1, Bar.class);
103+ }
104+
105+ @Test(groups = "short")
106+ public void should_use_enum_codecs_with_simple_statements() {
107+ session.execute(insertQuery, pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue);
108+ ResultSet rows = session.execute(selectQuery, pk);
109+ Row row = rows.one();
110+ assertRow(row);
111+ }
112+
113+ @Test(groups = "short")
114+ public void should_use_enum_codecs_with_prepared_statements_1() {
115+ session.execute(session.prepare(insertQuery).bind(pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue));
116+ PreparedStatement ps = session.prepare(selectQuery);
117+ ResultSet rows = session.execute(ps.bind(pk));
118+ Row row = rows.one();
119+ assertRow(row);
120+ }
121+
122+ @Test(groups = "short")
123+ public void should_use_enum_codecs_with_prepared_statements_2() {
124+ session.execute(session.prepare(insertQuery).bind()
125+ .setInt(0, pk)
126+ .set(1, FOO_1, Foo.class)
127+ .setList(2, foos, Foo.class)
128+ .set(3, BAR_1, Bar.class)
129+ .set(4, bars, new TypeToken<Set<Bar>>(){})
130+ .setMap(5, foobars, Foo.class, Bar.class)
131+ .setTupleValue(6, tupleValue)
132+ .setUDTValue(7, udtValue)
133+ );
134+ PreparedStatement ps = session.prepare(selectQuery);
135+ ResultSet rows = session.execute(ps.bind()
136+ .setInt(0, pk)
137+ );
138+ Row row = rows.one();
139+ assertRow(row);
140+ }
141+
142+ @Test(groups = "short")
143+ public void should_use_mapper_to_store_and_retrieve_nulls_with_enum_codecs() {
144+ // given
145+ MappingManager manager = new MappingManager(session);
146+ Mapper<Mapped> mapper = manager.mapper(Mapped.class);
147+ Mapped pojo = new Mapped();
148+ pojo.pk = 42;
149+ pojo.foo = FOO_1;
150+ // when
151+ mapper.save(pojo);
152+ Mapped actual = mapper.get(42, FOO_1);
153+ // then
154+ assertThat(actual).isEqualToComparingFieldByField(pojo);
155+ }
156+
157+ @Test(groups = "short")
158+ public void should_use_mapper_to_store_and_retrieve_values_with_enum_codecs() {
159+ // given
160+ MappingManager manager = new MappingManager(session);
161+ Mapper<Mapped> mapper = manager.mapper(Mapped.class);
162+ Mapped pojo = new Mapped();
163+ pojo.pk = 42;
164+ pojo.foo = FOO_1;
165+ pojo.bar = BAR_1;
166+ pojo.foos = newArrayList(FOO_2, FOO_1);
167+ pojo.bars = newHashSet(BAR_1, BAR_2);
168+ pojo.foobars = ImmutableMap.of(FOO_1, BAR_2);
169+ // when
170+ mapper.save(pojo);
171+ Mapped actual = mapper.get(42, FOO_1);
172+ // then
173+ assertThat(actual).isEqualToComparingFieldByField(pojo);
174+ }
175+
176+ @Test(groups = "short")
177+ public void should_use_accessor_to_store_and_retrieve_values_with_enum_codecs() {
178+ // given
179+ MappedAccessor accessor = new MappingManager(session).createAccessor(MappedAccessor.class);
180+ Mapped expected = new Mapped();
181+ expected.pk = 42;
182+ expected.foo = FOO_1;
183+ expected.bar = BAR_2;
184+ // when
185+ accessor.insert(42, FOO_1, BAR_2);
186+ Mapped result = accessor.getByFoo(42, FOO_1);
187+ // then
188+ assertThat(result).isEqualToComparingFieldByField(expected);
189+ }
190+
191+ private void assertRow(Row row) {
192+
193+ assertThat(row.getInt(0)).isEqualTo(pk);
194+
195+ assertThat(row.getObject(1)).isEqualTo(FOO_1.ordinal()); // uses the built-in IntCodec because CQL type is int
196+ assertThat(row.getInt("foo")).isEqualTo(FOO_1.ordinal()); // uses the built-in IntCodec
197+ assertThat(row.get(1, Integer.class)).isEqualTo(FOO_1.ordinal()); // forces IntCodec
198+ assertThat(row.get("foo", Foo.class)).isEqualTo(FOO_1); // forces EnumOrdinalCodec
199+
200+ assertThat(row.getObject(2)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal())); // uses the built-in ListCodec(IntCodec) because CQL type is list<int>
201+ assertThat(row.getList(2, Integer.class)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal()));
202+ assertThat(row.getList("foos", Foo.class)).isEqualTo(newArrayList(FOO_1, FOO_2));
203+ assertThat(row.get(2, new TypeToken<List<Integer>>(){})).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal()));
204+ assertThat(row.get("foos", new TypeToken<List<Foo>>(){})).isEqualTo(newArrayList(FOO_1, FOO_2));
205+
206+ assertThat(row.getObject(3)).isEqualTo(BAR_1.name()); // uses the built-in VarcharCodec because CQL type is varchar
207+ assertThat(row.getString("bar")).isEqualTo(BAR_1.name()); // forces VarcharCodec
208+ assertThat(row.get(3, String.class)).isEqualTo(BAR_1.name()); // forces VarcharCodec
209+ assertThat(row.get("bar", Bar.class)).isEqualTo(BAR_1); // forces EnumNameCodec
210+
211+ assertThat(row.getObject(4)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name())); // uses the built-in SetCodec(VarcharCodec) because CQL type is set<varchar>
212+ assertThat(row.getSet(4, String.class)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name()));
213+ assertThat(row.getSet("bars", Bar.class)).isEqualTo(newHashSet(BAR_1, BAR_2));
214+ assertThat(row.get(4, new TypeToken<Set<String>>(){})).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name()));
215+ assertThat(row.get("bars", new TypeToken<Set<Bar>>(){})).isEqualTo(newHashSet(BAR_1, BAR_2));
216+
217+ // uses default built-in codec MapCodec(IntCodec, VarcharCodec) because CQL type is map<int, varchar>
218+ assertThat(row.getObject(5)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
219+
220+ // getMap with combinations of built-in or EnumX codecs
221+ assertThat(row.getMap(5, Integer.class, String.class)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
222+ assertThat(row.getMap(5, Foo.class, String.class)).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name()));
223+ assertThat(row.getMap(5, Integer.class, Bar.class)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2));
224+ assertThat(row.getMap(5, Foo.class, Bar.class)).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2));
225+
226+ // get + TypeToken with combinations of built-in or EnumX codecs
227+ assertThat(row.get("foobars", new TypeToken<Map<Integer, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name()));
228+ assertThat(row.get("foobars", new TypeToken<Map<Foo, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name()));
229+ assertThat(row.get("foobars", new TypeToken<Map<Integer, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2));
230+ assertThat(row.get("foobars", new TypeToken<Map<Foo, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2));
231+
232+ assertThat(row.getTupleValue(6).getInt(0)).isEqualTo(FOO_1.ordinal());
233+ assertThat(row.get(6, TupleValue.class).get(0, Foo.class)).isEqualTo(FOO_1);
234+ assertThat(row.getTupleValue("tup").getString(1)).isEqualTo(BAR_1.name());
235+ assertThat(row.get("tup", TupleValue.class).get(1, Bar.class)).isEqualTo(BAR_1);
236+
237+ assertThat(row.getUDTValue(7).getInt("foo")).isEqualTo(FOO_1.ordinal());
238+ assertThat(row.get(7, UDTValue.class).get("foo", Foo.class)).isEqualTo(FOO_1);
239+ assertThat(row.getUDTValue("udt").getString("bar")).isEqualTo(BAR_1.name());
240+ assertThat(row.get("udt", UDTValue.class).get("bar", Bar.class)).isEqualTo(BAR_1);
241+
242+ }
243+
244+ @SuppressWarnings("unused")
245+ @Table(name = "t1")
246+ public static class Mapped {
247+
248+ @PartitionKey
249+ private int pk;
250+
251+ @ClusteringColumn
252+ private Foo foo;
253+
254+ private List<Foo> foos;
255+
256+ private Bar bar;
257+
258+ private Set<Bar> bars;
259+
260+ private Map<Foo, Bar> foobars;
261+
262+ public int getPk() {
263+ return pk;
264+ }
265+
266+ public void setPk(int pk) {
267+ this.pk = pk;
268+ }
269+
270+ public Foo getFoo() {
271+ return foo;
272+ }
273+
274+ public void setFoo(Foo foo) {
275+ this.foo = foo;
276+ }
277+
278+ public List<Foo> getFoos() {
279+ return foos;
280+ }
281+
282+ public void setFoos(List<Foo> foos) {
283+ this.foos = foos;
284+ }
285+
286+ public Bar getBar() {
287+ return bar;
288+ }
289+
290+ public void setBar(Bar bar) {
291+ this.bar = bar;
292+ }
293+
294+ public Set<Bar> getBars() {
295+ return bars;
296+ }
297+
298+ public void setBars(Set<Bar> bars) {
299+ this.bars = bars;
300+ }
301+
302+ public Map<Foo, Bar> getFoobars() {
303+ return foobars;
304+ }
305+
306+ public void setFoobars(Map<Foo, Bar> foobars) {
307+ this.foobars = foobars;
308+ }
309+ }
310+
311+ @Accessor
312+ public interface MappedAccessor {
313+
314+ @Query("select * from t1 where pk=? and foo=?")
315+ Mapped getByFoo(int pk, Foo foo);
316+
317+ @Query("insert into t1 (pk, foo, bar) values (?,?,?)")
318+ ResultSet insert(int pk, Foo foo, Bar bar);
319+
320+ }
321+
322+
323+ enum Foo {
324+ FOO_1, FOO_2
325+ }
326+
327+ enum Bar {
328+ BAR_1, BAR_2
329+ }
330+
331+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/guava/OptionalCodecTest.java +217 −0
@@ -0,0 +1,217 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.guava;
17+
18+import java.math.BigDecimal;
19+import java.util.Collection;
20+import java.util.Collections;
21+import java.util.List;
22+
23+import com.google.common.base.Optional;
24+import com.google.common.collect.Lists;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
27+
28+import static org.assertj.core.api.Assertions.assertThat;
29+
30+import com.datastax.driver.core.*;
31+import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
32+import com.datastax.driver.core.querybuilder.BuiltStatement;
33+import com.datastax.driver.core.querybuilder.QueryBuilder;
34+import com.datastax.driver.core.utils.CassandraVersion;
35+
36+import static com.datastax.driver.core.TypeCodec.bigint;
37+import static com.datastax.driver.core.TypeCodec.decimal;
38+import static com.datastax.driver.core.TypeCodec.list;
39+import static com.datastax.driver.core.TypeCodec.varchar;
40+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
41+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
42+
43+public class OptionalCodecTest extends PerClassSingleNodeCluster {
44+
45+ private final OptionalCodec<List<String>> optionalCodec = new OptionalCodec<List<String>>(list(varchar()));
46+
47+ private final CodecRegistry registry = new CodecRegistry().register(optionalCodec);
48+
49+ private BuiltStatement insertStmt;
50+
51+ private BuiltStatement selectStmt;
52+
53+ @Override
54+ protected Collection<String> getTableDefinitions() {
55+ return Collections.singletonList("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
56+ }
57+
58+ @Override
59+ protected Cluster.Builder configure(Cluster.Builder builder) {
60+ return builder.withCodecRegistry(registry);
61+ }
62+
63+ @BeforeMethod(groups = "short")
64+ public void createBuiltStatements() throws Exception {
65+ insertStmt = new QueryBuilder(cluster).insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker());
66+ selectStmt = new QueryBuilder(cluster).select("c2", "c3").from("foo").where(eq("c1", bindMarker()));
67+ }
68+
69+ /**
70+ * <p>
71+ * Validates that if a column is unset, that retrieving the value using {@link OptionalCodec} should return
72+ * an {@link Optional#absent()} value. Since CQL Lists can't differentiate between null and empty lists, the
73+ * OptionalCodec should be smart enough to map an empty list to absent.
74+ * </p>
75+ *
76+ * @test_category data_types:serialization
77+ * @expected_result an absent value.
78+ * @jira_ticket JAVA-846
79+ * @since 2.2.0
80+ */
81+ @Test(groups="short")
82+ @CassandraVersion(major=2.2)
83+ public void should_map_unset_value_to_absent() {
84+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
85+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
86+
87+ BoundStatement bs = insertPrep.bind();
88+ bs.setString(0, "should_map_unset_value_to_absent");
89+ bs.setString(1, "1");
90+ session.execute(bs);
91+
92+ ResultSet results = session.execute(selectPrep.bind("should_map_unset_value_to_absent"));
93+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
94+
95+ Row row = results.one();
96+ assertThat(row.getString("c2")).isEqualTo("1");
97+ assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.absent());
98+ }
99+
100+ /**
101+ * <p>
102+ * Validates that if a column is set to {@link Optional#absent()} using {@link OptionalCodec} that it should be
103+ * stored as null and that retrieving it should return {@link Optional#absent()} using {@link OptionalCodec}.
104+ * </p>
105+ *
106+ * @test_category data_types:serialization
107+ * @expected_result an absent value.
108+ * @jira_ticket JAVA-846
109+ * @since 2.2.0
110+ */
111+ @Test(groups="short")
112+ public void should_map_absent_null_value_to_absent() {
113+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
114+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
115+
116+ BoundStatement bs = insertPrep.bind();
117+ bs.setString(0, "should_map_absent_null_value_to_absent");
118+ bs.setString(1, "1");
119+ bs.set(2, Optional.<List<String>>absent(), optionalCodec.getJavaType());
120+ session.execute(bs);
121+
122+ ResultSet results = session.execute(selectPrep.bind("should_map_absent_null_value_to_absent"));
123+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
124+
125+ Row row = results.one();
126+ assertThat(row.getString("c2")).isEqualTo("1");
127+ assertThat(row.getList("c3", String.class)).isEmpty();
128+ assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.absent());
129+ }
130+
131+ /**
132+ * <p>
133+ * Validates that if a column is set to an {@link Optional} value using {@link OptionalCodec} that it should be
134+ * stored as the option's value and that retrieving it should return an {@link Optional} using {@link OptionalCodec}
135+ * and its actual value without using it.
136+ * </p>
137+ *
138+ * @test_category data_types:serialization
139+ * @expected_result The options value is stored appropriately and is retrievable with and without OptionalCodec.
140+ * @jira_ticket JAVA-846
141+ * @since 2.2.0
142+ */
143+ @Test(groups="short")
144+ public void should_map_some_back_to_itself() {
145+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
146+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
147+
148+ List<String> data = Lists.newArrayList("1", "2", "3");
149+
150+ BoundStatement bs = insertPrep.bind();
151+ bs.setString(0, "should_map_some_back_to_itself");
152+ bs.setString(1, "1");
153+ bs.set(2, Optional.of(data), optionalCodec.getJavaType());
154+ session.execute(bs);
155+
156+ ResultSet results = session.execute(selectPrep.bind("should_map_some_back_to_itself"));
157+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
158+
159+ Row row = results.one();
160+ assertThat(row.getString("c2")).isEqualTo("1");
161+
162+ // Ensure data stored correctly.
163+ assertThat(row.getList("c3", String.class)).isEqualTo(data);
164+
165+ // Ensure data retrievable using Option codec.
166+ Optional<List<String>> returnData = row.get("c3", optionalCodec.getJavaType());
167+ assertThat(returnData.isPresent()).isTrue();
168+ assertThat(returnData.get()).isEqualTo(data);
169+ }
170+
171+ @Test(groups="short")
172+ public void should_map_a_primitive_type_to_absent() {
173+ OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigint());
174+ cluster.getConfiguration().getCodecRegistry().register(optionalLongCodec);
175+
176+ PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c4) values (?,?,?)");
177+
178+ BoundStatement bs = stmt.bind();
179+ bs.setString(0, "should_map_a_primitive_type_to_absent");
180+ bs.setString(1, "1");
181+ bs.set(2, Optional.<Long>absent(), optionalLongCodec.getJavaType());
182+ session.execute(bs);
183+
184+ PreparedStatement selectBigint = session.prepare("select c1, c4 from foo where c1=?");
185+ ResultSet results = session.execute(selectBigint.bind("should_map_a_primitive_type_to_absent"));
186+
187+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
188+
189+ Row row = results.one();
190+ assertThat(row.get("c4", optionalLongCodec.getJavaType())).isEqualTo(Optional.<Long>absent());
191+ assertThat(row.getLong("c4")).isEqualTo(0L); // This will return a 0L since it returns the primitive value.
192+ assertThat(row.get("c4", Long.class)).isNull();
193+ }
194+
195+ @Test(groups="short")
196+ public void should_map_a_nullable_type_to_absent() {
197+ OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimal());
198+ cluster.getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
199+
200+ PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c5) values (?,?,?)");
201+
202+ BoundStatement bs = stmt.bind();
203+ bs.setString(0, "should_map_a_nullable_type_to_absent");
204+ bs.setString(1, "1");
205+ bs.set(2, Optional.<BigDecimal>absent(), optionalDecimalCodec.getJavaType());
206+ session.execute(bs);
207+
208+ PreparedStatement selectDecimal = session.prepare("select c1, c5 from foo where c1=?");
209+ ResultSet results = session.execute(selectDecimal.bind("should_map_a_nullable_type_to_absent"));
210+
211+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
212+
213+ Row row = results.one();
214+ assertThat(row.get("c5", optionalDecimalCodec.getJavaType())).isEqualTo(Optional.<BigDecimal>absent());
215+ assertThat(row.getDecimal("c5")).isNull(); // Since BigDecimal is not a primitive it is nullable so expect null.
216+ }
217+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/InstantCodecTest.java +75 −0
@@ -0,0 +1,75 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.Instant;
19+import java.time.ZonedDateTime;
20+
21+import org.testng.annotations.DataProvider;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.Assertions;
27+
28+import static com.datastax.driver.core.ProtocolVersion.V4;
29+
30+public class InstantCodecTest {
31+
32+ @DataProvider(name = "InstantCodecTest.parse")
33+ public Object[][] parseParameters() {
34+ return new Object[][]{
35+ { null , null },
36+ { "" , null },
37+ { "NULL" , null },
38+ { "0" , Instant.ofEpochMilli(0) },
39+ { "1277860847999" , Instant.ofEpochMilli(1277860847999L) },
40+ { "'2010-06-30T01:20'" , Instant.parse("2010-06-30T01:20:00.000Z") },
41+ { "'2010-06-30T01:20Z'" , Instant.parse("2010-06-30T01:20:00.000Z") },
42+ { "'2010-06-30T01:20:47'" , Instant.parse("2010-06-30T01:20:47.000Z") },
43+ { "'2010-06-30T01:20:47+01:00'" , Instant.parse("2010-06-30T00:20:47.000Z") },
44+ { "'2010-06-30T01:20:47.999'" , Instant.parse("2010-06-30T01:20:47.999Z") },
45+ { "'2010-06-30T01:20:47.999+01:00'" , Instant.parse("2010-06-30T00:20:47.999Z") }
46+ };
47+ }
48+
49+ @DataProvider(name = "InstantCodecTest.format")
50+ public Object[][] formatParameters() {
51+ return new Object[][]{
52+ { null , "NULL" },
53+ { Instant.ofEpochMilli(0) , "'1970-01-01T00:00:00.000+00:00'" },
54+ { ZonedDateTime.parse("2010-06-30T02:20:47.999+01:00").toInstant(), "'2010-06-30T01:20:47.999+00:00'" }
55+ };
56+ }
57+
58+ @Test(groups = "unit", dataProvider = "InstantCodecTest.parse")
59+ public void should_parse_valid_formats(String input, Instant expected) {
60+ // when
61+ Instant actual = InstantCodec.instance.parse(input);
62+ // then
63+ assertThat(actual).isEqualTo(expected);
64+ }
65+
66+ @Test(groups = "unit", dataProvider = "InstantCodecTest.format")
67+ public void should_serialize_and_format_valid_object(Instant input, String expected) {
68+ // when
69+ String actual = InstantCodec.instance.format(input);
70+ // then
71+ Assertions.assertThat(InstantCodec.instance).withProtocolVersion(V4).canSerialize(input);
72+ assertThat(actual).isEqualTo(expected);
73+ }
74+
75+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/Jdk8TimeCodecsTest.java +307 −0
@@ -0,0 +1,307 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.Instant;
19+import java.time.LocalDate;
20+import java.time.LocalTime;
21+import java.time.ZonedDateTime;
22+import java.util.*;
23+
24+import com.google.common.collect.ImmutableMap;
25+import org.testng.annotations.BeforeClass;
26+import org.testng.annotations.Test;
27+
28+import static com.google.common.collect.Lists.newArrayList;
29+import static com.google.common.collect.Sets.newHashSet;
30+import static org.assertj.core.api.Assertions.assertThat;
31+
32+import com.datastax.driver.core.*;
33+import com.datastax.driver.core.utils.CassandraVersion;
34+import com.datastax.driver.mapping.Mapper;
35+import com.datastax.driver.mapping.MappingManager;
36+import com.datastax.driver.mapping.annotations.Column;
37+import com.datastax.driver.mapping.annotations.PartitionKey;
38+import com.datastax.driver.mapping.annotations.Table;
39+
40+import static com.datastax.driver.core.DataType.timestamp;
41+import static com.datastax.driver.core.DataType.varchar;
42+
43+@CassandraVersion(major=2.2)
44+public class Jdk8TimeCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
45+
46+ @Override
47+ protected Collection<String> getTableDefinitions() {
48+ return Collections.singletonList(
49+ "CREATE TABLE IF NOT EXISTS foo ("
50+ + "c1 text PRIMARY KEY, "
51+ + "cdate date, "
52+ + "ctime time, "
53+ + "ctimestamp timestamp, "
54+ + "ctuple tuple<timestamp,varchar>, "
55+ + "cdates frozen<list<date>>, "
56+ + "ctimes frozen<set<time>>, "
57+ + "ctimestamps frozen<map<text,timestamp>>, "
58+ + "ctuples frozen<map<tuple<timestamp,varchar>,varchar>>"
59+ + ")");
60+ }
61+
62+ @BeforeClass(groups = "short")
63+ public void registerCodecs() throws Exception {
64+ TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
65+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
66+ codecRegistry
67+ .register(LocalTimeCodec.instance)
68+ .register(LocalDateCodec.instance)
69+ .register(InstantCodec.instance)
70+ .register(new ZonedDateTimeCodec(dateWithTimeZoneType));
71+ }
72+
73+ /**
74+ * <p>
75+ * Validates that a <code>time</code> column can be mapped to a {@link LocalTime} by using
76+ * {@link LocalTimeCodec}.
77+ * </p>
78+ *
79+ * @test_category data_types:serialization
80+ * @expected_result properly maps.
81+ * @jira_ticket JAVA-606
82+ * @since 2.2.0
83+ */
84+ @Test(groups="short")
85+ public void should_map_time_to_localtime() {
86+ // given
87+ LocalTime time = LocalTime.of(12, 16, 34, 999);
88+ // when
89+ session.execute("insert into foo (c1, ctime) values (?, ?)", "should_map_time_to_localtime", time);
90+ ResultSet result = session.execute("select ctime from foo where c1=?", "should_map_time_to_localtime");
91+ // then
92+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
93+ Row row = result.one();
94+ assertThat(row.get("ctime", LocalTime.class)).isEqualTo(time);
95+ assertThat(row.getTime("ctime")).isEqualTo(time.toNanoOfDay());
96+ }
97+
98+ /**
99+ * <p>
100+ * Validates that a <code>date</code> column can be mapped to a {@link LocalDate} by using
101+ * {@link LocalDateCodec}.
102+ * </p>
103+ *
104+ * @test_category data_types:serialization
105+ * @expected_result properly maps.
106+ * @jira_ticket JAVA-606
107+ * @since 2.2.0
108+ */
109+ @Test(groups="short")
110+ public void should_map_date_to_localdate() {
111+ // given
112+ LocalDate localDate = LocalDate.of(2015, 1, 1);
113+ com.datastax.driver.core.LocalDate driverLocalDate = com.datastax.driver.core.LocalDate.fromYearMonthDay(2015, 1, 1);
114+ // when
115+ session.execute("insert into foo (c1, cdate) values (?, ?)", "should_map_date_to_localdate", localDate);
116+ ResultSet result = session.execute("select cdate from foo where c1=?", "should_map_date_to_localdate");
117+ // then
118+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
119+ Row row = result.one();
120+ assertThat(row.get("cdate", LocalDate.class)).isEqualTo(localDate);
121+ assertThat(row.getDate("cdate")).isEqualTo(driverLocalDate);
122+ }
123+
124+ /**
125+ * <p>
126+ * Validates that a <code>timestamp</code> column can be mapped to a {@link Instant} by using
127+ * {@link InstantCodec}.
128+ * </p>
129+ *
130+ * @test_category data_types:serialization
131+ * @expected_result properly maps.
132+ * @jira_ticket JAVA-606
133+ * @since 2.2.0
134+ */
135+ @Test(groups="short")
136+ public void should_map_timestamp_to_instant() {
137+ // given
138+ Instant instant = Instant.parse("2010-06-30T01:20:30Z");
139+ // when
140+ session.execute("insert into foo (c1, ctimestamp) values (?, ?)", "should_map_timestamp_to_instant", instant);
141+ ResultSet result = session.execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_instant");
142+ // then
143+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
144+ Row row = result.one();
145+ assertThat(row.get("ctimestamp", Instant.class)).isEqualTo(instant);
146+ assertThat(row.getTimestamp("ctimestamp")).isEqualTo(Date.from(instant));
147+ }
148+
149+ /**
150+ * <p>
151+ * Validates that a <code>tuple&lt;timestamp,text&gt;</code> column can be mapped to a {@link ZonedDateTime} by using
152+ * {@link ZonedDateTimeCodec}.
153+ * </p>
154+ *
155+ * @test_category data_types:serialization
156+ * @expected_result properly maps.
157+ * @jira_ticket JAVA-606
158+ * @since 2.2.0
159+ */
160+ @Test(groups="short")
161+ public void should_map_tuple_to_zoneddatetime() {
162+ // given
163+ ZonedDateTime expected = ZonedDateTime.parse("2010-06-30T01:20+05:30");
164+ // when
165+ PreparedStatement insertStmt = session.prepare("insert into foo (c1, ctuple) values (?, ?)");
166+ session.execute(insertStmt.bind("should_map_tuple_to_instant", expected));
167+ ResultSet result = session.execute("select ctuple from foo where c1=?", "should_map_tuple_to_instant");
168+ // then
169+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
170+ Row row = result.one();
171+ ZonedDateTime actual = row.get("ctuple", ZonedDateTime.class);
172+ // Since timezone is preserved in the tuple, the date times should match perfectly.
173+ assertThat(actual).isEqualTo(expected);
174+ // Ensure the timezones match as well.
175+ // (This is just a safety check as the previous assert would have failed otherwise).
176+ assertThat(actual.getZone()).isEqualTo(expected.getZone());
177+ }
178+
179+ @Test(groups="short")
180+ public void should_use_mapper_to_store_and_retrieve_values_with_custom_jdk8_codecs() {
181+ // given
182+ MappingManager manager = new MappingManager(session);
183+ Mapper<Mapped> mapper = manager.mapper(Mapped.class);
184+ // when
185+ Mapped pojo = new Mapped();
186+ mapper.save(pojo);
187+ Mapped actual = mapper.get("mapper");
188+ // then
189+ assertThat(actual).isEqualToComparingFieldByField(pojo);
190+ }
191+
192+ @SuppressWarnings("unused")
193+ @Table(name = "foo")
194+ public static class Mapped {
195+
196+ @PartitionKey
197+ private String c1;
198+
199+ @Column(name = "cdate")
200+ private LocalDate date;
201+
202+ @Column(name = "ctime")
203+ private LocalTime time;
204+
205+ @Column(name = "ctimestamp")
206+ private Instant instant;
207+
208+ @Column(name = "ctuple")
209+ private ZonedDateTime zdt;
210+
211+ @Column(name = "cdates")
212+ private List<LocalDate> dates;
213+
214+ @Column(name = "ctimes")
215+ private Set<LocalTime> times;
216+
217+ @Column(name = "ctimestamps")
218+ private Map<String, Instant> instants;
219+
220+ @Column(name = "ctuples")
221+ private Map<ZonedDateTime, String> zdts;
222+
223+ public Mapped() {
224+ c1 = "mapper";
225+ date = LocalDate.parse("2014-01-01");
226+ time = LocalTime.NOON;
227+ instant = Instant.parse("2010-06-30T01:20:47.000Z");
228+ zdt = ZonedDateTime.parse("2010-06-30T01:20:47+05:30");
229+ dates = newArrayList(date);
230+ times = newHashSet(time);
231+ instants = ImmutableMap.of("foo", instant);
232+ zdts = ImmutableMap.of(zdt, "bar");
233+ }
234+
235+ public String getC1() {
236+ return c1;
237+ }
238+
239+ public void setC1(String c1) {
240+ this.c1 = c1;
241+ }
242+
243+ public LocalDate getDate() {
244+ return date;
245+ }
246+
247+ public void setDate(LocalDate date) {
248+ this.date = date;
249+ }
250+
251+ public LocalTime getTime() {
252+ return time;
253+ }
254+
255+ public void setTime(LocalTime time) {
256+ this.time = time;
257+ }
258+
259+ public Instant getInstant() {
260+ return instant;
261+ }
262+
263+ public void setInstant(Instant instant) {
264+ this.instant = instant;
265+ }
266+
267+ public ZonedDateTime getZdt() {
268+ return zdt;
269+ }
270+
271+ public void setZdt(ZonedDateTime zdt) {
272+ this.zdt = zdt;
273+ }
274+
275+ public List<LocalDate> getDates() {
276+ return dates;
277+ }
278+
279+ public void setDates(List<LocalDate> dates) {
280+ this.dates = dates;
281+ }
282+
283+ public Set<LocalTime> getTimes() {
284+ return times;
285+ }
286+
287+ public void setTimes(Set<LocalTime> times) {
288+ this.times = times;
289+ }
290+
291+ public Map<String, Instant> getInstants() {
292+ return instants;
293+ }
294+
295+ public void setInstants(Map<String, Instant> instants) {
296+ this.instants = instants;
297+ }
298+
299+ public Map<ZonedDateTime, String> getZdts() {
300+ return zdts;
301+ }
302+
303+ public void setZdts(Map<ZonedDateTime, String> zdts) {
304+ this.zdts = zdts;
305+ }
306+ }
307+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/LocalDateCodecTest.java +74 −0
@@ -0,0 +1,74 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.LocalDate;
19+
20+import org.testng.annotations.DataProvider;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+
25+import com.datastax.driver.core.Assertions;
26+
27+import static com.datastax.driver.core.ProtocolVersion.V4;
28+
29+public class LocalDateCodecTest {
30+
31+ private static final LocalDate EPOCH = LocalDate.ofEpochDay(0);
32+ private static final LocalDate MIN = LocalDate.parse("-5877641-06-23");
33+
34+ @DataProvider(name = "LocalDateCodecTest.parse")
35+ public Object[][] parseParameters() {
36+ return new Object[][]{
37+ { null , null },
38+ { "" , null },
39+ { "NULL" , null },
40+ { "0" , MIN },
41+ { "'2147483648'" , EPOCH },
42+ { "'-5877641-06-23'" , MIN },
43+ { "'1970-01-01'" , EPOCH },
44+ { "'2014-01-01'" , LocalDate.parse("2014-01-01") }
45+ };
46+ }
47+
48+ @DataProvider(name = "LocalDateCodecTest.format")
49+ public Object[][] formatParameters() {
50+ return new Object[][]{
51+ { null , "NULL" },
52+ { LocalDate.ofEpochDay(0) , "'1970-01-01'" },
53+ { LocalDate.parse("2010-06-30"), "'2010-06-30'" }
54+ };
55+ }
56+
57+ @Test(groups = "unit", dataProvider = "LocalDateCodecTest.parse")
58+ public void should_parse_valid_formats(String input, LocalDate expected) {
59+ // when
60+ LocalDate actual = LocalDateCodec.instance.parse(input);
61+ // then
62+ assertThat(actual).isEqualTo(expected);
63+ }
64+
65+ @Test(groups = "unit", dataProvider = "LocalDateCodecTest.format")
66+ public void should_serialize_and_format_valid_object(LocalDate input, String expected) {
67+ // when
68+ String actual = LocalDateCodec.instance.format(input);
69+ // then
70+ Assertions.assertThat(LocalDateCodec.instance).withProtocolVersion(V4).canSerialize(input);
71+ assertThat(actual).isEqualTo(expected);
72+ }
73+
74+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodecTest.java +74 −0
@@ -0,0 +1,74 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.LocalTime;
19+
20+import org.testng.annotations.DataProvider;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+
25+import com.datastax.driver.core.Assertions;
26+
27+import static com.datastax.driver.core.ParseUtils.quote;
28+import static com.datastax.driver.core.ProtocolVersion.V4;
29+
30+public class LocalTimeCodecTest {
31+
32+ @DataProvider(name = "LocalTimeCodecTest.parse")
33+ public Object[][] parseParameters() {
34+ LocalTime time = LocalTime.parse("13:25:47.123456789");
35+ String nanosOfDay = quote(Long.toString(time.toNanoOfDay()));
36+ return new Object[][]{
37+ { null , null },
38+ { "" , null },
39+ { "NULL" , null },
40+ { nanosOfDay , LocalTime.parse("13:25:47.123456789") },
41+ { "'13:25:47'" , LocalTime.parse("13:25:47") },
42+ { "'13:25:47.123'" , LocalTime.parse("13:25:47.123") },
43+ { "'13:25:47.123456'" , LocalTime.parse("13:25:47.123456") },
44+ { "'13:25:47.123456789'", LocalTime.parse("13:25:47.123456789") }
45+ };
46+ }
47+
48+ @DataProvider(name = "LocalTimeCodecTest.format")
49+ public Object[][] formatParameters() {
50+ return new Object[][]{
51+ { null , "NULL" },
52+ { LocalTime.NOON , "'12:00:00.000'" },
53+ { LocalTime.parse("02:20:47.999999"), "'02:20:47.999'" }
54+ };
55+ }
56+
57+ @Test(groups = "unit", dataProvider = "LocalTimeCodecTest.parse")
58+ public void should_parse_valid_formats(String input, LocalTime expected) {
59+ // when
60+ LocalTime actual = LocalTimeCodec.instance.parse(input);
61+ // then
62+ assertThat(actual).isEqualTo(expected);
63+ }
64+
65+ @Test(groups = "unit", dataProvider = "LocalTimeCodecTest.format")
66+ public void should_serialize_and_format_valid_object(LocalTime input, String expected) {
67+ // when
68+ String actual = LocalTimeCodec.instance.format(input);
69+ // then
70+ Assertions.assertThat(LocalTimeCodec.instance).withProtocolVersion(V4).canSerialize(input);
71+ assertThat(actual).isEqualTo(expected);
72+ }
73+
74+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodecTest.java +218 −0
@@ -0,0 +1,218 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.math.BigDecimal;
19+import java.util.Collection;
20+import java.util.Collections;
21+import java.util.List;
22+import java.util.Optional;
23+
24+import com.google.common.collect.Lists;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
27+
28+import static org.assertj.core.api.Assertions.assertThat;
29+
30+import com.datastax.driver.core.*;
31+import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
32+import com.datastax.driver.core.querybuilder.BuiltStatement;
33+import com.datastax.driver.core.querybuilder.QueryBuilder;
34+import com.datastax.driver.core.utils.CassandraVersion;
35+
36+import static com.datastax.driver.core.TypeCodec.bigint;
37+import static com.datastax.driver.core.TypeCodec.decimal;
38+import static com.datastax.driver.core.TypeCodec.list;
39+import static com.datastax.driver.core.TypeCodec.varchar;
40+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
41+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
42+
43+public class OptionalCodecTest extends PerClassSingleNodeCluster {
44+
45+ private final OptionalCodec<List<String>> optionalCodec = new OptionalCodec<List<String>>(list(varchar()));
46+
47+ private final CodecRegistry registry = new CodecRegistry().register(optionalCodec);
48+
49+ private BuiltStatement insertStmt;
50+
51+ private BuiltStatement selectStmt;
52+
53+ @Override
54+ protected Collection<String> getTableDefinitions() {
55+ return Collections.singletonList("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
56+ }
57+
58+ @Override
59+ protected Cluster.Builder configure(Cluster.Builder builder) {
60+ return builder.withCodecRegistry(registry);
61+ }
62+
63+ @BeforeMethod(groups = "short")
64+ public void createBuiltStatements() throws Exception {
65+ insertStmt = new QueryBuilder(cluster).insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker());
66+ selectStmt = new QueryBuilder(cluster).select("c2", "c3").from("foo").where(eq("c1", bindMarker()));
67+ }
68+
69+ /**
70+ * <p>
71+ * Validates that if a column is unset, that retrieving the value using {@link OptionalCodec} should return
72+ * an {@link Optional#empty()} value. Since CQL Lists can't differentiate between null and empty lists, the
73+ * OptionalCodec should be smart enough to map an empty list to empty.
74+ * </p>
75+ *
76+ * @test_category data_types:serialization
77+ * @expected_result an empty value.
78+ * @jira_ticket JAVA-606
79+ * @since 2.2.0
80+ */
81+ @Test(groups="short")
82+ @CassandraVersion(major=2.2)
83+ public void should_map_unset_value_to_empty() {
84+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
85+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
86+
87+ BoundStatement bs = insertPrep.bind();
88+ bs.setString(0, "should_map_unset_value_to_empty");
89+ bs.setString(1, "1");
90+ session.execute(bs);
91+
92+ ResultSet results = session.execute(selectPrep.bind("should_map_unset_value_to_empty"));
93+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
94+
95+ Row row = results.one();
96+ assertThat(row.getString("c2")).isEqualTo("1");
97+ assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.empty());
98+ }
99+
100+ /**
101+ * <p>
102+ * Validates that if a column is set to {@link Optional#empty()} using {@link OptionalCodec} that it should be
103+ * stored as null and that retrieving it should return {@link Optional#empty()} using {@link OptionalCodec}.
104+ * </p>
105+ *
106+ * @test_category data_types:serialization
107+ * @expected_result an empty value.
108+ * @jira_ticket JAVA-606
109+ * @since 2.2.0
110+ */
111+ @Test(groups="short")
112+ public void should_map_absent_null_value_to_empty() {
113+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
114+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
115+
116+ BoundStatement bs = insertPrep.bind();
117+ bs.setString(0, "should_map_absent_null_value_to_empty");
118+ bs.setString(1, "1");
119+ bs.set(2, Optional.<List<String>>empty(), optionalCodec.getJavaType());
120+ session.execute(bs);
121+
122+ ResultSet results = session.execute(selectPrep.bind("should_map_absent_null_value_to_empty"));
123+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
124+
125+ Row row = results.one();
126+ assertThat(row.getString("c2")).isEqualTo("1");
127+ assertThat(row.getList("c3", String.class)).isEmpty();
128+ assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.empty());
129+ }
130+
131+ /**
132+ * <p>
133+ * Validates that if a column is set to an {@link Optional} value using {@link OptionalCodec} that it should be
134+ * stored as the option's value and that retrieving it should return an {@link Optional} using {@link OptionalCodec}
135+ * and its actual value without using it.
136+ * </p>
137+ *
138+ * @test_category data_types:serialization
139+ * @expected_result The options value is stored appropriately and is retrievable with and without OptionalCodec.
140+ * @jira_ticket JAVA-606
141+ * @since 2.2.0
142+ */
143+ @Test(groups="short")
144+ public void should_map_some_back_to_itself() {
145+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
146+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
147+
148+ List<String> data = Lists.newArrayList("1", "2", "3");
149+
150+ BoundStatement bs = insertPrep.bind();
151+ bs.setString(0, "should_map_some_back_to_itself");
152+ bs.setString(1, "1");
153+ bs.set(2, Optional.of(data), optionalCodec.getJavaType());
154+ session.execute(bs);
155+
156+ ResultSet results = session.execute(selectPrep.bind("should_map_some_back_to_itself"));
157+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
158+
159+ Row row = results.one();
160+ assertThat(row.getString("c2")).isEqualTo("1");
161+
162+ // Ensure data stored correctly.
163+ assertThat(row.getList("c3", String.class)).isEqualTo(data);
164+
165+ // Ensure data retrievable using Option codec.
166+ Optional<List<String>> returnData = row.get("c3", optionalCodec.getJavaType());
167+ assertThat(returnData.isPresent()).isTrue();
168+ assertThat(returnData.get()).isEqualTo(data);
169+ }
170+
171+ @Test(groups="short")
172+ public void should_map_a_primitive_type_to_empty() {
173+ OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigint());
174+ cluster.getConfiguration().getCodecRegistry().register(optionalLongCodec);
175+
176+ PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c4) values (?,?,?)");
177+
178+ BoundStatement bs = stmt.bind();
179+ bs.setString(0, "should_map_a_primitive_type_to_empty");
180+ bs.setString(1, "1");
181+ bs.set(2, Optional.<Long>empty(), optionalLongCodec.getJavaType());
182+ session.execute(bs);
183+
184+ PreparedStatement selectBigint = session.prepare("select c1, c4 from foo where c1=?");
185+ ResultSet results = session.execute(selectBigint.bind("should_map_a_primitive_type_to_empty"));
186+
187+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
188+
189+ Row row = results.one();
190+ assertThat(row.get("c4", optionalLongCodec.getJavaType())).isEqualTo(Optional.<Long>empty());
191+ assertThat(row.getLong("c4")).isEqualTo(0L); // This will return a 0L since it returns the primitive value.
192+ assertThat(row.get("c4", Long.class)).isNull();
193+ }
194+
195+ @Test(groups="short")
196+ public void should_map_a_nullable_type_to_empty() {
197+ OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimal());
198+ cluster.getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
199+
200+ PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c5) values (?,?,?)");
201+
202+ BoundStatement bs = stmt.bind();
203+ bs.setString(0, "should_map_a_nullable_type_to_empty");
204+ bs.setString(1, "1");
205+ bs.set(2, Optional.<BigDecimal>empty(), optionalDecimalCodec.getJavaType());
206+ session.execute(bs);
207+
208+ PreparedStatement selectDecimal = session.prepare("select c1, c5 from foo where c1=?");
209+ ResultSet results = session.execute(selectDecimal.bind("should_map_a_nullable_type_to_empty"));
210+
211+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
212+
213+ Row row = results.one();
214+ assertThat(row.get("c5", optionalDecimalCodec.getJavaType())).isEqualTo(Optional.<BigDecimal>empty());
215+ assertThat(row.getDecimal("c5")).isNull(); // Since BigDecimal is not a primitive it is nullable so expect null.
216+ }
217+
218+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodecTest.java +92 −0
@@ -0,0 +1,92 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.ZoneOffset;
19+import java.time.ZonedDateTime;
20+
21+import static java.time.Instant.ofEpochMilli;
22+import static java.time.Instant.parse;
23+import static java.time.ZoneOffset.UTC;
24+import static java.time.ZonedDateTime.ofInstant;
25+
26+import org.testng.annotations.DataProvider;
27+import org.testng.annotations.Test;
28+
29+import static com.google.common.collect.Lists.newArrayList;
30+import static org.assertj.core.api.Assertions.assertThat;
31+import static org.mockito.Mockito.mock;
32+import static org.mockito.Mockito.when;
33+
34+import com.datastax.driver.core.Assertions;
35+import com.datastax.driver.core.TupleType;
36+
37+import static com.datastax.driver.core.DataType.timestamp;
38+import static com.datastax.driver.core.DataType.varchar;
39+import static com.datastax.driver.core.ProtocolVersion.V4;
40+
41+public class ZonedDateTimeCodecTest {
42+
43+ private final TupleType tupleType = mock(TupleType.class);
44+
45+ @DataProvider(name = "ZonedDateTimeCodecTest.parse")
46+ public Object[][] parseParameters() {
47+ return new Object[][]{
48+ { null , null },
49+ { "" , null },
50+ { "NULL" , null },
51+ { "(0 ,'+01:00')" , ofInstant(ofEpochMilli(0) , ZoneOffset.of("+01:00")) },
52+ { "(1277860847999 ,'+01:00')" , ofInstant(parse("2010-06-30T01:20:47.999Z"), ZoneOffset.of("+01:00")) },
53+ { "('2010-06-30T01:20Z' ,'+01:00')" , ofInstant(parse("2010-06-30T01:20:00.000Z"), ZoneOffset.of("+01:00")) },
54+ { "('2010-06-30T01:20:47Z' ,'+01:00')" , ofInstant(parse("2010-06-30T01:20:47.000Z"), ZoneOffset.of("+01:00")) },
55+ { "('2010-06-30T01:20:47.999Z','+01:00')" , ofInstant(parse("2010-06-30T01:20:47.999Z"), ZoneOffset.of("+01:00")) }
56+ };
57+ }
58+
59+ @DataProvider(name = "ZonedDateTimeCodecTest.format")
60+ public Object[][] formatParameters() {
61+ return new Object[][]{
62+ { null , "NULL" },
63+ { ofInstant(ofEpochMilli(0), UTC) , "('1970-01-01T00:00:00Z','+00:00')" },
64+ { ZonedDateTime.parse("2010-06-30T01:20:47.999+01:00"), "('2010-06-30T00:20:47.999Z','+01:00')" }
65+ };
66+ }
67+
68+ @Test(groups = "unit", dataProvider = "ZonedDateTimeCodecTest.parse")
69+ public void should_parse_valid_formats(String input, ZonedDateTime expected) {
70+ // given
71+ TupleType tupleType = mock(TupleType.class);
72+ when(tupleType.getComponentTypes()).thenReturn(newArrayList(timestamp(), varchar()));
73+ ZonedDateTimeCodec codec = new ZonedDateTimeCodec(tupleType);
74+ // when
75+ ZonedDateTime actual = codec.parse(input);
76+ // then
77+ assertThat(actual).isEqualTo(expected);
78+ }
79+
80+ @Test(groups = "unit", dataProvider = "ZonedDateTimeCodecTest.format")
81+ public void should_serialize_and_format_valid_object(ZonedDateTime input, String expected) {
82+ // given
83+ when(tupleType.getComponentTypes()).thenReturn(newArrayList(timestamp(), varchar()));
84+ ZonedDateTimeCodec codec = new ZonedDateTimeCodec(tupleType);
85+ // when
86+ String actual = codec.format(input);
87+ // then
88+ Assertions.assertThat(codec).withProtocolVersion(V4).canSerialize(input);
89+ assertThat(actual).isEqualTo(expected);
90+ }
91+
92+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/DateTimeCodecTest.java +87 −0
@@ -0,0 +1,87 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.joda;
17+
18+import org.joda.time.DateTime;
19+import org.joda.time.DateTimeZone;
20+import org.testng.annotations.DataProvider;
21+import org.testng.annotations.Test;
22+
23+import static com.google.common.collect.Lists.newArrayList;
24+import static org.assertj.core.api.Assertions.assertThat;
25+import static org.joda.time.DateTimeZone.UTC;
26+import static org.joda.time.DateTimeZone.forID;
27+import static org.mockito.Mockito.mock;
28+import static org.mockito.Mockito.when;
29+
30+import com.datastax.driver.core.Assertions;
31+import com.datastax.driver.core.TupleType;
32+
33+import static com.datastax.driver.core.DataType.timestamp;
34+import static com.datastax.driver.core.DataType.varchar;
35+import static com.datastax.driver.core.ProtocolVersion.V4;
36+
37+public class DateTimeCodecTest {
38+
39+ private final TupleType tupleType = mock(TupleType.class);
40+
41+ @DataProvider(name = "DateTimeCodecTest.parse")
42+ public Object[][] parseParameters() {
43+ return new Object[][]{
44+ { null , null },
45+ { "" , null },
46+ { "NULL" , null },
47+ { "(0 ,'UTC')" , new DateTime(0, forID("UTC")) },
48+ { "(1277860847999 ,'+01:00')" , new DateTime("2010-06-30T02:20:47.999+01:00", forID("+01:00")) },
49+ { "('2010-06-30T01:20Z' ,'+01:00')" , new DateTime("2010-06-30T02:20:00.000+01:00", forID("+01:00")) },
50+ { "('2010-06-30T01:20:47Z' ,'+01:00')" , new DateTime("2010-06-30T02:20:47.000+01:00", forID("+01:00")) },
51+ { "('2010-06-30T01:20:47.999Z','+01:00')" , new DateTime("2010-06-30T02:20:47.999+01:00", forID("+01:00")) }
52+ };
53+ }
54+
55+ @DataProvider(name = "DateTimeCodecTest.format")
56+ public Object[][] formatParameters() {
57+ return new Object[][]{
58+ { null , "NULL" },
59+ { new DateTime(0).withZone(UTC) , "('1970-01-01T00:00:00.000Z','+00:00')" },
60+ { new DateTime("2010-06-30T01:20:47.999+01:00", forID("+01:00")), "('2010-06-30T00:20:47.999Z','+01:00')" }
61+ };
62+ }
63+
64+ @Test(groups = "unit", dataProvider = "DateTimeCodecTest.parse")
65+ public void should_parse_valid_formats(String input, DateTime expected) {
66+ // given
67+ when(tupleType.getComponentTypes()).thenReturn(newArrayList(timestamp(), varchar()));
68+ DateTimeCodec codec = new DateTimeCodec(tupleType);
69+ // when
70+ DateTime actual = codec.parse(input);
71+ // then
72+ assertThat(actual).isEqualTo(expected);
73+ }
74+
75+ @Test(groups = "unit", dataProvider = "DateTimeCodecTest.format")
76+ public void should_serialize_and_format_valid_object(DateTime input, String expected) {
77+ // given
78+ when(tupleType.getComponentTypes()).thenReturn(newArrayList(timestamp(), varchar()));
79+ DateTimeCodec codec = new DateTimeCodec(tupleType);
80+ // when
81+ String actual = codec.format(input);
82+ // then
83+ Assertions.assertThat(codec).withProtocolVersion(V4).canSerialize(input);
84+ assertThat(actual).isEqualTo(expected);
85+ }
86+
87+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/InstantCodecTest.java +75 −0
@@ -0,0 +1,75 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.joda;
17+
18+import java.text.ParseException;
19+
20+import org.joda.time.Instant;
21+import org.testng.annotations.DataProvider;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.Assertions;
27+
28+import static com.datastax.driver.core.ProtocolVersion.V4;
29+
30+public class InstantCodecTest {
31+
32+ @DataProvider(name = "InstantCodecTest.parse")
33+ public Object[][] parseParameters() {
34+ return new Object[][]{
35+ { null , null },
36+ { "" , null },
37+ { "NULL" , null },
38+ { "0" , new Instant(0) },
39+ { "1277860847999" , new Instant(1277860847999L) },
40+ { "'2010-06-30T01:20'" , Instant.parse("2010-06-30T01:20:00.000Z") },
41+ { "'2010-06-30T01:20Z'" , Instant.parse("2010-06-30T01:20:00.000Z") },
42+ { "'2010-06-30T01:20:47'" , Instant.parse("2010-06-30T01:20:47.000Z") },
43+ { "'2010-06-30T01:20:47+01:00'" , Instant.parse("2010-06-30T00:20:47.000Z") },
44+ { "'2010-06-30T01:20:47.999'" , Instant.parse("2010-06-30T01:20:47.999Z") },
45+ { "'2010-06-30T01:20:47.999+01:00'" , Instant.parse("2010-06-30T00:20:47.999Z") }
46+ };
47+ }
48+
49+ @DataProvider(name = "InstantCodecTest.format")
50+ public Object[][] formatParameters() throws ParseException {
51+ return new Object[][]{
52+ { null , "NULL" },
53+ { new Instant(0) , "'1970-01-01T00:00:00.000+00:00'" },
54+ { Instant.parse("2010-06-30T02:20:47.999+01:00").toInstant(), "'2010-06-30T01:20:47.999+00:00'" }
55+ };
56+ }
57+
58+ @Test(groups = "unit", dataProvider = "InstantCodecTest.parse")
59+ public void should_parse_valid_formats(String input, Instant expected) {
60+ // when
61+ Instant actual = InstantCodec.instance.parse(input);
62+ // then
63+ assertThat(actual).isEqualTo(expected);
64+ }
65+
66+ @Test(groups = "unit", dataProvider = "InstantCodecTest.format")
67+ public void should_serialize_and_format_valid_object(Instant input, String expected) {
68+ // when
69+ String actual = InstantCodec.instance.format(input);
70+ // then
71+ Assertions.assertThat(InstantCodec.instance).withProtocolVersion(V4).canSerialize(input);
72+ assertThat(actual).isEqualTo(expected);
73+ }
74+
75+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/JodaTimeCodecsTest.java +309 −0
@@ -0,0 +1,309 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.joda;
17+
18+import java.util.*;
19+
20+import static java.util.concurrent.TimeUnit.MILLISECONDS;
21+import static java.util.concurrent.TimeUnit.NANOSECONDS;
22+
23+import com.google.common.collect.ImmutableMap;
24+import org.joda.time.DateTime;
25+import org.joda.time.Instant;
26+import org.joda.time.LocalDate;
27+import org.joda.time.LocalTime;
28+import org.testng.annotations.BeforeClass;
29+import org.testng.annotations.Test;
30+
31+import static com.google.common.collect.Lists.newArrayList;
32+import static com.google.common.collect.Sets.newHashSet;
33+import static org.assertj.core.api.Assertions.assertThat;
34+
35+import com.datastax.driver.core.*;
36+import com.datastax.driver.core.utils.CassandraVersion;
37+import com.datastax.driver.mapping.Mapper;
38+import com.datastax.driver.mapping.MappingManager;
39+import com.datastax.driver.mapping.annotations.Column;
40+import com.datastax.driver.mapping.annotations.PartitionKey;
41+import com.datastax.driver.mapping.annotations.Table;
42+
43+import static com.datastax.driver.core.DataType.timestamp;
44+import static com.datastax.driver.core.DataType.varchar;
45+
46+@CassandraVersion(major=2.2)
47+public class JodaTimeCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
48+
49+ @Override
50+ protected Collection<String> getTableDefinitions() {
51+ return Collections.singletonList(
52+ "CREATE TABLE IF NOT EXISTS foo ("
53+ + "c1 text PRIMARY KEY, "
54+ + "cdate date, "
55+ + "ctime time, "
56+ + "ctimestamp timestamp, "
57+ + "ctuple tuple<timestamp,varchar>, "
58+ + "cdates frozen<list<date>>, "
59+ + "ctimes frozen<set<time>>, "
60+ + "ctimestamps frozen<map<text,timestamp>>, "
61+ + "ctuples frozen<map<tuple<timestamp,varchar>,varchar>>"
62+ + ")");
63+ }
64+
65+ @BeforeClass(groups = "short")
66+ public void registerCodecs() throws Exception {
67+ TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
68+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
69+ codecRegistry
70+ .register(LocalTimeCodec.instance)
71+ .register(LocalDateCodec.instance)
72+ .register(InstantCodec.instance)
73+ .register(new DateTimeCodec(dateWithTimeZoneType));
74+ }
75+
76+ /**
77+ * <p>
78+ * Validates that a <code>time</code> column can be mapped to a {@link LocalTime} by using
79+ * {@link LocalTimeCodec}.
80+ * </p>
81+ *
82+ * @test_category data_types:serialization
83+ * @expected_result properly maps.
84+ * @jira_ticket JAVA-846
85+ * @since 2.2.0
86+ */
87+ @Test(groups="short")
88+ public void should_map_time_to_localtime() {
89+ // given
90+ LocalTime time = new LocalTime(12, 16, 34, 999);
91+ // when
92+ session.execute("insert into foo (c1, ctime) values (?, ?)", "should_map_time_to_localtime", time);
93+ ResultSet result = session.execute("select ctime from foo where c1=?", "should_map_time_to_localtime");
94+ // then
95+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
96+ Row row = result.one();
97+ assertThat(row.get("ctime", LocalTime.class)).isEqualTo(time);
98+ assertThat(row.getTime("ctime")).isEqualTo(NANOSECONDS.convert(time.getMillisOfDay(), MILLISECONDS));
99+ }
100+
101+ /**
102+ * <p>
103+ * Validates that a <code>date</code> column can be mapped to a {@link org.joda.time.LocalDate} by using
104+ * {@link LocalDateCodec}.
105+ * </p>
106+ *
107+ * @test_category data_types:serialization
108+ * @expected_result properly maps.
109+ * @jira_ticket JAVA-846
110+ * @since 2.2.0
111+ */
112+ @Test(groups="short")
113+ public void should_map_date_to_localdate() {
114+ // given
115+ LocalDate localDate = new LocalDate(2015, 1, 1);
116+ com.datastax.driver.core.LocalDate driverLocalDate = com.datastax.driver.core.LocalDate.fromYearMonthDay(2015, 1, 1);
117+ // when
118+ session.execute("insert into foo (c1, cdate) values (?, ?)", "should_map_date_to_localdate", localDate);
119+ ResultSet result = session.execute("select cdate from foo where c1=?", "should_map_date_to_localdate");
120+ // then
121+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
122+ Row row = result.one();
123+ assertThat(row.get("cdate", LocalDate.class)).isEqualTo(localDate);
124+ assertThat(row.getDate("cdate")).isEqualTo(driverLocalDate);
125+ }
126+
127+ /**
128+ * <p>
129+ * Validates that a <code>timestamp</code> column can be mapped to an {@link Instant} by using
130+ * {@link InstantCodec}.
131+ * </p>
132+ *
133+ * @test_category data_types:serialization
134+ * @expected_result properly maps.
135+ * @jira_ticket JAVA-846
136+ * @since 2.2.0
137+ */
138+ @Test(groups="short")
139+ public void should_map_timestamp_to_instant() {
140+ // given
141+ Instant instant = Instant.parse("2010-06-30T01:20+05:00");
142+ // when
143+ session.execute("insert into foo (c1, ctimestamp) values (?, ?)", "should_map_timestamp_to_datetime", instant);
144+ ResultSet result = session.execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_datetime");
145+ // then
146+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
147+ Row row = result.one();
148+ assertThat(row.get("ctimestamp", Instant.class)).isEqualTo(instant);
149+ assertThat(row.getTimestamp("ctimestamp")).isEqualTo(instant.toDate());
150+ }
151+
152+ /**
153+ * <p>
154+ * Validates that a <code>tuple&lt;timestamp,text&gt;</code> column can be mapped to a {@link DateTime} by using
155+ * {@link DateTimeCodec}.
156+ * </p>
157+ *
158+ * @test_category data_types:serialization
159+ * @expected_result properly maps.
160+ * @jira_ticket JAVA-846
161+ * @since 2.2.0
162+ */
163+ @Test(groups="short")
164+ public void should_map_tuple_to_datetime() {
165+ // given
166+ DateTime expected = DateTime.parse("2010-06-30T01:20+05:30");
167+ // when
168+ PreparedStatement insertStmt = session.prepare("insert into foo (c1, ctuple) values (?, ?)");
169+ session.execute(insertStmt.bind("should_map_tuple_to_datetime", expected));
170+ ResultSet result = session.execute("select ctuple from foo where c1=?", "should_map_tuple_to_datetime");
171+ // then
172+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
173+ Row row = result.one();
174+ // Since timezone is preserved in the tuple, the date times should match perfectly.
175+ assertThat(row.get("ctuple", DateTime.class)).isEqualTo(expected);
176+ // Ensure the timezones match as well.
177+ // (This is just a safety check as the previous assert would have failed otherwise).
178+ assertThat(row.get("ctuple", DateTime.class).getZone()).isEqualTo(expected.getZone());
179+ }
180+
181+ @Test(groups="short")
182+ public void should_use_mapper_to_store_and_retrieve_values_with_custom_joda_codecs() {
183+ // given
184+ MappingManager manager = new MappingManager(session);
185+ Mapper<Mapped> mapper = manager.mapper(Mapped.class);
186+ // when
187+ Mapped pojo = new Mapped();
188+ mapper.save(pojo);
189+ Mapped actual = mapper.get("mapper");
190+ // then
191+ assertThat(actual).isEqualToComparingFieldByField(pojo);
192+ }
193+
194+ @SuppressWarnings("unused")
195+ @Table(name = "foo")
196+ public static class Mapped {
197+
198+ @PartitionKey
199+ private String c1;
200+
201+ @Column(name = "cdate")
202+ private LocalDate date;
203+
204+ @Column(name = "ctime")
205+ private LocalTime time;
206+
207+ @Column(name = "ctimestamp")
208+ private Instant instant;
209+
210+ @Column(name = "ctuple")
211+ private DateTime datetime;
212+
213+ @Column(name = "cdates")
214+ private List<LocalDate> dates;
215+
216+ @Column(name = "ctimes")
217+ private Set<LocalTime> times;
218+
219+ @Column(name = "ctimestamps")
220+ private Map<String, Instant> instants;
221+
222+ @Column(name = "ctuples")
223+ private Map<DateTime, String> datetimes;
224+
225+ public Mapped() {
226+ c1 = "mapper";
227+ date = LocalDate.parse("2014-01-01");
228+ time = LocalTime.parse("13:03:24");
229+ instant = Instant.parse("2010-06-30T01:20:47.000Z");
230+ datetime = DateTime.parse("2010-06-30T01:20:47+05:30");
231+ dates = newArrayList(date);
232+ times = newHashSet(time);
233+ instants = ImmutableMap.of("foo", instant);
234+ datetimes = ImmutableMap.of(datetime, "bar");
235+ }
236+
237+ public String getC1() {
238+ return c1;
239+ }
240+
241+ public void setC1(String c1) {
242+ this.c1 = c1;
243+ }
244+
245+ public LocalDate getDate() {
246+ return date;
247+ }
248+
249+ public void setDate(LocalDate date) {
250+ this.date = date;
251+ }
252+
253+ public LocalTime getTime() {
254+ return time;
255+ }
256+
257+ public void setTime(LocalTime time) {
258+ this.time = time;
259+ }
260+
261+ public Instant getInstant() {
262+ return instant;
263+ }
264+
265+ public void setInstant(Instant instant) {
266+ this.instant = instant;
267+ }
268+
269+ public DateTime getDatetime() {
270+ return datetime;
271+ }
272+
273+ public void setDatetime(DateTime datetime) {
274+ this.datetime = datetime;
275+ }
276+
277+ public List<LocalDate> getDates() {
278+ return dates;
279+ }
280+
281+ public void setDates(List<LocalDate> dates) {
282+ this.dates = dates;
283+ }
284+
285+ public Set<LocalTime> getTimes() {
286+ return times;
287+ }
288+
289+ public void setTimes(Set<LocalTime> times) {
290+ this.times = times;
291+ }
292+
293+ public Map<String, Instant> getInstants() {
294+ return instants;
295+ }
296+
297+ public void setInstants(Map<String, Instant> instants) {
298+ this.instants = instants;
299+ }
300+
301+ public Map<DateTime, String> getDatetimes() {
302+ return datetimes;
303+ }
304+
305+ public void setDatetimes(Map<DateTime, String> datetimes) {
306+ this.datetimes = datetimes;
307+ }
308+ }
309+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/LocalDateCodecTest.java +73 −0
@@ -0,0 +1,73 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.joda;
17+
18+import org.joda.time.LocalDate;
19+import org.testng.annotations.DataProvider;
20+import org.testng.annotations.Test;
21+
22+import static org.assertj.core.api.Assertions.assertThat;
23+
24+import com.datastax.driver.core.Assertions;
25+
26+import static com.datastax.driver.core.ProtocolVersion.V4;
27+
28+public class LocalDateCodecTest {
29+
30+ private static final LocalDate EPOCH = new LocalDate(1970, 1, 1);
31+ private static final LocalDate MIN = LocalDate.parse("-5877641-06-23");
32+
33+ @DataProvider(name = "LocalDateCodecTest")
34+ public Object[][] parseParameters() {
35+ return new Object[][]{
36+ { null , null },
37+ { "" , null },
38+ { "NULL" , null },
39+ { "0" , MIN },
40+ { "'2147483648'" , EPOCH },
41+ { "'-5877641-06-23'" , MIN },
42+ { "'1970-01-01'" , EPOCH },
43+ { "'2014-01-01'" , LocalDate.parse("2014-01-01") }
44+ };
45+ }
46+
47+ @DataProvider(name = "LocalDateCodecTest.format")
48+ public Object[][] formatParameters() {
49+ return new Object[][]{
50+ { null , "NULL" },
51+ { EPOCH , "'1970-01-01'" },
52+ { LocalDate.parse("2010-06-30"), "'2010-06-30'" }
53+ };
54+ }
55+
56+ @Test(groups = "unit", dataProvider = "LocalDateCodecTest")
57+ public void should_parse_valid_formats(String input, LocalDate expected) {
58+ // when
59+ LocalDate actual = LocalDateCodec.instance.parse(input);
60+ // then
61+ assertThat(actual).isEqualTo(expected);
62+ }
63+
64+ @Test(groups = "unit", dataProvider = "LocalDateCodecTest.format")
65+ public void should_serialize_and_format_valid_object(LocalDate input, String expected) {
66+ // when
67+ String actual = LocalDateCodec.instance.format(input);
68+ // then
69+ Assertions.assertThat(LocalDateCodec.instance).withProtocolVersion(V4).canSerialize(input);
70+ assertThat(actual).isEqualTo(expected);
71+ }
72+
73+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/joda/LocalTimeCodecTest.java +76 −0
@@ -0,0 +1,76 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.joda;
17+
18+import static java.util.concurrent.TimeUnit.MILLISECONDS;
19+
20+import org.joda.time.LocalTime;
21+import org.testng.annotations.DataProvider;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.Assertions;
27+
28+import static com.datastax.driver.core.ParseUtils.quote;
29+import static com.datastax.driver.core.ProtocolVersion.V4;
30+
31+public class LocalTimeCodecTest {
32+
33+ @DataProvider(name = "LocalTimeCodecTest.parse")
34+ public Object[][] parseParameters() {
35+ LocalTime time = LocalTime.parse("13:25:47.123456789");
36+ String nanosOfDay = quote(Long.toString(MILLISECONDS.toNanos(time.getMillisOfDay())));
37+ return new Object[][]{
38+ { null , null },
39+ { "" , null },
40+ { "NULL" , null },
41+ { nanosOfDay , LocalTime.parse("13:25:47.123456789") },
42+ { "'13:25:47'" , LocalTime.parse("13:25:47") },
43+ { "'13:25:47.123'" , LocalTime.parse("13:25:47.123") },
44+ { "'13:25:47.123456'" , LocalTime.parse("13:25:47.123456") },
45+ { "'13:25:47.123456789'", LocalTime.parse("13:25:47.123456789") }
46+ };
47+ }
48+
49+ @DataProvider(name = "LocalTimeCodecTest.format")
50+ public Object[][] formatParameters() {
51+ return new Object[][]{
52+ { null , "NULL" },
53+ { LocalTime.parse("12:00") , "'12:00:00.000'" },
54+ { LocalTime.parse("02:20:47.999999"), "'02:20:47.999'" }
55+ };
56+ }
57+
58+ @Test(groups = "unit", dataProvider = "LocalTimeCodecTest.parse")
59+ public void should_parse_valid_formats(String input, LocalTime expected) {
60+ // when
61+ LocalTime actual = LocalTimeCodec.instance.parse(input);
62+ // then
63+ assertThat(actual).isEqualTo(expected);
64+ }
65+
66+ @Test(groups = "unit", dataProvider = "LocalTimeCodecTest.format")
67+ public void should_serialize_and_format_valid_object(LocalTime input, String expected) {
68+ // when
69+ String actual = LocalTimeCodec.instance.format(input);
70+ // then
71+ Assertions.assertThat(LocalTimeCodec.instance).withProtocolVersion(V4).canSerialize(input);
72+ assertThat(actual).isEqualTo(expected);
73+ }
74+
75+
76+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodecTest.java +222 −0
@@ -0,0 +1,222 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.json;
17+
18+import java.util.ArrayList;
19+import java.util.Collection;
20+
21+import com.fasterxml.jackson.annotation.JsonCreator;
22+import com.fasterxml.jackson.annotation.JsonProperty;
23+import com.google.common.base.Objects;
24+import com.google.common.collect.Lists;
25+import org.testng.annotations.Test;
26+
27+import static org.assertj.core.api.Assertions.assertThat;
28+
29+import com.datastax.driver.core.*;
30+import com.datastax.driver.core.querybuilder.BuiltStatement;
31+import com.datastax.driver.core.querybuilder.QueryBuilder;
32+import com.datastax.driver.core.utils.CassandraVersion;
33+import com.datastax.driver.extras.codecs.json.JacksonJsonCodec;
34+
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
36+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
37+
38+public class JacksonJsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
39+
40+ private static final JacksonJsonCodec<User> jsonCodec = new JacksonJsonCodec<User>(User.class);
41+
42+ private static final User alice = new User(1, "Alice");
43+ private static final User bob = new User(2, "Bob");
44+ private static final User charlie = new User(3, "Charlie");
45+
46+ private static final String bobJson = "{\"id\":2,\"name\":\"Bob\"}";
47+ private static final String charlieJson = "{\"id\":3,\"name\":\"Charlie\"}";
48+ private static final String aliceJson = "{\"id\":1,\"name\":\"Alice\"}";
49+
50+ private static final ArrayList<User> bobAndCharlie = Lists.newArrayList(bob, charlie);
51+
52+ private static final String insertQuery = "INSERT INTO t1 (c1, c2, c3) VALUES (?, ?, ?)";
53+ private static final String selectQuery = "SELECT c1, c2, c3 FROM t1 WHERE c1 = ? and c2 = ?";
54+
55+ private static final String notAJsonString = "this text is not json";
56+
57+ @Override
58+ protected Collection<String> getTableDefinitions() {
59+ return Lists.newArrayList(
60+ "CREATE TABLE t1 (c1 text, c2 text, c3 list<text>, PRIMARY KEY (c1, c2))"
61+ );
62+ }
63+
64+ @Override
65+ protected Cluster.Builder configure(Cluster.Builder builder) {
66+ return builder.withCodecRegistry(
67+ new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
68+ );
69+ }
70+
71+ @Test(groups = "unit")
72+ public void test_cql_text_to_json() {
73+ JacksonJsonCodec<User> codec = new JacksonJsonCodec<User>(User.class);
74+ // the codec is expected to format json objects as json strings enclosed in single quotes,
75+ // as it is required for CQL literals of varchar type.
76+ String json = "'{\"id\":1,\"name\":\"John Doe\"}'";
77+ User user = new User(1, "John Doe");
78+ assertThat(codec.format(user)).isEqualTo(json);
79+ assertThat(codec.parse(json)).isEqualToComparingFieldByField(user);
80+ }
81+
82+ @Test(groups = "unit")
83+ public void test_nulls() {
84+ JacksonJsonCodec<User> codec = new JacksonJsonCodec<User>(User.class);
85+ assertThat(codec.format(null)).isEqualTo("NULL");
86+ assertThat(codec.parse(null)).isNull();
87+ }
88+
89+ @Test(groups = "short")
90+ @CassandraVersion(major=2.0)
91+ public void should_use_custom_codec_with_simple_statements() {
92+ session.execute(insertQuery, notAJsonString, alice, bobAndCharlie);
93+ ResultSet rows = session.execute(selectQuery, notAJsonString, alice);
94+ Row row = rows.one();
95+ assertRow(row);
96+ }
97+
98+ @Test(groups = "short")
99+ public void should_use_custom_codec_with_built_statements_1() {
100+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
101+ .value("c1", bindMarker())
102+ .value("c2", bindMarker())
103+ .value("c3", bindMarker());
104+ BuiltStatement selectStmt = new QueryBuilder(cluster).select("c1", "c2", "c3")
105+ .from("t1")
106+ .where(eq("c1", bindMarker()))
107+ .and(eq("c2", bindMarker()));
108+ session.execute(session.prepare(insertStmt).bind(notAJsonString, alice, bobAndCharlie));
109+ ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, alice));
110+ Row row = rows.one();
111+ assertRow(row);
112+ }
113+
114+ @Test(groups = "short")
115+ public void should_use_custom_codec_with_built_statements_2() {
116+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
117+ .value("c1", notAJsonString)
118+ .value("c2", alice)
119+ .value("c3", bobAndCharlie);
120+ BuiltStatement selectStmt =
121+ new QueryBuilder(cluster).select("c1", "c2", "c3")
122+ .from("t1")
123+ .where(eq("c1", notAJsonString))
124+ .and(eq("c2", alice));
125+ session.execute(insertStmt);
126+ ResultSet rows = session.execute(selectStmt);
127+ Row row = rows.one();
128+ assertRow(row);
129+ }
130+
131+ @Test(groups = "short")
132+ public void should_use_custom_codec_with_prepared_statements_1() {
133+ session.execute(session.prepare(insertQuery).bind(notAJsonString, alice, bobAndCharlie));
134+ PreparedStatement ps = session.prepare(selectQuery);
135+ // this bind() method does not convey information about the java type of alice
136+ // so the registry will look for a codec accepting varchar <-> ANY
137+ // and will find jsonCodec because it is the first registered
138+ ResultSet rows = session.execute(ps.bind(notAJsonString, alice));
139+ Row row = rows.one();
140+ assertRow(row);
141+ }
142+
143+ @Test(groups = "short")
144+ public void should_use_custom_codec_with_prepared_statements_2() {
145+ session.execute(session.prepare(insertQuery).bind()
146+ .setString(0, notAJsonString)
147+ .set(1, alice, User.class)
148+ .setList(2, bobAndCharlie, User.class)
149+ );
150+ PreparedStatement ps = session.prepare(selectQuery);
151+ ResultSet rows = session.execute(ps.bind()
152+ .setString(0, notAJsonString)
153+ // this set() method conveys information about the java type of alice
154+ // so the registry will look for a codec accepting varchar <-> User
155+ // and will find jsonCodec because it is the only matching one
156+ .set(1, alice, User.class)
157+ );
158+ Row row = rows.one();
159+ assertRow(row);
160+ }
161+
162+ private void assertRow(Row row) {
163+ // getString requires a codec accepting varchar <-> String, so VarcharCodec is used
164+ assertThat(row.getString(0)).isEqualTo(notAJsonString);
165+ // getObject requires a codec accepting varchar <-> ANY;
166+ // the first codec that accepts that is jsonCodec, so it is used
167+ assertThat(row.getObject(1)).isEqualTo(aliceJson);
168+ // getObject uses the default codec VarcharCodec
169+ assertThat(row.get(1, User.class)).isEqualTo(alice);
170+ // we still can get the column as a string using VarcharCodec.instance behind the scenes
171+ assertThat(row.getString(1)).isEqualTo(aliceJson);
172+ assertThat(row.getList(2, User.class)).containsExactly(bob, charlie);
173+ // we still can get the column as a List<String>
174+ assertThat(row.getList(2, String.class)).containsExactly(bobJson, charlieJson);
175+ }
176+
177+ @SuppressWarnings("unused")
178+ public static class User {
179+
180+ private int id;
181+
182+ private String name;
183+
184+ @JsonCreator
185+ public User(@JsonProperty("id") int id, @JsonProperty("name") String name) {
186+ this.id = id;
187+ this.name = name;
188+ }
189+
190+ public int getId() {
191+ return id;
192+ }
193+
194+ public void setId(int id) {
195+ this.id = id;
196+ }
197+
198+ public String getName() {
199+ return name;
200+ }
201+
202+ public void setName(String name) {
203+ this.name = name;
204+ }
205+
206+ @Override
207+ public boolean equals(Object o) {
208+ if (this == o)
209+ return true;
210+ if (o == null || getClass() != o.getClass())
211+ return false;
212+ User user = (User)o;
213+ return Objects.equal(id, user.id) &&
214+ Objects.equal(name, user.name);
215+ }
216+
217+ @Override
218+ public int hashCode() {
219+ return Objects.hashCode(id, name);
220+ }
221+ }
222+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodecTest.java +168 −0
@@ -0,0 +1,168 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.json;
17+
18+import java.io.IOException;
19+import java.io.StringWriter;
20+import java.util.Collection;
21+
22+import com.google.common.collect.Lists;
23+import javax.json.*;
24+import org.testng.annotations.DataProvider;
25+import org.testng.annotations.Test;
26+
27+import static org.assertj.core.api.Assertions.assertThat;
28+
29+import com.datastax.driver.core.*;
30+import com.datastax.driver.core.querybuilder.BuiltStatement;
31+import com.datastax.driver.core.querybuilder.QueryBuilder;
32+import com.datastax.driver.core.utils.CassandraVersion;
33+import com.datastax.driver.extras.codecs.json.Jsr353JsonCodec;
34+
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
36+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
37+
38+public class Jsr353JsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
39+
40+ private static final Jsr353JsonCodec jsonCodec = new Jsr353JsonCodec();
41+
42+ private static final JsonObject alice = Json.createObjectBuilder().add("id", 1).add("name", "Alice") .build();
43+ private static final JsonObject bob = Json.createObjectBuilder().add("id", 2).add("name", "Bob") .build();
44+ private static final JsonObject charlie = Json.createObjectBuilder().add("id", 3).add("name", "Charlie").build();
45+
46+ private static final JsonArray bobAndCharlie = Json.createArrayBuilder().add(bob).add(charlie).build();
47+
48+ private static final String insertQuery = "INSERT INTO t1 (c1, c2) VALUES (?, ?)";
49+ private static final String selectQuery = "SELECT c1, c2 FROM t1 WHERE c1 = ? and c2 = ?";
50+
51+ private static final String notAJsonString = "this text is not json";
52+
53+ @Override
54+ protected Collection<String> getTableDefinitions() {
55+ return Lists.newArrayList(
56+ "CREATE TABLE t1 (c1 text, c2 text, PRIMARY KEY (c1, c2))"
57+ );
58+ }
59+
60+ @Override
61+ protected Cluster.Builder configure(Cluster.Builder builder) {
62+ return builder.withCodecRegistry(
63+ new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
64+ );
65+ }
66+
67+ @DataProvider(name = "Jsr353JsonCodecTest")
68+ public static Object[][] parameters() {
69+ return new Object[][] {
70+ { alice },
71+ { bobAndCharlie }
72+ };
73+ }
74+
75+ @Test(groups = "unit")
76+ public void test_cql_text_to_json() {
77+ Jsr353JsonCodec codec = new Jsr353JsonCodec();
78+ String json = "'{\"id\":1,\"name\":\"John Doe\"}'";
79+ JsonObject object = Json.createObjectBuilder().add("id", 1).add("name", "John Doe").build();
80+ assertThat(codec.format(object)).isEqualTo(json);
81+ assertThat(codec.parse(json)).isEqualTo(object);
82+ }
83+
84+ @Test(groups = "unit")
85+ public void test_nulls() {
86+ Jsr353JsonCodec codec = new Jsr353JsonCodec();
87+ assertThat(codec.format(null)).isEqualTo("NULL");
88+ assertThat(codec.parse(null)).isNull();
89+ }
90+
91+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
92+ @CassandraVersion(major=2.0)
93+ public void should_use_custom_codec_with_simple_statements(JsonStructure object) throws IOException {
94+ session.execute(insertQuery, notAJsonString, object);
95+ ResultSet rows = session.execute(selectQuery, notAJsonString, object);
96+ Row row = rows.one();
97+ assertRow(row, object);
98+ }
99+
100+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
101+ public void should_use_custom_codec_with_built_statements_1(JsonStructure object) throws IOException {
102+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
103+ .value("c1", bindMarker())
104+ .value("c2", bindMarker());
105+ BuiltStatement selectStmt = new QueryBuilder(cluster).select("c1", "c2")
106+ .from("t1")
107+ .where(eq("c1", bindMarker()))
108+ .and(eq("c2", bindMarker()));
109+ session.execute(session.prepare(insertStmt).bind(notAJsonString, object));
110+ ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, object));
111+ Row row = rows.one();
112+ assertRow(row, object);
113+ }
114+
115+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
116+ public void should_use_custom_codec_with_built_statements_2(JsonStructure object) throws IOException {
117+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
118+ .value("c1", notAJsonString)
119+ .value("c2", object);
120+ BuiltStatement selectStmt =
121+ new QueryBuilder(cluster).select("c1", "c2")
122+ .from("t1")
123+ .where(eq("c1", notAJsonString))
124+ .and(eq("c2", object));
125+ session.execute(insertStmt);
126+ ResultSet rows = session.execute(selectStmt);
127+ Row row = rows.one();
128+ assertRow(row, object);
129+ }
130+
131+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
132+ public void should_use_custom_codec_with_prepared_statements_1(JsonStructure object) throws IOException {
133+ session.execute(session.prepare(insertQuery).bind(notAJsonString, object));
134+ PreparedStatement ps = session.prepare(selectQuery);
135+ ResultSet rows = session.execute(ps.bind(notAJsonString, object));
136+ Row row = rows.one();
137+ assertRow(row, object);
138+ }
139+
140+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
141+ public void should_use_custom_codec_with_prepared_statements_2(JsonStructure object) throws IOException {
142+ session.execute(session.prepare(insertQuery).bind()
143+ .setString(0, notAJsonString)
144+ .set(1, object, JsonStructure.class)
145+ );
146+ PreparedStatement ps = session.prepare(selectQuery);
147+ ResultSet rows = session.execute(ps.bind()
148+ .setString(0, notAJsonString)
149+ .set(1, object, JsonStructure.class)
150+ );
151+ Row row = rows.one();
152+ assertRow(row, object);
153+ }
154+
155+ private void assertRow(Row row, JsonStructure object) throws IOException {
156+ String json;
157+ StringWriter sw = new StringWriter();
158+ JsonWriter writer = Json.createWriter(sw);
159+ writer.write(object);
160+ json = sw.toString();
161+ assertThat(row.getString(0)).isEqualTo(notAJsonString);
162+ assertThat(row.getObject(1)).isEqualTo(json);
163+ assertThat(row.getString(1)).isEqualTo(json);
164+ assertThat(row.get(1, String.class)).isEqualTo(json);
165+ assertThat(row.get(1, JsonStructure.class)).isEqualTo(object);
166+ }
167+
168+}
added driver-extras/src/test/resources/log4j.properties +29 −0
@@ -0,0 +1,29 @@
1+#
2+# Copyright (C) 2012-2015 DataStax Inc.
3+#
4+# Licensed under the Apache License, Version 2.0 (the "License");
5+# you may not use this file except in compliance with the License.
6+# You may obtain a copy of the License at
7+#
8+# http://www.apache.org/licenses/LICENSE-2.0
9+#
10+# Unless required by applicable law or agreed to in writing, software
11+# distributed under the License is distributed on an "AS IS" BASIS,
12+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+# See the License for the specific language governing permissions and
14+# limitations under the License.
15+#
16+
17+# Set root logger level to OFF and its only appender to A1.
18+log4j.rootLogger=OFF, A1
19+
20+# Adjust Scassandra's log level
21+# (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both)
22+log4j.logger.org.scassandra=OFF
23+
24+# A1 is set to be a ConsoleAppender.
25+log4j.appender.A1=org.apache.log4j.ConsoleAppender
26+
27+# A1 uses PatternLayout.
28+log4j.appender.A1.layout=org.apache.log4j.PatternLayout
29+log4j.appender.A1.layout.ConversionPattern=\ %-6r [%t] %-5p %c %x - %m%n
modified driver-mapping/pom.xml +4 −12
@@ -50,28 +50,28 @@
5050 <dependency>
5151 <groupId>org.testng</groupId>
5252 <artifactId>testng</artifactId>
53- <version>6.8.1</version>
53+ <version>${testng.version}</version>
5454 <scope>test</scope>
5555 </dependency>
5656
5757 <dependency>
5858 <groupId>org.assertj</groupId>
5959 <artifactId>assertj-core</artifactId>
60- <version>1.7.0</version>
60+ <version>${assertj.version}</version>
6161 <scope>test</scope>
6262 </dependency>
6363
6464 <dependency>
6565 <groupId>org.mockito</groupId>
6666 <artifactId>mockito-all</artifactId>
67- <version>1.10.8</version>
67+ <version>${mockito.version}</version>
6868 <scope>test</scope>
6969 </dependency>
7070
7171 <dependency>
7272 <groupId>org.apache.commons</groupId>
7373 <artifactId>commons-exec</artifactId>
74- <version>1.3</version>
74+ <version>${commons-exec.version}</version>
7575 <scope>test</scope>
7676 </dependency>
7777
@@ -151,14 +151,6 @@
151151 </systemPropertyVariables>
152152 </configuration>
153153 </plugin>
154- <plugin>
155- <artifactId>maven-compiler-plugin</artifactId>
156- <configuration>
157- <compilerArgument>-Xlint:all</compilerArgument>
158- <showWarnings>true</showWarnings>
159- <showDeprecation>true</showDeprecation>
160- </configuration>
161- </plugin>
162154 </plugins>
163155 </build>
164156 </profile>
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +22 −33
@@ -18,19 +18,16 @@
1818 import java.lang.annotation.Annotation;
1919 import java.lang.reflect.Field;
2020 import java.lang.reflect.*;
21-import java.util.ArrayList;
22-import java.util.Collections;
23-import java.util.Comparator;
24-import java.util.List;
21+import java.util.*;
2522 import java.util.concurrent.atomic.AtomicInteger;
2623
2724 import com.google.common.base.Strings;
25+import com.google.common.collect.Maps;
2826 import com.google.common.reflect.TypeToken;
2927
3028 import com.datastax.driver.core.ConsistencyLevel;
3129 import com.datastax.driver.core.TypeCodec;
3230 import com.datastax.driver.core.UserType;
33-import com.datastax.driver.mapping.MethodMapper.EnumParamMapper;
3431 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
3532 import com.datastax.driver.mapping.annotations.*;
3633
@@ -80,7 +77,7 @@
8077 throw new UnsupportedOperationException("Computed fields are not supported with native protocol v1");
8178
8279 AnnotationChecks.validateAnnotations(field, "entity",
83- Column.class, ClusteringColumn.class, Enumerated.class, Frozen.class, FrozenKey.class,
80+ Column.class, ClusteringColumn.class, Frozen.class, FrozenKey.class,
8481 FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
8582
8683 if (field.getAnnotation(Transient.class) != null)
@@ -107,12 +104,22 @@
107104 validateOrder(pks, "@PartitionKey");
108105 validateOrder(ccs, "@ClusteringColumn");
109106
110- mapper.addColumns(convert(pks, factory, mapper.entityClass, mappingManager, columnCounter),
111- convert(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
112- convert(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
107+ mapper.addColumns(createColumnMappers(pks, factory, mapper.entityClass, mappingManager, columnCounter),
108+ createColumnMappers(ccs, factory, mapper.entityClass, mappingManager, columnCounter),
109+ createColumnMappers(rgs, factory, mapper.entityClass, mappingManager, columnCounter));
113110 return mapper;
114111 }
115112
113+ private static <T> List<ColumnMapper<T>> createColumnMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
114+ List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
115+ for (int i = 0; i < fields.size(); i++) {
116+ Field field = fields.get(i);
117+ int pos = position(field);
118+ mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter));
119+ }
120+ return mappers;
121+ }
122+
116123 public static <T> MappedUDTCodec<T> parseUDT(Class<T> udtClass, EntityMapper.Factory factory, MappingManager mappingManager) {
117124 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
118125
@@ -139,7 +146,7 @@
139146
140147 AnnotationChecks.validateAnnotations(field, "UDT",
141148 com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
142- FrozenValue.class, Enumerated.class, Transient.class);
149+ FrozenValue.class, Transient.class);
143150
144151 if (field.getAnnotation(Transient.class) != null)
145152 continue;
@@ -154,16 +161,17 @@
154161 break;
155162 }
156163 }
157- List<ColumnMapper<T>> columnMappers = convert(columns, factory, udtClass, mappingManager, null);
164+ Map<String, ColumnMapper<T>> columnMappers = createFieldMappers(columns, factory, udtClass, mappingManager, null);
158165 return new MappedUDTCodec<T>(userType, udtClass, columnMappers, mappingManager);
159166 }
160167
161- private static <T> List<ColumnMapper<T>> convert(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
162- List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
168+ private static <T> Map<String, ColumnMapper<T>> createFieldMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter) {
169+ Map<String, ColumnMapper<T>> mappers = Maps.newHashMapWithExpectedSize(fields.size());
163170 for (int i = 0; i < fields.size(); i++) {
164171 Field field = fields.get(i);
165172 int pos = position(field);
166- mappers.add(factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter));
173+ ColumnMapper<T> mapper = factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter);
174+ mappers.put(mapper.getColumnName(), mapper);
167175 }
168176 return mappers;
169177 }
@@ -208,15 +216,6 @@
208216 return ColumnMapper.Kind.REGULAR;
209217 }
210218
211- public static EnumType enumType(Field field) {
212- Class<?> type = field.getType();
213- if (!type.isEnum())
214- return null;
215-
216- Enumerated enumerated = field.getAnnotation(Enumerated.class);
217- return (enumerated == null) ? EnumType.STRING : enumerated.value();
218- }
219-
220219 public static String columnName(Field field) {
221220 Column column = field.getAnnotation(Column.class);
222221 Computed computedField = field.getAnnotation(Computed.class);
@@ -337,16 +336,6 @@
337336 private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Class<? extends TypeCodec<?>> codecClass, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
338337 if (paramType instanceof Class) {
339338 Class<?> paramClass = (Class<?>) paramType;
340- if (paramClass.isEnum()) {
341- EnumType enumType = EnumType.STRING;
342- for (Annotation annotation : paramAnnotations) {
343- if (annotation instanceof Enumerated) {
344- enumType = ((Enumerated) annotation).value();
345- }
346- }
347- return new EnumParamMapper(paramName, idx, enumType);
348- }
349-
350339 if (TypeMappings.isMappedUDT(paramClass))
351340 mappingManager.getUDTCodec(paramClass);
352341
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +4 −6
@@ -20,10 +20,9 @@
2020
2121 import com.google.common.reflect.TypeToken;
2222
23+import com.datastax.driver.core.Metadata;
2324 import com.datastax.driver.core.TypeCodec;
2425
25-import static com.datastax.driver.core.querybuilder.QueryBuilder.quote;
26-
2726 abstract class ColumnMapper<T> {
2827
2928 public enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED};
@@ -57,7 +56,7 @@
5756 public String getColumnName() {
5857 return kind == Kind.COMPUTED
5958 ? columnName
60- : quote(columnName);
59+ : Metadata.quote(columnName);
6160 }
6261
6362 public String getAlias() {
@@ -69,10 +68,9 @@
6968 }
7069
7170 /**
72- * The Java type that will get passed to the codec.
73- * This might be different from the field type if the column mapper does a transformation.
71+ * The Java type of this column.
7472 */
75- public TypeToken<Object> getPivotType() {
73+ public TypeToken<Object> getJavaType() {
7674 return fieldType;
7775 }
7876 }
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/EnumType.java +0 −41
@@ -1,41 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.mapping;
17-
18-import com.google.common.reflect.TypeToken;
19-
20-/**
21- * The types of way to persist a JAVA Enum.
22- */
23-public enum EnumType {
24- /**
25- * Persists enumeration values using their ordinal in the Enum declaration.
26- * <p>
27- * Note that this relies on the order of the values in source code, and will change
28- * if values are added/removed before existing ones.
29- */
30- ORDINAL(Integer.class),
31- /** Persists enumeration values using the string they have been declared with. */
32- STRING(String.class);
33-
34- @SuppressWarnings("unchecked")
35- EnumType(Class<?> klass) {
36- this.pivotType = (TypeToken<Object>)TypeToken.of(klass);
37- }
38-
39- /** The type enum constants will be turned into before being saved */
40- final TypeToken<Object> pivotType;
41-}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +38 −49
@@ -17,6 +17,7 @@
1717
1818 import java.nio.ByteBuffer;
1919 import java.util.List;
20+import java.util.Map;
2021
2122 import com.google.common.collect.Lists;
2223
@@ -26,13 +27,13 @@
2627 /**
2728 * Serializes a class annotated with {@code @UDT} to the corresponding CQL user-defined type.
2829 */
29-class MappedUDTCodec<T> extends TypeCodec<T> {
30+class MappedUDTCodec<T> extends TypeCodec.AbstractUDTCodec<T> {
3031 private final UserType cqlUserType;
3132 private final Class<T> udtClass;
32- private final List<ColumnMapper<T>> columnMappers;
33+ private final Map<String, ColumnMapper<T>> columnMappers;
3334 private final CodecRegistry codecRegistry;
3435
35- public MappedUDTCodec(UserType cqlUserType, Class<T> udtClass, List<ColumnMapper<T>> columnMappers, MappingManager mappingManager) {
36+ public MappedUDTCodec(UserType cqlUserType, Class<T> udtClass, Map<String, ColumnMapper<T>> columnMappers, MappingManager mappingManager) {
3637 super(cqlUserType, udtClass);
3738 this.cqlUserType = cqlUserType;
3839 this.udtClass = udtClass;
@@ -41,70 +42,58 @@
4142 }
4243
4344 @Override
44- public ByteBuffer serialize(T sourceObject, ProtocolVersion protocolVersion) throws InvalidTypeException {
45- if (sourceObject == null)
46- return null;
47-
48- int size = 0;
49-
50- List<ByteBuffer> serializedFields = Lists.newArrayList();
51- for (ColumnMapper<T> cm : columnMappers) {
52- Object value = cm.getValue(sourceObject);
53- TypeCodec<Object> codec = cm.getCustomCodec();
54- if (codec == null)
55- codec = codecRegistry.codecFor(cqlUserType.getFieldType(cm.getColumnName()), cm.getPivotType());
56- ByteBuffer serializedField = codec.serialize(value, protocolVersion);
57- size += 4 + (serializedField == null ? 0 : serializedField.remaining());
58- serializedFields.add(serializedField);
59- }
60-
61- ByteBuffer result = ByteBuffer.allocate(size);
62- for (ByteBuffer bb : serializedFields) {
63- if (bb == null) {
64- result.putInt(-1);
65- } else {
66- result.putInt(bb.remaining());
67- result.put(bb.duplicate());
68- }
45+ protected T newInstance() {
46+ try {
47+ return udtClass.newInstance();
48+ } catch (Exception e) {
49+ throw new IllegalArgumentException("Error creating instance of @UDT-annotated class " + udtClass, e);
6950 }
70- return (ByteBuffer)result.flip();
7151 }
7252
7353 @Override
74- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
75- if (bytes == null || bytes.remaining() == 0)
54+ protected ByteBuffer serializeField(T source, String fieldName, ProtocolVersion protocolVersion) {
55+ // The parent class passes lowercase names unquoted, but in our internal map of mappers they are always quoted
56+ if (!fieldName.startsWith("\""))
57+ fieldName = Metadata.quote(fieldName);
58+
59+ ColumnMapper<T> columnMapper = columnMappers.get(fieldName);
60+
61+ if (columnMapper == null)
7662 return null;
77- ByteBuffer input = bytes.duplicate();
7863
79- T targetObject = newInstance();
64+ Object value = columnMapper.getValue(source);
8065
81- for (ColumnMapper<T> cm : columnMappers) {
82- int size = input.getInt();
83- ByteBuffer serialized = (size < 0) ? null : CodecUtils.readBytes(input, size);
84- TypeCodec<Object> codec = cm.getCustomCodec();
85- if (codec == null)
86- codec = codecRegistry.codecFor(cqlUserType.getFieldType(cm.getColumnName()), cm.getPivotType());
87- cm.setValue(targetObject, codec.deserialize(serialized, protocolVersion));
88- }
66+ TypeCodec<Object> codec = columnMapper.getCustomCodec();
67+ if (codec == null)
68+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType());
8969
90- return targetObject;
70+ return codec.serialize(value, protocolVersion);
9171 }
9272
93- private T newInstance() {
94- try {
95- return udtClass.newInstance();
96- } catch (Exception e) {
97- throw new IllegalArgumentException("Error creating instance of @UDT-annotated class " + udtClass, e);
73+ @Override
74+ protected T deserializeAndSetField(ByteBuffer input, T target, String fieldName, ProtocolVersion protocolVersion) {
75+ if (!fieldName.startsWith("\""))
76+ fieldName = Metadata.quote(fieldName);
77+
78+ ColumnMapper<T> columnMapper = columnMappers.get(fieldName);
79+ if (columnMapper != null) {
80+ TypeCodec<Object> codec = columnMapper.getCustomCodec();
81+ if (codec == null)
82+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType());
83+ columnMapper.setValue(target, codec.deserialize(input, protocolVersion));
9884 }
85+ return target;
9986 }
10087
10188 @Override
102- public T parse(String value) throws InvalidTypeException {
89+ protected String formatField(T source, String fieldName) {
90+ // This codec implementation is internal-use only, and its format method is never used
10391 throw new UnsupportedOperationException();
10492 }
10593
10694 @Override
107- public String format(T value) throws InvalidTypeException {
95+ protected T parseAndSetField(String input, T target, String fieldName) {
96+ // This codec implementation is internal-use only, and its parse method is never used
10897 throw new UnsupportedOperationException();
10998 }
11099 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +1 −1
@@ -226,7 +226,7 @@
226226 if (customCodec != null)
227227 bs.set(i, value, customCodec);
228228 else
229- bs.set(i, value, mapper.getPivotType());
229+ bs.set(i, value, mapper.getJavaType());
230230 }
231231
232232 /**
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +2 −30
@@ -143,7 +143,7 @@
143143
144144 ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
145145 for (int i = 0; i < args.length; i++) {
146- paramMappers[i].setValue(bs, args[i], protocolVersion);
146+ paramMappers[i].setValue(bs, args[i]);
147147 }
148148
149149 if (consistency != null)
@@ -196,7 +196,7 @@
196196 }
197197 }
198198
199- void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
199+ void setValue(BoundStatement boundStatement, Object arg) {
200200 if (paramName == null) {
201201 if (codec == null)
202202 boundStatement.set(paramIdx, arg, paramType);
@@ -211,32 +211,4 @@
211211 }
212212 }
213213
214- static class EnumParamMapper extends ParamMapper {
215-
216- private final EnumType enumType;
217-
218- public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) {
219- super(paramName, paramIdx, enumType.pivotType, null);
220- this.enumType = enumType;
221- }
222-
223- @Override
224- void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
225- super.setValue(boundStatement, convert(arg), protocolVersion);
226- }
227-
228- @SuppressWarnings("rawtypes")
229- private Object convert(Object arg) {
230- if(arg == null)
231- return arg;
232-
233- switch (enumType) {
234- case STRING:
235- return arg.toString();
236- case ORDINAL:
237- return ((Enum) arg).ordinal();
238- }
239- throw new AssertionError();
240- }
241- }
242214 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +0 −4
@@ -58,10 +58,6 @@
5858 this.endInclusive = endInclusive;
5959 }
6060
61- public static QueryType slice(int startBoundSize, boolean startInclusive, int endBoundSize, boolean endInclusive, boolean reversed) {
62- return new QueryType(reversed ? Kind.REVERSED_SLICE : Kind.SLICE, startBoundSize, startInclusive, endBoundSize, endInclusive);
63- }
64-
6561 String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) {
6662 QueryBuilder builder = new QueryBuilder(manager.getSession().getCluster());
6763 switch (kind) {
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +0 −60
@@ -19,12 +19,8 @@
1919 import java.beans.PropertyDescriptor;
2020 import java.lang.reflect.Field;
2121 import java.lang.reflect.Method;
22-import java.util.HashMap;
23-import java.util.Map;
2422 import java.util.concurrent.atomic.AtomicInteger;
2523
26-import com.google.common.reflect.TypeToken;
27-
2824 import com.datastax.driver.core.ConsistencyLevel;
2925
3026 /**
@@ -86,58 +82,6 @@
8682 }
8783 }
8884
89- private static class EnumMapper<T> extends LiteralMapper<T> {
90-
91- private final EnumType enumType;
92- private final Map<String, Object> fromString;
93-
94- private EnumMapper(Field field, int position, PropertyDescriptor pd, EnumType enumType, AtomicInteger columnCounter) {
95- super(field, position, pd, columnCounter);
96- this.enumType = enumType;
97-
98- if (enumType == EnumType.STRING) {
99- fromString = new HashMap<String, Object>(fieldType.getRawType().getEnumConstants().length);
100- for (Object constant : fieldType.getRawType().getEnumConstants())
101- fromString.put(constant.toString().toLowerCase(), constant);
102-
103- } else {
104- fromString = null;
105- }
106- }
107-
108- @SuppressWarnings("rawtypes")
109- @Override
110- public Object getValue(T entity) {
111- Object value = super.getValue(entity);
112- switch (enumType) {
113- case STRING:
114- return (value == null) ? null : value.toString();
115- case ORDINAL:
116- return (value == null) ? null : ((Enum)value).ordinal();
117- }
118- throw new AssertionError();
119- }
120-
121- @Override
122- public void setValue(Object entity, Object value) {
123- Object converted = null;
124- switch (enumType) {
125- case STRING:
126- converted = fromString.get(value.toString().toLowerCase());
127- break;
128- case ORDINAL:
129- converted = fieldType.getRawType().getEnumConstants()[(Integer)value];
130- break;
131- }
132- super.setValue(entity, converted);
133- }
134-
135- @Override
136- public TypeToken<Object> getPivotType() {
137- return enumType.pivotType;
138- }
139- }
140-
14185 private static class ReflectionFactory implements Factory {
14286
14387 public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
@@ -150,10 +94,6 @@
15094 try {
15195 PropertyDescriptor pd = new PropertyDescriptor(fieldName, field.getDeclaringClass());
15296
153- if (field.getType().isEnum()) {
154- return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field), columnCounter);
155- }
156-
15797 for (Class<?> udt : TypeMappings.findUDTs(field.getGenericType()))
15898 mappingManager.getUDTCodec(udt);
15999
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +1 −1
@@ -52,7 +52,7 @@
5252 if (customCodec != null)
5353 value = row.get(name, customCodec);
5454 else
55- value = row.get(name, cm.getPivotType());
55+ value = row.get(name, cm.getJavaType());
5656
5757 if (shouldSetValue(value)) {
5858 cm.setValue(entity, value);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +0 −8
@@ -24,8 +24,6 @@
2424
2525 import com.google.common.collect.Sets;
2626
27-import com.datastax.driver.core.TupleValue;
28-import com.datastax.driver.core.UDTValue;
2927 import com.datastax.driver.mapping.annotations.UDT;
3028
3129 /**
@@ -53,12 +51,6 @@
5351 return klass.isAnnotationPresent(UDT.class);
5452 }
5553
56- static boolean mapsToUserTypeOrTuple(Class<?> klass) {
57- return isMappedUDT(klass) ||
58- klass.equals(UDTValue.class) ||
59- klass.equals(TupleValue.class);
60- }
61-
6254 /**
6355 * Traverses the type of a Java field or parameter to find classes annotated with @UDT.
6456 * This will recurse into nested collections, e.g. List<Set<TheMappedUDT>>
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Enumerated.java +0 −41
@@ -1,41 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.mapping.annotations;
17-
18-import java.lang.annotation.ElementType;
19-import java.lang.annotation.Retention;
20-import java.lang.annotation.RetentionPolicy;
21-import java.lang.annotation.Target;
22-
23-import com.datastax.driver.mapping.EnumType;
24-
25-/**
26- * Defines that the annotated field (that must be a Java Enum) must be
27- * persisted as an enumerated type.
28- * <p>
29- * The optional {@link EnumType} value defined how the enumeration must be
30- * persisted.
31- */
32-@Target(value = {ElementType.FIELD, ElementType.PARAMETER})
33-@Retention(RetentionPolicy.RUNTIME)
34-public @interface Enumerated {
35- /**
36- * How the enumeration must be persisted.
37- *
38- * @return the {@link EnumType} to use for mapping this enumeration.
39- */
40- EnumType value() default EnumType.STRING;
41-}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +2 −59
@@ -23,7 +23,6 @@
2323 import static org.assertj.core.api.Assertions.assertThat;
2424
2525 import com.datastax.driver.core.CCMBridge;
26-import com.datastax.driver.core.ResultSet;
2726 import com.datastax.driver.core.Row;
2827 import com.datastax.driver.core.utils.CassandraVersion;
2928 import com.datastax.driver.mapping.annotations.*;
@@ -39,36 +38,6 @@
3938 );
4039 }
4140
42- @Test(groups = "short")
43- public void should_allow_enum_as_int_in_accessor_params() {
44- UserAccessor accessor = new MappingManager(session)
45- .createAccessor(UserAccessor.class);
46-
47- accessor.addUser(0, Enum.FEMALE);
48- accessor.addUser(1, Enum.MALE);
49-
50- assertThat(accessor.getUser(Enum.MALE).one().getGender()).isEqualTo(Enum.MALE);
51- assertThat(accessor.getUser(Enum.MALE).one().getKey()).isEqualTo(1);
52-
53- assertThat(accessor.getUser(Enum.FEMALE).one().getGender()).isEqualTo(Enum.FEMALE);
54- assertThat(accessor.getUser(Enum.FEMALE).one().getKey()).isEqualTo(0);
55- }
56-
57- @Test(groups = "short")
58- public void should_allow_enum_as_string_in_accessor_params() {
59- UserAccessor accessor = new MappingManager(session)
60- .createAccessor(UserAccessor.class);
61-
62- accessor.addUserStr(0, Enum.FEMALE);
63- accessor.addUserStr(1, Enum.MALE);
64-
65- assertThat(accessor.getUserStr(Enum.MALE).one().getGender()).isEqualTo(Enum.MALE);
66- assertThat(accessor.getUserStr(Enum.MALE).one().getKey()).isEqualTo(1);
67-
68- assertThat(accessor.getUserStr(Enum.FEMALE).one().getGender()).isEqualTo(Enum.FEMALE);
69- assertThat(accessor.getUserStr(Enum.FEMALE).one().getKey()).isEqualTo(0);
70- }
71-
7241 @Test(groups = "short")
7342 @CassandraVersion(major = 2.0, description = "Uses named parameters")
7443 public void should_allow_less_parameters_than_bind_markers_if_there_are_repeated_names() {
@@ -118,21 +87,6 @@
11887 MALE, FEMALE
11988 }
12089
121- @Accessor
122- public interface UserAccessor {
123- @Query("select * from user where gender=?")
124- Result<User> getUser(@Enumerated(EnumType.ORDINAL) Enum value);
125-
126- @Query("select * from user_str where gender=?")
127- Result<UserStr> getUserStr(@Enumerated(EnumType.STRING) Enum value);
128-
129- @Query("insert into user (key, gender) values (?,?)")
130- ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value);
131-
132- @Query("insert into user_str (key, gender) values (?,?)")
133- ResultSet addUserStr(int key, @Enumerated(EnumType.STRING) Enum value);
134- }
135-
13690 /** Tests various ways to match method parameters to query bind markers. */
13791 @Accessor
13892 public interface UserPhoneAccessor {
@@ -176,15 +130,11 @@
176130 @PartitionKey
177131 private int key;
178132
179- @Enumerated(EnumType.ORDINAL)
180- private Enum gender;
181-
182133 public User() {
183134 }
184135
185- public User(int k, Enum val) {
136+ public User(int k) {
186137 this.key = k;
187- this.gender = val;
188138 }
189139
190140 public int getKey() {
@@ -195,13 +145,6 @@
195145 this.key = pk;
196146 }
197147
198- public Enum getGender() {
199- return this.gender;
200- }
201-
202- public void setGender(Enum val) {
203- this.gender = val;
204- }
205148 }
206149
207150 @Table(name = "user")
@@ -235,4 +178,4 @@
235178 this.gender = val;
236179 }
237180 }
238-}
No newline at the end of the file
181+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCustomCodecTest.java +44 −1
@@ -19,10 +19,12 @@
1919 import java.util.Collection;
2020 import java.util.Map;
2121
22-import com.datastax.driver.core.utils.CassandraVersion;
2322 import com.google.common.base.Optional;
23+import com.google.common.base.Predicate;
2424 import com.google.common.collect.ImmutableMap;
2525 import com.google.common.collect.Lists;
26+import com.google.common.reflect.TypeParameter;
27+import com.google.common.reflect.TypeToken;
2628 import org.testng.annotations.Test;
2729
2830 import static org.assertj.core.api.Assertions.assertThat;
@@ -30,6 +32,7 @@
3032
3133 import com.datastax.driver.core.*;
3234 import com.datastax.driver.core.exceptions.InvalidTypeException;
35+import com.datastax.driver.core.utils.CassandraVersion;
3336 import com.datastax.driver.mapping.annotations.*;
3437
3538 @CassandraVersion(major=2.1)
@@ -556,6 +559,46 @@
556559 }
557560 }
558561
562+ /**
563+ * This class is a copy of GuavaOptionalCodec declared in the extras module,
564+ * to avoid circular dependencies between Maven modules.
565+ */
566+ public static class OptionalCodec<T> extends MappingCodec<Optional<T>, T> {
567+
568+ private final Predicate<T> isAbsent;
569+
570+ public OptionalCodec(TypeCodec<T> codec) {
571+ super(codec, new TypeToken<Optional<T>>(){}.where(new TypeParameter<T>(){}, codec.getJavaType()));
572+ this.isAbsent = new Predicate<T>() {
573+ @Override
574+ public boolean apply(T input) {
575+ return input == null
576+ || input instanceof Collection && ((Collection)input).isEmpty()
577+ || input instanceof Map && ((Map)input).isEmpty();
578+ }
579+ };
580+ }
581+
582+ @Override
583+ protected Optional<T> deserialize(T value) {
584+ return isAbsent(value) ? Optional.<T>absent() : Optional.fromNullable(value);
585+ }
586+
587+ @Override
588+ protected T serialize(Optional<T> value) {
589+ return value.isPresent() ? value.get() : absentValue();
590+ }
591+
592+ protected T absentValue() {
593+ return null;
594+ }
595+
596+ protected boolean isAbsent(T value) {
597+ return isAbsent.apply(value);
598+ }
599+
600+ }
601+
559602 private static class NoDefaultConstructorCodec extends TypeCodec<String> {
560603
561604 public NoDefaultConstructorCodec(DataType cqlType, Class<String> javaClass) {
deleted driver-mapping/src/test/java/com/datastax/driver/mapping/MapperEnumTest.java +0 −130
@@ -1,130 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.mapping;
17-
18-import java.util.Collection;
19-
20-import com.datastax.driver.mapping.annotations.Enumerated;
21-import com.datastax.driver.mapping.annotations.PartitionKey;
22-import com.datastax.driver.mapping.annotations.Table;
23-import com.google.common.collect.Lists;
24-import org.testng.annotations.Test;
25-
26-import static org.junit.Assert.assertNull;
27-
28-import com.datastax.driver.core.CCMBridge;
29-
30-/**
31- * Covers handling of enum fields by the mapper.
32- */
33-public class MapperEnumTest extends CCMBridge.PerClassSingleNodeCluster {
34-
35- @Override
36- protected Collection<String> getTableDefinitions() {
37- return Lists.newArrayList("CREATE TABLE asOrdinal (k int primary key, v int)",
38- "CREATE TABLE asString (k int primary key, v text)");
39- }
40-
41- public enum Enum {
42- FOO, BAR
43- }
44-
45- @Test(groups = "short")
46- public void should_handle_null_enum_as_ordinal() {
47- Mapper<AsOrdinal> mapper = new MappingManager(session).mapper(AsOrdinal.class);
48-
49- mapper.save(new AsOrdinal(1, null));
50- AsOrdinal o = mapper.get(1);
51-
52- assertNull(o.getV());
53- }
54-
55- @Test(groups = "short")
56- public void should_handle_null_enum_as_string() {
57- Mapper<AsString> mapper = new MappingManager(session).mapper(AsString.class);
58-
59- mapper.save(new AsString(1, null));
60- AsString o = mapper.get(1);
61-
62- assertNull(o.getV());
63- }
64-
65- @Table(name = "asOrdinal")
66- public static class AsOrdinal {
67- @PartitionKey
68- private int k;
69-
70- @Enumerated(EnumType.ORDINAL)
71- private Enum v;
72-
73- public AsOrdinal(Integer k, Enum v) {
74- this.k = k;
75- this.v = v;
76- }
77-
78- public AsOrdinal() {
79- }
80-
81- public int getK() {
82- return k;
83- }
84-
85- public void setK(int k) {
86- this.k = k;
87- }
88-
89- public Enum getV() {
90- return v;
91- }
92-
93- public void setV(Enum v) {
94- this.v = v;
95- }
96- }
97-
98- @Table(name = "asString")
99- public static class AsString {
100- @PartitionKey
101- private int k;
102-
103- @Enumerated(EnumType.STRING)
104- private Enum v;
105-
106- public AsString(Integer k, Enum v) {
107- this.k = k;
108- this.v = v;
109- }
110-
111- public AsString() {
112- }
113-
114- public int getK() {
115- return k;
116- }
117-
118- public void setK(int k) {
119- this.k = k;
120- }
121-
122- public Enum getV() {
123- return v;
124- }
125-
126- public void setV(Enum v) {
127- this.v = v;
128- }
129- }
130-}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +13 −41
@@ -28,7 +28,6 @@
2828 import static org.assertj.core.api.Assertions.assertThat;
2929 import static org.testng.Assert.*;
3030
31-import com.datastax.driver.mapping.MapperTest.User.Gender;
3231 import com.datastax.driver.mapping.annotations.*;
3332 import com.datastax.driver.core.*;
3433 import com.datastax.driver.core.utils.UUIDs;
@@ -38,6 +37,7 @@
3837 */
3938 public class MapperTest extends CCMBridge.PerClassSingleNodeCluster {
4039
40+ @Override
4141 protected Collection<String> getTableDefinitions() {
4242 // We'll allow to generate those create statement from the annotated entities later, but it's currently
4343 // a TODO
@@ -56,6 +56,7 @@
5656 *
5757 * And the next step will be to support UDT (which should be relatively simple).
5858 */
59+ @SuppressWarnings("unused")
5960 @Table(name = "users",
6061 readConsistency="QUORUM",
6162 writeConsistency="QUORUM")
@@ -64,8 +65,6 @@
6465 // Dummy constant to test that static fields are properly ignored
6566 public static final int FOO = 1;
6667
67- public enum Gender { FEMALE, MALE }
68-
6968 @PartitionKey
7069 @Column(name = "user_id")
7170 private UUID userId;
@@ -75,15 +74,12 @@
7574 @Column // not strictly required, but we want to check that the annotation works without a name
7675 private int year;
7776
78- private Gender gender;
79-
8077 public User() {}
8178
82- public User(String name, String email, Gender gender) {
79+ public User(String name, String email) {
8380 this.userId = UUIDs.random();
8481 this.name = name;
8582 this.email = email;
86- this.gender = gender;
8783 }
8884
8985 public UUID getUserId() {
@@ -114,14 +110,6 @@
114110 return year;
115111 }
116112
117- public void setGender(Gender gender) {
118- this.gender = gender;
119- }
120-
121- public Gender getGender() {
122- return gender;
123- }
124-
125113 public void setYear(int year) {
126114 this.year = year;
127115 }
@@ -135,13 +123,12 @@
135123 return Objects.equal(userId, that.userId)
136124 && Objects.equal(name, that.name)
137125 && Objects.equal(email, that.email)
138- && Objects.equal(year, that.year)
139- && Objects.equal(gender, that.gender);
126+ && Objects.equal(year, that.year);
140127 }
141128
142129 @Override
143130 public int hashCode() {
144- return Objects.hashCode(userId, name, email, year, gender);
131+ return Objects.hashCode(userId, name, email, year);
145132 }
146133 }
147134
@@ -151,6 +138,7 @@
151138 * the order must be specified (@ClusteringColumn(0), @ClusteringColumn(1), ...).
152139 * The same stands for the @PartitionKey.
153140 */
141+ @SuppressWarnings("unused")
154142 @Table(name = "posts")
155143 public static class Post {
156144
@@ -268,7 +256,7 @@
268256 // harcoded arg0, arg1, .... A big annoying, and apparently Java 8 will fix that
269257 // somehow, but well, not a huge deal.
270258 @Query("SELECT * FROM posts WHERE user_id=:userId AND post_id=:postId")
271- public Post getOne(@Param("userId") UUID userId,
259+ Post getOne(@Param("userId") UUID userId,
272260 @Param("postId") UUID postId);
273261
274262 // Note that the following method will be asynchronous (it will use executeAsync
@@ -276,23 +264,16 @@
276264 // that we need to map the result to the Post entity thanks to the return type.
277265 @Query("SELECT * FROM posts WHERE user_id=?")
278266 @QueryParameters(consistency="QUORUM")
279- public ListenableFuture<Result<Post>> getAllAsync(UUID userId);
267+ ListenableFuture<Result<Post>> getAllAsync(UUID userId);
280268
281269 // The method above actually query stuff, but if a method is declared to return
282270 // a Statement, it will not execute anything, but just return you the BoundStatement
283271 // ready for execution. That way, you can batch stuff for instance (see usage below).
284272 @Query("UPDATE posts SET content=? WHERE user_id=? AND post_id=?")
285- public Statement updateContentQuery(String newContent, UUID userId, UUID postId);
273+ Statement updateContentQuery(String newContent, UUID userId, UUID postId);
286274
287275 @Query("SELECT * FROM posts")
288- public Result<Post> getAll();
289- }
290-
291- @Accessor
292- public interface UserAccessor {
293- // Demonstrates use of an enum as an accessor parameter
294- @Query("UPDATE users SET name=?, gender=? WHERE user_id=?")
295- ResultSet updateNameAndGender(String name, Gender gender, UUID userId);
276+ Result<Post> getAll();
296277 }
297278
298279 @Test(groups = "short")
@@ -302,7 +283,7 @@
302283 // supported by the Mapper object.
303284 Mapper<User> m = new MappingManager(session).mapper(User.class);
304285
305- User u1 = new User("Paul", "paul@yahoo.com", User.Gender.MALE);
286+ User u1 = new User("Paul", "paul@yahoo.com");
306287 u1.setYear(2014);
307288 m.save(u1);
308289
@@ -320,7 +301,7 @@
320301
321302 Mapper<Post> m = manager.mapper(Post.class);
322303
323- User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
304+ User u1 = new User("Paul", "paul@gmail.com");
324305 Post p1 = new Post(u1, "Something about mapping");
325306 Post p2 = new Post(u1, "Something else");
326307 Post p3 = new Post(u1, "Something more");
@@ -372,15 +353,6 @@
372353
373354 assertTrue(postAccessor.getAllAsync(u1.getUserId()).get().isExhausted());
374355
375- // Pass an enum constant as an accessor parameter
376- UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
377- userAccessor.updateNameAndGender("Paule", User.Gender.FEMALE, u1.getUserId());
378- Mapper<User> userMapper = manager.mapper(User.class);
379- assertEquals(userMapper.get(u1.getUserId()).getGender(), User.Gender.FEMALE);
380-
381- // Test that an enum value can be unassigned through an accessor (set to null).
382- userAccessor.updateNameAndGender("Paule", null, u1.getUserId());
383- assertEquals(userMapper.get(u1.getUserId()).getGender(), null);
384356 }
385357
386358 @Test(groups="short")
@@ -390,7 +362,7 @@
390362 Mapper<Post> m = manager.mapper(Post.class);
391363
392364 // Insert a few posts
393- User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
365+ User u1 = new User("Paul", "paul@gmail.com");
394366 Post p1 = new Post(u1, "Something about mapping");
395367 Post p2 = new Post(u1, "Something else");
396368 Post p3 = new Post(u1, "Something more");
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +41 −6
@@ -39,7 +39,7 @@
3939 public class MapperUDTTest extends CCMBridge.PerClassSingleNodeCluster {
4040
4141 protected Collection<String> getTableDefinitions() {
42- return Arrays.asList("CREATE TYPE address (street text, city text, zip_code int, phones set<text>)",
42+ return Arrays.asList("CREATE TYPE address (street text, city text, \"ZIP_code\" int, phones set<text>)",
4343 "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
4444 }
4545
@@ -113,6 +113,8 @@
113113
114114 @Override
115115 public boolean equals(Object other) {
116+ if (this == other)
117+ return true;
116118 if (other instanceof User) {
117119 User that = (User) other;
118120 return Objects.equal(this.userId, that.userId) &&
@@ -122,6 +124,21 @@
122124 }
123125 return false;
124126 }
127+
128+ @Override
129+ public int hashCode() {
130+ return Objects.hashCode(this.userId, this.name, this.mainAddress, this.otherAddresses);
131+ }
132+
133+ @Override
134+ public String toString() {
135+ return Objects.toStringHelper(User.class)
136+ .add("userId", userId)
137+ .add("name", name)
138+ .add("mainAddress", mainAddress)
139+ .add("otherAddresses", otherAddresses)
140+ .toString();
141+ }
125142 }
126143
127144 @UDT(name = "address")
@@ -130,12 +147,13 @@
130147 // Dummy constant to test that static fields are properly ignored
131148 public static final int FOO = 1;
132149
133- private String street;
134-
135150 @Field // not strictly required, but we want to check that the annotation works without a name
136151 private String city;
137152
138- @Field(name = "zip_code")
153+ // Declared out of order compared to the UDT definition, to make sure that we serialize fields in the correct order (JAVA-884)
154+ private String street;
155+
156+ @Field(name = "ZIP_code", caseSensitive = true)
139157 private int zipCode;
140158
141159 private Set<String> phones;
@@ -187,6 +205,8 @@
187205
188206 @Override
189207 public boolean equals(Object other) {
208+ if (this == other)
209+ return true;
190210 if (other instanceof Address) {
191211 Address that = (Address) other;
192212 return Objects.equal(this.street, that.street) &&
@@ -196,6 +216,21 @@
196216 }
197217 return false;
198218 }
219+
220+ @Override
221+ public int hashCode() {
222+ return Objects.hashCode(this.street, this.city, this.zipCode, this.phones);
223+ }
224+
225+ @Override
226+ public String toString() {
227+ return Objects.toStringHelper(Address.class)
228+ .add("street", street)
229+ .add("city", city)
230+ .add("zip", zipCode)
231+ .add("phones", phones)
232+ .toString();
233+ }
199234 }
200235
201236 @Accessor
@@ -286,9 +321,9 @@
286321 UUID userId = UUIDs.random();
287322
288323 // Create a user.
289- session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', zip_code: 89898, phones: {'8675309'}} " +
324+ session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', \"ZIP_code\": 89898, phones: {'8675309'}} " +
290325 " WHERE user_id=" + TypeCodec.uuid().format(userId));
291- session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', zip_code: 49553, phones: {'8675039'}} " +
326+ session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', \"ZIP_code\": 49553, phones: {'8675039'}} " +
292327 " WHERE user_Id=" + TypeCodec.uuid().format(userId));
293328
294329 // Get the user.
modified features/object_mapper/creating/README.md +0 −25
@@ -82,31 +82,6 @@
8282 [cc]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/ClusteringColumn.html
8383 [pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html
8484
85-#### Enumerations
86-
87-[@Enumerated][enum] is used to map Java enumerations. Since Cassandra
88-does not support enumerations, the object mapper defines two ways to
89-persist an enum value :
90-
91-- `EnumType.ORDINAL` : the value is persisted as a Cassandra's `int` and
92- its value is its position in the enum.
93-- `EnumType.STRING` : the value is persisted as a Cassandra's `text` and
94- its value is its name in the enum.
95-
96-According to the chosen type, the matching database column must be the
97-same type.
98-
99-```
100-CREATE TABLE person (id uuid PRIMARY KEY, name text, gender int);
101-```
102-
103-```java
104-@Enumerated(EnumType.ORDINAL)
105-private Gender gender;
106-```
107-
108-[enum]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Enumerated.html
109-
11085 #### Computed fields
11186
11287 [@Computed][computed] can be used on fields that are the result of a
modified pom.xml +80 −6
@@ -36,6 +36,7 @@
3636 <modules>
3737 <module>driver-core</module>
3838 <module>driver-mapping</module>
39+ <module>driver-extras</module>
3940 <module>driver-examples</module>
4041 <module>driver-dse</module>
4142 <module>driver-dist</module>
@@ -57,8 +58,11 @@
5758 <testng.version>6.8.8</testng.version>
5859 <assertj.version>1.7.0</assertj.version>
5960 <mockito.version>1.10.8</mockito.version>
61+ <commons-exec.version>1.3</commons-exec.version>
6062 <scassandra.version>0.10.0</scassandra.version>
6163 <main.basedir>${project.basedir}</main.basedir>
64+ <!-- Set default javadoc.opts, overriden by profiles -->
65+ <javadoc.opts></javadoc.opts>
6266 </properties>
6367
6468 <dependencies>
@@ -78,6 +82,7 @@
7882 </dependencies>
7983
8084 <profiles>
85+
8186 <profile>
8287 <id>doclint-java8-disable</id>
8388 <activation>
@@ -87,19 +92,55 @@
8792 <javadoc.opts>-Xdoclint:none</javadoc.opts>
8893 </properties>
8994 </profile>
95+
96+ <profile>
97+ <id>enforce-java8</id>
98+ <build>
99+ <plugins>
100+ <plugin>
101+ <groupId>org.apache.maven.plugins</groupId>
102+ <artifactId>maven-enforcer-plugin</artifactId>
103+ <version>1.4.1</version>
104+ <executions>
105+ <execution>
106+ <id>enforce-java</id>
107+ <goals>
108+ <goal>enforce</goal>
109+ </goals>
110+ <configuration>
111+ <rules>
112+ <requireJavaVersion>
113+ <version>1.8</version>
114+ </requireJavaVersion>
115+ </rules>
116+ </configuration>
117+ </execution>
118+ </executions>
119+ </plugin>
120+ </plugins>
121+ </build>
122+ </profile>
123+
90124 </profiles>
91125
92126 <build>
93127 <plugins>
94128 <plugin>
95129 <artifactId>maven-compiler-plugin</artifactId>
96- <version>3.1</version>
130+ <version>3.3</version>
97131 <configuration>
98132 <source>${java.version}</source>
99133 <target>${java.version}</target>
100134 <optimize>true</optimize>
101135 <showDeprecation>true</showDeprecation>
102136 <showWarnings>true</showWarnings>
137+ <!--
138+ Avoids warnings when cross-compiling to older source levels, see
139+ https://blogs.oracle.com/darcy/entry/bootclasspath_older_source
140+ -->
141+ <compilerArgument>-Xlint:-options</compilerArgument>
142+ <!-- this actually means: use incremental compilation -->
143+ <useIncrementalCompilation>false</useIncrementalCompilation>
103144 </configuration>
104145 </plugin>
105146 <plugin>
@@ -120,8 +161,9 @@
120161 <artifactId>maven-javadoc-plugin</artifactId>
121162 <version>2.9.1</version>
122163 <configuration>
164+ <verbose>false</verbose>
123165 <!-- I can haz math in my javadoc (see http://zverovich.net/2012/01/14/beautiful-math-in-javadoc.html) -->
124- <additionalparam>-header '&lt;script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"&gt;&lt;/script&gt;'</additionalparam>
166+ <additionalparam>${javadoc.opts} -header '&lt;script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"&gt;&lt;/script&gt;'</additionalparam>
125167 </configuration>
126168 <executions>
127169 <execution>
@@ -129,9 +171,6 @@
129171 <goals>
130172 <goal>jar</goal>
131173 </goals>
132- <configuration>
133- <additionalparam>${javadoc.opts}</additionalparam>
134- </configuration>
135174 </execution>
136175 </executions>
137176 </plugin>
@@ -141,12 +180,13 @@
141180 <version>2.5</version>
142181 <configuration>
143182 <tagNameFormat>@{project.version}</tagNameFormat>
183+ <arguments>-Penforce-java8</arguments>
144184 </configuration>
145185 </plugin>
146186 <plugin>
147187 <groupId>org.codehaus.mojo</groupId>
148188 <artifactId>clirr-maven-plugin</artifactId>
149- <version>2.6.1</version>
189+ <version>2.7</version>
150190 <executions>
151191 <execution>
152192 <phase>compile</phase>
@@ -166,6 +206,19 @@
166206 <exclude>com/datastax/driver/core/Connection$*</exclude>
167207 </excludes>
168208 </configuration>
209+ <!--
210+ Workaround to make clirr plugin work with Java 8.
211+ The bug is actually in the BCEL library,
212+ see https://issues.apache.org/jira/browse/BCEL-173.
213+ See also https://github.com/RichardWarburton/lambda-behave/issues/31#issuecomment-86052095
214+ -->
215+ <dependencies>
216+ <dependency>
217+ <groupId>com.google.code.findbugs</groupId>
218+ <artifactId>bcel-findbugs</artifactId>
219+ <version>6.0</version>
220+ </dependency>
221+ </dependencies>
169222 </plugin>
170223 <plugin>
171224 <groupId>org.codehaus.mojo</groupId>
@@ -226,6 +279,27 @@
226279 </execution>
227280 </executions>
228281 </plugin>
282+ <plugin>
283+ <groupId>org.codehaus.mojo</groupId>
284+ <artifactId>animal-sniffer-maven-plugin</artifactId>
285+ <version>1.14</version>
286+ <configuration>
287+ <signature>
288+ <groupId>org.codehaus.mojo.signature</groupId>
289+ <artifactId>java16</artifactId>
290+ <version>1.0</version>
291+ </signature>
292+ </configuration>
293+ <executions>
294+ <execution>
295+ <id>check</id>
296+ <phase>compile</phase>
297+ <goals>
298+ <goal>check</goal>
299+ </goals>
300+ </execution>
301+ </executions>
302+ </plugin>
229303 </plugins>
230304 </build>
231305
modified upgrade_guide/README.md +22 −0
@@ -208,6 +208,28 @@
208208 20. `TableMetadata.Options` has been made a top-level class and renamed to
209209 `TableOptionsMetadata`. It is now also used by `MaterializedViewMetadata`.
210210
211+21. The mapper annotation `@Enumerated` has been removed, users should now
212+ use the newly-introduced `driver-extras` module to get automatic
213+ enum-to-CQL mappings. Two new codecs provide the same functionality:
214+ `EnumOrdinalCodec` and `EnumNameCodec`:
215+
216+ ```java
217+ enum Foo {...}
218+ enum Bar {...}
219+
220+ // register the appropriate codecs
221+ CodecRegistry.DEFAULT_INSTANCE
222+ .register(new EnumOrdinalCodec<Foo>(Foo.class))
223+ .register(new EnumNameCodec<Bar>(Bar.class))
224+
225+ // the following mappings are handled out-of-the-box
226+ @Table
227+ public class MyPojo {
228+ private Foo foo;
229+ private List<Bar> bars;
230+ ...
231+ }
232+ ```
211233
212234 ### 2.1.8
213235