kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 56ebe0d224e9b316b691c6b7582e7a120badce56d40a528430128316241b184f |
|---|---|
| Author | Alexandre Dutra <alexandre.dutra@datastax.com> · 2015-10-26 17:34 +01:00 |
| Committer | Alexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-17 14:51 +01:00 |
| Parents | 7aa30ea93ee9 |
69 files changed
modified README.md +11 −0
| @@ -90,6 +90,17 @@ | ||
| 90 | 90 | </dependency> |
| 91 | 91 | ``` |
| 92 | 92 | |
| 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 | + | |
| 93 | 104 | We also provide a [shaded JAR](features/shaded_jar/) |
| 94 | 105 | to avoid the explicit dependency to Netty. |
| 95 | 106 |
modified changelog/README.md +1 −0
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | - [improvement] JAVA-948: Don't limit cipher suites by default. |
| 15 | 15 | - [improvement] JAVA-917: Document SSL configuration. |
| 16 | 16 | - [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. | |
| 17 | 18 | |
| 18 | 19 | Merged from 2.1 branch: |
| 19 | 20 |
modified driver-core/pom.xml +1 −23
| @@ -121,21 +121,7 @@ | ||
| 121 | 121 | <dependency> |
| 122 | 122 | <groupId>org.apache.commons</groupId> |
| 123 | 123 | <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> | |
| 139 | 125 | <scope>test</scope> |
| 140 | 126 | </dependency> |
| 141 | 127 | |
| @@ -157,14 +143,6 @@ | ||
| 157 | 143 | </resource> |
| 158 | 144 | </resources> |
| 159 | 145 | <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> | |
| 168 | 146 | <plugin> |
| 169 | 147 | <groupId>org.apache.maven.plugins</groupId> |
| 170 | 148 | <artifactId>maven-jar-plugin</artifactId> |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java +9 −9
| @@ -24,9 +24,9 @@ | ||
| 24 | 24 | import com.google.common.base.Objects; |
| 25 | 25 | import com.google.common.reflect.TypeToken; |
| 26 | 26 | |
| 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; | |
| 30 | 30 | |
| 31 | 31 | abstract class AbstractAddressableByIndexData<T extends SettableByIndexData<T>> extends AbstractGettableByIndexData implements SettableByIndexData<T> { |
| 32 | 32 | |
| @@ -170,12 +170,12 @@ | ||
| 170 | 170 | |
| 171 | 171 | @Override |
| 172 | 172 | 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)); | |
| 174 | 174 | } |
| 175 | 175 | |
| 176 | 176 | @Override |
| 177 | 177 | 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)); | |
| 179 | 179 | } |
| 180 | 180 | |
| 181 | 181 | @SuppressWarnings("unchecked") |
| @@ -185,12 +185,12 @@ | ||
| 185 | 185 | |
| 186 | 186 | @Override |
| 187 | 187 | 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)); | |
| 189 | 189 | } |
| 190 | 190 | |
| 191 | 191 | @Override |
| 192 | 192 | 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)); | |
| 194 | 194 | } |
| 195 | 195 | |
| 196 | 196 | @SuppressWarnings("unchecked") |
| @@ -200,12 +200,12 @@ | ||
| 200 | 200 | |
| 201 | 201 | @Override |
| 202 | 202 | 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)); | |
| 204 | 204 | } |
| 205 | 205 | |
| 206 | 206 | @Override |
| 207 | 207 | 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)); | |
| 209 | 209 | } |
| 210 | 210 | |
| 211 | 211 | 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 @@ | ||
| 24 | 24 | import com.google.common.base.Objects; |
| 25 | 25 | import com.google.common.reflect.TypeToken; |
| 26 | 26 | |
| 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; | |
| 30 | 30 | |
| 31 | 31 | // 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). |
| 32 | 32 | abstract class AbstractData<T extends SettableData<T>> extends AbstractGettableData implements SettableData<T> { |
| @@ -364,12 +364,12 @@ | ||
| 364 | 364 | |
| 365 | 365 | @Override |
| 366 | 366 | 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)); | |
| 368 | 368 | } |
| 369 | 369 | |
| 370 | 370 | @Override |
| 371 | 371 | 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)); | |
| 373 | 373 | } |
| 374 | 374 | |
| 375 | 375 | @Override |
| @@ -404,12 +404,12 @@ | ||
| 404 | 404 | |
| 405 | 405 | @Override |
| 406 | 406 | 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)); | |
| 408 | 408 | } |
| 409 | 409 | |
| 410 | 410 | @Override |
| 411 | 411 | 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)); | |
| 413 | 413 | } |
| 414 | 414 | |
| 415 | 415 | @Override |
| @@ -444,12 +444,12 @@ | ||
| 444 | 444 | |
| 445 | 445 | @Override |
| 446 | 446 | 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)); | |
| 448 | 448 | } |
| 449 | 449 | |
| 450 | 450 | @Override |
| 451 | 451 | 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)); | |
| 453 | 453 | } |
| 454 | 454 | |
| 455 | 455 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +6 −6
| @@ -25,9 +25,9 @@ | ||
| 25 | 25 | |
| 26 | 26 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 27 | 27 | |
| 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; | |
| 31 | 31 | |
| 32 | 32 | abstract class AbstractGettableByIndexData implements GettableByIndexData { |
| 33 | 33 | |
| @@ -302,7 +302,7 @@ | ||
| 302 | 302 | @SuppressWarnings("unchecked") |
| 303 | 303 | public <T> List<T> getList(int i, TypeToken<T> elementsType) { |
| 304 | 304 | ByteBuffer value = getValue(i); |
| 305 | - TypeToken<List<T>> javaType = listOf(elementsType); | |
| 305 | + TypeToken<List<T>> javaType = TypeTokens.listOf(elementsType); | |
| 306 | 306 | return codecFor(i, javaType).deserialize(value, protocolVersion); |
| 307 | 307 | } |
| 308 | 308 | |
| @@ -322,7 +322,7 @@ | ||
| 322 | 322 | @SuppressWarnings("unchecked") |
| 323 | 323 | public <T> Set<T> getSet(int i, TypeToken<T> elementsType) { |
| 324 | 324 | ByteBuffer value = getValue(i); |
| 325 | - TypeToken<Set<T>> javaType = setOf(elementsType); | |
| 325 | + TypeToken<Set<T>> javaType = TypeTokens.setOf(elementsType); | |
| 326 | 326 | return codecFor(i, javaType).deserialize(value, protocolVersion); |
| 327 | 327 | } |
| 328 | 328 | |
| @@ -342,7 +342,7 @@ | ||
| 342 | 342 | @SuppressWarnings("unchecked") |
| 343 | 343 | public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) { |
| 344 | 344 | ByteBuffer value = getValue(i); |
| 345 | - TypeToken<Map<K, V>> javaType = mapOf(keysType, valuesType); | |
| 345 | + TypeToken<Map<K, V>> javaType = TypeTokens.mapOf(keysType, valuesType); | |
| 346 | 346 | return codecFor(i, javaType).deserialize(value, protocolVersion); |
| 347 | 347 | } |
| 348 | 348 |
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +1 −1
| @@ -242,7 +242,7 @@ | ||
| 242 | 242 | return null; |
| 243 | 243 | components[i] = value; |
| 244 | 244 | } |
| 245 | - return CodecUtils.compose(components); | |
| 245 | + return SimpleStatement.compose(components); | |
| 246 | 246 | } |
| 247 | 247 | } |
| 248 | 248 | return null; |
modified driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java +119 −189
| @@ -26,155 +26,15 @@ | ||
| 26 | 26 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 27 | 27 | |
| 28 | 28 | /** |
| 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. | |
| 34 | 30 | */ |
| 35 | 31 | public final class CodecUtils { |
| 36 | 32 | |
| 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); | |
| 162 | 34 | |
| 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); | |
| 173 | 36 | |
| 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(){} | |
| 178 | 38 | |
| 179 | 39 | /** |
| 180 | 40 | * Utility method that "packs" together a list of {@link ByteBuffer}s containing |
| @@ -186,27 +46,27 @@ | ||
| 186 | 46 | * @param version the protocol version to use |
| 187 | 47 | * @return The serialized collection |
| 188 | 48 | */ |
| 189 | - public static ByteBuffer pack(List<ByteBuffer> buffers, int elements, ProtocolVersion version) { | |
| 49 | + public static ByteBuffer pack(ByteBuffer[] buffers, int elements, ProtocolVersion version) { | |
| 190 | 50 | int size = 0; |
| 191 | 51 | for (ByteBuffer bb : buffers) { |
| 192 | 52 | int elemSize = sizeOfValue(bb, version); |
| 193 | 53 | size += elemSize; |
| 194 | 54 | } |
| 195 | 55 | ByteBuffer result = ByteBuffer.allocate(sizeOfCollectionSize(version) + size); |
| 196 | - writeCollectionSize(result, elements, version); | |
| 56 | + writeSize(result, elements, version); | |
| 197 | 57 | for (ByteBuffer bb : buffers) |
| 198 | - writeCollectionValue(result, bb, version); | |
| 58 | + writeValue(result, bb, version); | |
| 199 | 59 | return (ByteBuffer)result.flip(); |
| 200 | 60 | } |
| 201 | 61 | |
| 202 | 62 | /** |
| 203 | - * Utility method that reads the collection size. | |
| 63 | + * Utility method that reads a size value. | |
| 204 | 64 | * 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. | |
| 206 | 66 | * @param version The protocol version to use. |
| 207 | - * @return The collection size | |
| 67 | + * @return The size value. | |
| 208 | 68 | */ |
| 209 | - public static int readCollectionSize(ByteBuffer input, ProtocolVersion version) { | |
| 69 | + public static int readSize(ByteBuffer input, ProtocolVersion version) { | |
| 210 | 70 | switch (version) { |
| 211 | 71 | case V1: |
| 212 | 72 | case V2: |
| @@ -219,48 +79,140 @@ | ||
| 219 | 79 | } |
| 220 | 80 | } |
| 221 | 81 | |
| 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) { | |
| 231 | 91 | switch (version) { |
| 232 | 92 | case V1: |
| 233 | 93 | 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); | |
| 235 | 97 | break; |
| 236 | 98 | case V3: |
| 237 | 99 | case V4: |
| 238 | - size = input.getInt(); | |
| 100 | + output.putInt(size); | |
| 239 | 101 | break; |
| 240 | 102 | default: |
| 241 | 103 | throw version.unsupported(); |
| 242 | 104 | } |
| 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); | |
| 243 | 117 | return size < 0 ? null : readBytes(input, size); |
| 244 | 118 | } |
| 245 | 119 | |
| 120 | + /** | |
| 121 | + * Utility method that writes a value. | |
| 122 | + * Mainly intended for collection codecs when deserializing CQL collections. | |
| 246 | 123 | |
| 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) { | |
| 248 | 129 | switch (version) { |
| 249 | 130 | case V1: |
| 250 | 131 | 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()); | |
| 254 | 135 | break; |
| 255 | 136 | case V3: |
| 256 | 137 | 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 | + } | |
| 258 | 144 | break; |
| 259 | 145 | default: |
| 260 | 146 | throw version.unsupported(); |
| 261 | 147 | } |
| 262 | 148 | } |
| 263 | 149 | |
| 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 | + | |
| 264 | 216 | private static int sizeOfCollectionSize(ProtocolVersion version) { |
| 265 | 217 | switch (version) { |
| 266 | 218 | case V1: |
| @@ -274,28 +226,6 @@ | ||
| 274 | 226 | } |
| 275 | 227 | } |
| 276 | 228 | |
| 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 | - | |
| 299 | 229 | private static int sizeOfValue(ByteBuffer value, ProtocolVersion version) { |
| 300 | 230 | switch (version) { |
| 301 | 231 | case V1: |
modified driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java +37 −1
| @@ -286,11 +286,47 @@ | ||
| 286 | 286 | |
| 287 | 287 | void setCodecRegistry(CodecRegistry codecRegistry) { |
| 288 | 288 | for (Definition definition : byIdx) { |
| 289 | - CodecUtils.setCodecRegistry(definition.type, codecRegistry); | |
| 289 | + propagateCodecRegistry(definition.type, codecRegistry); | |
| 290 | 290 | } |
| 291 | 291 | this.codecRegistry = codecRegistry; |
| 292 | 292 | } |
| 293 | 293 | |
| 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 | + | |
| 294 | 330 | /** |
| 295 | 331 | * A column definition. |
| 296 | 332 | */ |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +1 −1
| @@ -136,7 +136,7 @@ | ||
| 136 | 136 | } |
| 137 | 137 | |
| 138 | 138 | public PreparedStatement setRoutingKey(ByteBuffer... routingKeyComponents) { |
| 139 | - this.routingKey = CodecUtils.compose(routingKeyComponents); | |
| 139 | + this.routingKey = SimpleStatement.compose(routingKeyComponents); | |
| 140 | 140 | return this; |
| 141 | 141 | } |
| 142 | 142 |
modified driver-core/src/main/java/com/datastax/driver/core/ParseUtils.java +326 −5
| @@ -15,12 +15,37 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 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 | + | |
| 18 | 25 | /** |
| 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). | |
| 20 | 27 | */ |
| 21 | -abstract class ParseUtils { | |
| 28 | +public abstract class ParseUtils { | |
| 22 | 29 | |
| 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 | + }; | |
| 24 | 49 | |
| 25 | 50 | /** |
| 26 | 51 | * Returns the index of the first character in toParse from idx that is not a "space". |
| @@ -149,15 +174,311 @@ | ||
| 149 | 174 | throw new IllegalArgumentException(); |
| 150 | 175 | } |
| 151 | 176 | |
| 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 | + */ | |
| 153 | 186 | public static boolean isIdentifierChar(int c) { |
| 154 | 187 | return (c >= '0' && c <= '9') |
| 155 | 188 | || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') |
| 156 | 189 | || c == '-' || c == '+' || c == '.' || c == '_' || c == '&'; |
| 157 | 190 | } |
| 158 | 191 | |
| 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 | + */ | |
| 160 | 202 | public static boolean isBlank(int c) { |
| 161 | 203 | return c == ' ' || c == '\t' || c == '\n'; |
| 162 | 204 | } |
| 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 | + | |
| 163 | 484 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SanityChecks.java +1 −1
| @@ -47,7 +47,7 @@ | ||
| 47 | 47 | */ |
| 48 | 48 | static void checkGuava() { |
| 49 | 49 | 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); | |
| 51 | 51 | Type type = mapOfString.getType(); |
| 52 | 52 | if(type instanceof ParameterizedType) { |
| 53 | 53 | ParameterizedType pType = (ParameterizedType)type; |
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +78 −2
| @@ -17,8 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.nio.ByteBuffer; |
| 19 | 19 | |
| 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; | |
| 22 | 21 | |
| 23 | 22 | /** |
| 24 | 23 | * A simple {@code RegularStatement} implementation built directly from a query |
| @@ -195,4 +194,81 @@ | ||
| 195 | 194 | return this; |
| 196 | 195 | } |
| 197 | 196 | |
| 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 | + | |
| 198 | 274 | } |
modified driver-core/src/main/java/com/datastax/driver/core/TupleValue.java +2 −14
| @@ -76,20 +76,8 @@ | ||
| 76 | 76 | @Override |
| 77 | 77 | public String toString() { |
| 78 | 78 | 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)); | |
| 93 | 81 | return sb.toString(); |
| 94 | 82 | } |
| 95 | 83 | } |
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +477 −387
| @@ -23,10 +23,7 @@ | ||
| 23 | 23 | import java.nio.ByteBuffer; |
| 24 | 24 | import java.nio.charset.Charset; |
| 25 | 25 | import java.text.ParseException; |
| 26 | -import java.text.ParsePosition; | |
| 27 | -import java.text.SimpleDateFormat; | |
| 28 | 26 | import java.util.*; |
| 29 | -import java.util.concurrent.TimeUnit; | |
| 30 | 27 | import java.util.regex.Pattern; |
| 31 | 28 | |
| 32 | 29 | import com.google.common.collect.ImmutableMap; |
| @@ -38,9 +35,9 @@ | ||
| 38 | 35 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 39 | 36 | import com.datastax.driver.core.utils.Bytes; |
| 40 | 37 | |
| 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; | |
| 44 | 41 | import static com.datastax.driver.core.DataType.*; |
| 45 | 42 | |
| 46 | 43 | /** |
| @@ -264,7 +261,7 @@ | ||
| 264 | 261 | * The returned instance is a singleton. |
| 265 | 262 | * @return the default codec for CQL type {@code time}. |
| 266 | 263 | **/ |
| 267 | - public static TypeCodec<Long> time() { | |
| 264 | + public static PrimitiveLongCodec time() { | |
| 268 | 265 | return TimeCodec.instance; |
| 269 | 266 | } |
| 270 | 267 | |
| @@ -778,49 +775,17 @@ | ||
| 778 | 775 | public String parse(String value) { |
| 779 | 776 | if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) |
| 780 | 777 | return null; |
| 781 | - if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'') | |
| 778 | + if (!ParseUtils.isQuoted(value)) | |
| 782 | 779 | throw new InvalidTypeException("text or varchar values must be enclosed by single quotes"); |
| 783 | 780 | |
| 784 | - return value.substring(1, value.length() - 1).replace("''", "'"); | |
| 781 | + return ParseUtils.unquote(value); | |
| 785 | 782 | } |
| 786 | 783 | |
| 787 | 784 | @Override |
| 788 | 785 | public String format(String value) { |
| 789 | 786 | if (value == null) |
| 790 | 787 | 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); | |
| 824 | 789 | } |
| 825 | 790 | |
| 826 | 791 | @Override |
| @@ -832,7 +797,7 @@ | ||
| 832 | 797 | * {@inheritDoc} |
| 833 | 798 | * |
| 834 | 799 | * 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. | |
| 836 | 801 | */ |
| 837 | 802 | @Override |
| 838 | 803 | public String deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) { |
| @@ -1243,7 +1208,7 @@ | ||
| 1243 | 1208 | return null; |
| 1244 | 1209 | |
| 1245 | 1210 | value = value.trim(); |
| 1246 | - if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'') | |
| 1211 | + if (!ParseUtils.isQuoted(value)) | |
| 1247 | 1212 | throw new InvalidTypeException(String.format("inet values must be enclosed in single quotes (\"%s\")", value)); |
| 1248 | 1213 | try { |
| 1249 | 1214 | return InetAddress.getByName(value.substring(1, value.length() - 1)); |
| @@ -1416,64 +1381,21 @@ | ||
| 1416 | 1381 | */ |
| 1417 | 1382 | private static class TimestampCodec extends TypeCodec<Date> { |
| 1418 | 1383 | |
| 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 | - | |
| 1436 | 1384 | private static final TimestampCodec instance = new TimestampCodec(); |
| 1437 | 1385 | |
| 1438 | - private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$"); | |
| 1439 | - | |
| 1440 | 1386 | private TimestampCodec() { |
| 1441 | 1387 | super(DataType.timestamp(), Date.class); |
| 1442 | 1388 | } |
| 1443 | 1389 | |
| 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 | - | |
| 1467 | 1390 | @Override |
| 1468 | 1391 | public Date parse(String value) { |
| 1469 | 1392 | if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) |
| 1470 | 1393 | return null; |
| 1471 | - | |
| 1472 | 1394 | // 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); | |
| 1475 | 1397 | |
| 1476 | - if (IS_LONG_PATTERN.matcher(value).matches()) { | |
| 1398 | + if (ParseUtils.isLongLiteral(value)) { | |
| 1477 | 1399 | try { |
| 1478 | 1400 | return new Date(Long.parseLong(value)); |
| 1479 | 1401 | } catch (NumberFormatException e) { |
| @@ -1482,7 +1404,7 @@ | ||
| 1482 | 1404 | } |
| 1483 | 1405 | |
| 1484 | 1406 | try { |
| 1485 | - return parseDate(value, iso8601Patterns); | |
| 1407 | + return ParseUtils.parseDate(value); | |
| 1486 | 1408 | } catch (ParseException e) { |
| 1487 | 1409 | throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); |
| 1488 | 1410 | } |
| @@ -1513,10 +1435,7 @@ | ||
| 1513 | 1435 | |
| 1514 | 1436 | private static final DateCodec instance = new DateCodec(); |
| 1515 | 1437 | |
| 1516 | - private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$"); | |
| 1517 | 1438 | 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); | |
| 1520 | 1439 | |
| 1521 | 1440 | private DateCodec() { |
| 1522 | 1441 | super(DataType.date(), LocalDate.class); |
| @@ -1527,69 +1446,58 @@ | ||
| 1527 | 1446 | if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) |
| 1528 | 1447 | return null; |
| 1529 | 1448 | |
| 1530 | - // strip enclosing single quotes, if any | |
| 1531 | 1449 | // 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; | |
| 1539 | 1456 | try { |
| 1540 | - cqlLong = Long.parseLong(value); | |
| 1457 | + unsigned = Long.parseLong(value); | |
| 1541 | 1458 | } 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); | |
| 1543 | 1466 | } |
| 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); | |
| 1551 | 1467 | } |
| 1552 | 1468 | |
| 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); | |
| 1560 | 1471 | return LocalDate.fromMillisSinceEpoch(date.getTime()); |
| 1472 | + } catch (ParseException e) { | |
| 1473 | + throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value), e); | |
| 1561 | 1474 | } |
| 1562 | - | |
| 1563 | - throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value)); | |
| 1564 | 1475 | } |
| 1565 | 1476 | |
| 1566 | 1477 | @Override |
| 1567 | 1478 | public String format(LocalDate value) { |
| 1568 | 1479 | if (value == null) |
| 1569 | 1480 | return "NULL"; |
| 1570 | - return "'" + value.toString() + "'"; | |
| 1481 | + return ParseUtils.quote(value.toString()); | |
| 1571 | 1482 | } |
| 1572 | 1483 | |
| 1573 | 1484 | @Override |
| 1574 | 1485 | 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); | |
| 1576 | 1490 | } |
| 1577 | 1491 | |
| 1578 | 1492 | @Override |
| 1579 | 1493 | 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); | |
| 1588 | 1499 | } |
| 1589 | 1500 | |
| 1590 | - private static int javaToProtocol(int j) { | |
| 1591 | - return j - Integer.MIN_VALUE; | |
| 1592 | - } | |
| 1593 | 1501 | } |
| 1594 | 1502 | |
| 1595 | 1503 | /** |
| @@ -1597,97 +1505,34 @@ | ||
| 1597 | 1505 | */ |
| 1598 | 1506 | private static class TimeCodec extends LongCodec { |
| 1599 | 1507 | |
| 1600 | - private static final Pattern IS_LONG_PATTERN = Pattern.compile("^-?\\d+$"); | |
| 1601 | - | |
| 1602 | 1508 | private static final TimeCodec instance = new TimeCodec(); |
| 1603 | 1509 | |
| 1604 | 1510 | private TimeCodec() { |
| 1605 | 1511 | super(DataType.time()); |
| 1606 | 1512 | } |
| 1607 | 1513 | |
| 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 | - | |
| 1669 | 1514 | @Override |
| 1670 | 1515 | public Long parse(String value) { |
| 1671 | 1516 | if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) |
| 1672 | 1517 | return null; |
| 1673 | 1518 | |
| 1674 | 1519 | // enclosing single quotes required, even for long literals |
| 1675 | - if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'') | |
| 1520 | + if (!ParseUtils.isQuoted(value)) | |
| 1676 | 1521 | throw new InvalidTypeException("time values must be enclosed by single quotes"); |
| 1677 | 1522 | value = value.substring(1, value.length() - 1); |
| 1678 | 1523 | |
| 1679 | - if (IS_LONG_PATTERN.matcher(value).matches()) { | |
| 1524 | + if (ParseUtils.isLongLiteral(value)) { | |
| 1680 | 1525 | try { |
| 1681 | 1526 | return Long.parseLong(value); |
| 1682 | 1527 | } 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); | |
| 1684 | 1529 | } |
| 1685 | 1530 | } |
| 1686 | 1531 | |
| 1687 | 1532 | 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); | |
| 1691 | 1536 | } |
| 1692 | 1537 | } |
| 1693 | 1538 | |
| @@ -1695,33 +1540,7 @@ | ||
| 1695 | 1540 | public String format(Long value) { |
| 1696 | 1541 | if (value == null) |
| 1697 | 1542 | 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)); | |
| 1725 | 1544 | } |
| 1726 | 1545 | |
| 1727 | 1546 | } |
| @@ -1740,7 +1559,7 @@ | ||
| 1740 | 1559 | try { |
| 1741 | 1560 | return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : UUID.fromString(value); |
| 1742 | 1561 | } 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); | |
| 1744 | 1563 | } |
| 1745 | 1564 | } |
| 1746 | 1565 | |
| @@ -1826,7 +1645,7 @@ | ||
| 1826 | 1645 | try { |
| 1827 | 1646 | return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : new BigInteger(value); |
| 1828 | 1647 | } 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); | |
| 1830 | 1649 | } |
| 1831 | 1650 | } |
| 1832 | 1651 | |
| @@ -1849,16 +1668,16 @@ | ||
| 1849 | 1668 | } |
| 1850 | 1669 | |
| 1851 | 1670 | /** |
| 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. | |
| 1855 | 1673 | */ |
| 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> { | |
| 1857 | 1675 | |
| 1858 | 1676 | protected final TypeCodec<E> eltCodec; |
| 1859 | 1677 | |
| 1860 | - private CollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) { | |
| 1678 | + protected AbstractCollectionCodec(CollectionType cqlType, TypeToken<C> javaType, TypeCodec<E> eltCodec) { | |
| 1861 | 1679 | super(cqlType, javaType); |
| 1680 | + checkArgument(cqlType.getName() == Name.LIST || cqlType.getName() == Name.SET, "Expecting list or set type, got %s", cqlType); | |
| 1862 | 1681 | this.eltCodec = eltCodec; |
| 1863 | 1682 | } |
| 1864 | 1683 | |
| @@ -1866,7 +1685,8 @@ | ||
| 1866 | 1685 | public ByteBuffer serialize(C value, ProtocolVersion protocolVersion) { |
| 1867 | 1686 | if (value == null) |
| 1868 | 1687 | return null; |
| 1869 | - List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(value.size()); | |
| 1688 | + int i = 0; | |
| 1689 | + ByteBuffer[] bbs = new ByteBuffer[value.size()]; | |
| 1870 | 1690 | for (E elt : value) { |
| 1871 | 1691 | if (elt == null) { |
| 1872 | 1692 | throw new NullPointerException("Collection elements cannot be null"); |
| @@ -1879,7 +1699,7 @@ | ||
| 1879 | 1699 | String.format("Invalid type for %s element, expecting %s but got %s", |
| 1880 | 1700 | cqlType, eltCodec.getJavaType(), elt.getClass()), e); |
| 1881 | 1701 | } |
| 1882 | - bbs.add(bb); | |
| 1702 | + bbs[i++] = bb; | |
| 1883 | 1703 | } |
| 1884 | 1704 | return CodecUtils.pack(bbs, value.size(), protocolVersion); |
| 1885 | 1705 | } |
| @@ -1890,15 +1710,15 @@ | ||
| 1890 | 1710 | return newInstance(0); |
| 1891 | 1711 | try { |
| 1892 | 1712 | 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); | |
| 1897 | 1717 | coll.add(eltCodec.deserialize(databb, protocolVersion)); |
| 1898 | 1718 | } |
| 1899 | 1719 | return coll; |
| 1900 | 1720 | } catch (BufferUnderflowException e) { |
| 1901 | - throw new InvalidTypeException("Not enough bytes to deserialize list"); | |
| 1721 | + throw new InvalidTypeException("Not enough bytes to deserialize collection", e); | |
| 1902 | 1722 | } |
| 1903 | 1723 | } |
| 1904 | 1724 | |
| @@ -1925,7 +1745,7 @@ | ||
| 1925 | 1745 | |
| 1926 | 1746 | int idx = ParseUtils.skipSpaces(value, 0); |
| 1927 | 1747 | 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))); | |
| 1929 | 1749 | |
| 1930 | 1750 | idx = ParseUtils.skipSpaces(value, idx); |
| 1931 | 1751 | |
| @@ -1938,7 +1758,7 @@ | ||
| 1938 | 1758 | try { |
| 1939 | 1759 | n = ParseUtils.skipCQLValue(value, idx); |
| 1940 | 1760 | } 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); | |
| 1942 | 1762 | } |
| 1943 | 1763 | |
| 1944 | 1764 | l.add(eltCodec.parse(value.substring(idx, n))); |
| @@ -1948,31 +1768,51 @@ | ||
| 1948 | 1768 | if (value.charAt(idx) == getClosingChar()) |
| 1949 | 1769 | return l; |
| 1950 | 1770 | 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))); | |
| 1952 | 1772 | |
| 1953 | 1773 | idx = ParseUtils.skipSpaces(value, idx); |
| 1954 | 1774 | } |
| 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())); | |
| 1956 | 1776 | } |
| 1957 | 1777 | |
| 1958 | 1778 | @Override |
| 1959 | 1779 | public boolean accepts(Object value) { |
| 1960 | 1780 | if (getJavaType().getRawType().isAssignableFrom(value.getClass())) { |
| 1961 | 1781 | // 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()) | |
| 1964 | 1784 | return true; |
| 1965 | - Object elt = list.iterator().next(); | |
| 1785 | + Object elt = coll.iterator().next(); | |
| 1966 | 1786 | return eltCodec.accepts(elt); |
| 1967 | 1787 | } |
| 1968 | 1788 | return false; |
| 1969 | 1789 | } |
| 1970 | 1790 | |
| 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); | |
| 1972 | 1798 | |
| 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 | + } | |
| 1974 | 1807 | |
| 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 | + } | |
| 1976 | 1816 | |
| 1977 | 1817 | } |
| 1978 | 1818 | |
| @@ -1980,25 +1820,15 @@ | ||
| 1980 | 1820 | * This codec maps a CQL {@link DataType#list(DataType) list type} to a Java {@link List}. |
| 1981 | 1821 | * Implementation note: this codec returns mutable, non thread-safe {@link ArrayList} instances. |
| 1982 | 1822 | */ |
| 1983 | - private static class ListCodec<T> extends CollectionCodec<T, List<T>> { | |
| 1823 | + private static class ListCodec<T> extends AbstractCollectionCodec<T, List<T>> { | |
| 1984 | 1824 | |
| 1985 | 1825 | 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); | |
| 1997 | 1827 | } |
| 1998 | 1828 | |
| 1999 | 1829 | @Override |
| 2000 | - protected char getClosingChar() { | |
| 2001 | - return ']'; | |
| 1830 | + protected List<T> newInstance(int size) { | |
| 1831 | + return new ArrayList<T>(size); | |
| 2002 | 1832 | } |
| 2003 | 1833 | |
| 2004 | 1834 | } |
| @@ -2007,40 +1837,30 @@ | ||
| 2007 | 1837 | * This codec maps a CQL {@link DataType#set(DataType) set type} to a Java {@link Set}. |
| 2008 | 1838 | * Implementation note: this codec returns mutable, non thread-safe {@link LinkedHashSet} instances. |
| 2009 | 1839 | */ |
| 2010 | - private static class SetCodec<T> extends CollectionCodec<T, Set<T>> { | |
| 1840 | + private static class SetCodec<T> extends AbstractCollectionCodec<T, Set<T>> { | |
| 2011 | 1841 | |
| 2012 | 1842 | 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); | |
| 2019 | 1844 | } |
| 2020 | 1845 | |
| 2021 | 1846 | @Override |
| 2022 | - protected char getOpeningChar() { | |
| 2023 | - return '{'; | |
| 1847 | + protected Set<T> newInstance(int size) { | |
| 1848 | + return new LinkedHashSet<T>(size); | |
| 2024 | 1849 | } |
| 2025 | 1850 | |
| 2026 | - @Override | |
| 2027 | - protected char getClosingChar() { | |
| 2028 | - return '}'; | |
| 2029 | - } | |
| 2030 | 1851 | } |
| 2031 | 1852 | |
| 2032 | 1853 | /** |
| 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}. | |
| 2035 | 1855 | */ |
| 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>> { | |
| 2037 | 1857 | |
| 2038 | - private final TypeCodec<K> keyCodec; | |
| 1858 | + protected final TypeCodec<K> keyCodec; | |
| 2039 | 1859 | |
| 2040 | - private final TypeCodec<V> valueCodec; | |
| 1860 | + protected final TypeCodec<V> valueCodec; | |
| 2041 | 1861 | |
| 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())); | |
| 2044 | 1864 | this.keyCodec = keyCodec; |
| 2045 | 1865 | this.valueCodec = valueCodec; |
| 2046 | 1866 | } |
| @@ -2070,7 +1890,7 @@ | ||
| 2070 | 1890 | idx = ParseUtils.skipSpaces(value, idx); |
| 2071 | 1891 | |
| 2072 | 1892 | if (value.charAt(idx) == '}') |
| 2073 | - return new LinkedHashMap<K, V>(0); | |
| 1893 | + return newInstance(0); | |
| 2074 | 1894 | |
| 2075 | 1895 | Map<K, V> m = new HashMap<K, V>(); |
| 2076 | 1896 | while (idx < value.length()) { |
| @@ -2134,7 +1954,8 @@ | ||
| 2134 | 1954 | public ByteBuffer serialize(Map<K, V> value, ProtocolVersion protocolVersion) { |
| 2135 | 1955 | if (value == null) |
| 2136 | 1956 | return null; |
| 2137 | - List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(2 * value.size()); | |
| 1957 | + int i = 0; | |
| 1958 | + ByteBuffer[] bbs = new ByteBuffer[2 * value.size()]; | |
| 2138 | 1959 | for (Map.Entry<K, V> entry : value.entrySet()) { |
| 2139 | 1960 | ByteBuffer bbk; |
| 2140 | 1961 | K key = entry.getKey(); |
| @@ -2144,7 +1965,7 @@ | ||
| 2144 | 1965 | try { |
| 2145 | 1966 | bbk = keyCodec.serialize(key, protocolVersion); |
| 2146 | 1967 | } 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); | |
| 2148 | 1969 | } |
| 2149 | 1970 | ByteBuffer bbv; |
| 2150 | 1971 | V v = entry.getValue(); |
| @@ -2154,10 +1975,10 @@ | ||
| 2154 | 1975 | try { |
| 2155 | 1976 | bbv = valueCodec.serialize(v, protocolVersion); |
| 2156 | 1977 | } 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); | |
| 2158 | 1979 | } |
| 2159 | - bbs.add(bbk); | |
| 2160 | - bbs.add(bbv); | |
| 1980 | + bbs[i++] = bbk; | |
| 1981 | + bbs[i++] = bbv; | |
| 2161 | 1982 | } |
| 2162 | 1983 | return CodecUtils.pack(bbs, value.size(), protocolVersion); |
| 2163 | 1984 | } |
| @@ -2165,46 +1986,135 @@ | ||
| 2165 | 1986 | @Override |
| 2166 | 1987 | public Map<K, V> deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) { |
| 2167 | 1988 | if (bytes == null || bytes.remaining() == 0) |
| 2168 | - return new LinkedHashMap<K, V>(0); | |
| 1989 | + return newInstance(0); | |
| 2169 | 1990 | try { |
| 2170 | 1991 | 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); | |
| 2173 | 1994 | 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); | |
| 2176 | 1997 | m.put(keyCodec.deserialize(kbb, protocolVersion), valueCodec.deserialize(vbb, protocolVersion)); |
| 2177 | 1998 | } |
| 2178 | 1999 | return m; |
| 2179 | 2000 | } 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); | |
| 2181 | 2002 | } |
| 2182 | 2003 | } |
| 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 | + | |
| 2183 | 2030 | } |
| 2184 | 2031 | |
| 2185 | 2032 | /** |
| 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. | |
| 2187 | 2037 | */ |
| 2188 | - private static class UDTCodec extends TypeCodec<UDTValue> { | |
| 2038 | + public abstract static class AbstractUDTCodec<T> extends TypeCodec<T> { | |
| 2189 | 2039 | |
| 2190 | - private final UserType definition; | |
| 2040 | + protected final UserType definition; | |
| 2191 | 2041 | |
| 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); | |
| 2194 | 2049 | this.definition = definition; |
| 2195 | 2050 | } |
| 2196 | 2051 | |
| 2197 | 2052 | @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(); | |
| 2200 | 2075 | } |
| 2201 | 2076 | |
| 2202 | 2077 | @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")) | |
| 2205 | 2115 | return null; |
| 2206 | 2116 | |
| 2207 | - UDTValue v = definition.newValue(); | |
| 2117 | + T v = newInstance(); | |
| 2208 | 2118 | |
| 2209 | 2119 | int idx = ParseUtils.skipSpaces(value, 0); |
| 2210 | 2120 | if (value.charAt(idx++) != '{') |
| @@ -2240,9 +2150,8 @@ | ||
| 2240 | 2150 | throw new InvalidTypeException(String.format("Cannot parse UDT value from \"%s\", invalid CQL value at character %d", value, idx), e); |
| 2241 | 2151 | } |
| 2242 | 2152 | |
| 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); | |
| 2246 | 2155 | idx = n; |
| 2247 | 2156 | |
| 2248 | 2157 | idx = ParseUtils.skipSpaces(value, idx); |
| @@ -2257,23 +2166,154 @@ | ||
| 2257 | 2166 | throw new InvalidTypeException(String.format("Malformed UDT value \"%s\", missing closing '}'", value)); |
| 2258 | 2167 | } |
| 2259 | 2168 | |
| 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 | + | |
| 2260 | 2240 | @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); | |
| 2265 | 2302 | } |
| 2266 | 2303 | |
| 2267 | 2304 | @Override |
| 2268 | - public ByteBuffer serialize(UDTValue value, ProtocolVersion protocolVersion) { | |
| 2305 | + public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) { | |
| 2269 | 2306 | if (value == null) |
| 2270 | 2307 | return null; |
| 2271 | 2308 | 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 | + } | |
| 2275 | 2315 | ByteBuffer result = ByteBuffer.allocate(size); |
| 2276 | - for (ByteBuffer bb : value.values) { | |
| 2316 | + for (ByteBuffer bb : elements) { | |
| 2277 | 2317 | if (bb == null) { |
| 2278 | 2318 | result.putInt(-1); |
| 2279 | 2319 | } else { |
| @@ -2285,54 +2325,42 @@ | ||
| 2285 | 2325 | } |
| 2286 | 2326 | |
| 2287 | 2327 | @Override |
| 2288 | - public UDTValue deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) { | |
| 2328 | + public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) { | |
| 2289 | 2329 | if (bytes == null) |
| 2290 | 2330 | return null; |
| 2291 | - // empty byte buffers will result in empty UDTValues | |
| 2331 | + // empty byte buffers will result in empty values | |
| 2292 | 2332 | ByteBuffer input = bytes.duplicate(); |
| 2293 | - UDTValue value = definition.newValue(); | |
| 2294 | - | |
| 2333 | + T value = newInstance(); | |
| 2295 | 2334 | int i = 0; |
| 2296 | - while (input.hasRemaining() && i < value.values.length) { | |
| 2335 | + while (input.hasRemaining() && i < definition.getComponentTypes().size()) { | |
| 2297 | 2336 | 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); | |
| 2299 | 2339 | } |
| 2300 | 2340 | return value; |
| 2301 | 2341 | } |
| 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 | - } | |
| 2322 | 2342 | |
| 2323 | 2343 | @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(); | |
| 2328 | 2356 | } |
| 2329 | 2357 | |
| 2330 | 2358 | @Override |
| 2331 | - public TupleValue parse(String value) { | |
| 2359 | + public T parse(String value) { | |
| 2332 | 2360 | if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) |
| 2333 | 2361 | return null; |
| 2334 | 2362 | |
| 2335 | - TupleValue v = definition.newValue(); | |
| 2363 | + T v = newInstance(); | |
| 2336 | 2364 | |
| 2337 | 2365 | int idx = ParseUtils.skipSpaces(value, 0); |
| 2338 | 2366 | if (value.charAt(idx++) != '(') |
| @@ -2352,9 +2380,8 @@ | ||
| 2352 | 2380 | throw new InvalidTypeException(String.format("Cannot parse tuple value from \"%s\", invalid CQL value at character %d", value, idx), e); |
| 2353 | 2381 | } |
| 2354 | 2382 | |
| 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); | |
| 2358 | 2385 | idx = n; |
| 2359 | 2386 | i += 1; |
| 2360 | 2387 | |
| @@ -2370,48 +2397,111 @@ | ||
| 2370 | 2397 | throw new InvalidTypeException(String.format("Malformed tuple value \"%s\", missing closing ')'", value)); |
| 2371 | 2398 | } |
| 2372 | 2399 | |
| 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 | + | |
| 2373 | 2464 | @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()); | |
| 2378 | 2469 | } |
| 2379 | 2470 | |
| 2380 | 2471 | @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) | |
| 2383 | 2479 | 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 | + } | |
| 2387 | 2482 | |
| 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); | |
| 2398 | 2488 | } |
| 2399 | 2489 | |
| 2400 | 2490 | @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 | + } | |
| 2407 | 2496 | |
| 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; | |
| 2414 | 2503 | } |
| 2504 | + | |
| 2415 | 2505 | } |
| 2416 | 2506 | |
| 2417 | 2507 | } |
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 @@ | ||
| 30 | 30 | } |
| 31 | 31 | |
| 32 | 32 | protected DataType getType(int i) { |
| 33 | - return definition.getFields()[i].getType(); | |
| 33 | + return definition.byIdx[i].getType(); | |
| 34 | 34 | } |
| 35 | 35 | |
| 36 | 36 | protected String getName(int i) { |
| 37 | - return definition.getFields()[i].getName(); | |
| 37 | + return definition.byIdx[i].getName(); | |
| 38 | 38 | } |
| 39 | 39 | |
| 40 | 40 | @Override |
| @@ -43,7 +43,7 @@ | ||
| 43 | 43 | } |
| 44 | 44 | |
| 45 | 45 | protected int[] getAllIndexesOf(String name) { |
| 46 | - int[] indexes = definition.getFieldIndicesByName().get(Metadata.handleId(name)); | |
| 46 | + int[] indexes = definition.byName.get(Metadata.handleId(name)); | |
| 47 | 47 | if (indexes == null) |
| 48 | 48 | throw new IllegalArgumentException(name + " is not a field defined in this UDT"); |
| 49 | 49 | return indexes; |
| @@ -78,23 +78,8 @@ | ||
| 78 | 78 | @Override |
| 79 | 79 | public String toString() { |
| 80 | 80 | 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)); | |
| 98 | 83 | return sb.toString(); |
| 99 | 84 | } |
| 100 | 85 | } |
modified driver-core/src/main/java/com/datastax/driver/core/UserType.java +3 −11
| @@ -40,11 +40,11 @@ | ||
| 40 | 40 | // Note that we don't expose the order of fields, from an API perspective this is a map |
| 41 | 41 | // of String->Field, but internally we care about the order because the serialization format |
| 42 | 42 | // of UDT expects a particular order. |
| 43 | - private final Field[] byIdx; | |
| 43 | + final Field[] byIdx; | |
| 44 | 44 | // For a given name, we can only have one field with that name, so we don't need a int[] in |
| 45 | 45 | // practice. However, storing one element arrays save allocations in UDTValue.getAllIndexesOf |
| 46 | 46 | // implementation. |
| 47 | - private final Map<String, int[]> byName; | |
| 47 | + final Map<String, int[]> byName; | |
| 48 | 48 | |
| 49 | 49 | UserType(String keyspace, String typeName, Collection<Field> fields, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { |
| 50 | 50 | super(DataType.Name.UDT); |
| @@ -178,14 +178,6 @@ | ||
| 178 | 178 | return true; |
| 179 | 179 | } |
| 180 | 180 | |
| 181 | - Field[] getFields() { | |
| 182 | - return byIdx; | |
| 183 | - } | |
| 184 | - | |
| 185 | - Map<String, int[]> getFieldIndicesByName() { | |
| 186 | - return byName; | |
| 187 | - } | |
| 188 | - | |
| 189 | 181 | @Override |
| 190 | 182 | public int hashCode() { |
| 191 | 183 | int result = name.hashCode(); |
| @@ -207,7 +199,7 @@ | ||
| 207 | 199 | return name.equals(other.name) |
| 208 | 200 | && keyspace.equals(other.keyspace) |
| 209 | 201 | && typeName.equals(other.typeName) |
| 210 | - && Arrays.equals(getFields(), other.getFields()); | |
| 202 | + && Arrays.equals(byIdx, other.byIdx); | |
| 211 | 203 | } |
| 212 | 204 | |
| 213 | 205 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +3 −6
| @@ -24,9 +24,6 @@ | ||
| 24 | 24 | import com.datastax.driver.core.*; |
| 25 | 25 | import com.datastax.driver.core.policies.RetryPolicy; |
| 26 | 26 | |
| 27 | -import static com.datastax.driver.core.CodecUtils.compose; | |
| 28 | -import static com.datastax.driver.core.CodecUtils.convert; | |
| 29 | - | |
| 30 | 27 | /** |
| 31 | 28 | * Common ancestor to the query builder built statements. |
| 32 | 29 | */ |
| @@ -68,7 +65,7 @@ | ||
| 68 | 65 | } |
| 69 | 66 | |
| 70 | 67 | // 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) { | |
| 72 | 69 | // we don't need to escape if it's lowercase and match non-quoted CQL3 ids. |
| 73 | 70 | return lowercaseId.matcher(ident).matches() ? ident : Metadata.quote(ident); |
| 74 | 71 | } |
| @@ -203,7 +200,7 @@ | ||
| 203 | 200 | } |
| 204 | 201 | return routingKeyParts.length == 1 |
| 205 | 202 | ? routingKeyParts[0] |
| 206 | - : compose(routingKeyParts); | |
| 203 | + : Utils.compose(routingKeyParts); | |
| 207 | 204 | } |
| 208 | 205 | |
| 209 | 206 | @Override |
| @@ -219,7 +216,7 @@ | ||
| 219 | 216 | @Override |
| 220 | 217 | public ByteBuffer[] getValues() { |
| 221 | 218 | maybeRebuildCache(); |
| 222 | - return values == null ? null : convert(values.toArray(), getProtocolVersion(), getCodecRegistry()); | |
| 219 | + return values == null ? null : Utils.convert(values.toArray(), getProtocolVersion(), getCodecRegistry()); | |
| 223 | 220 | } |
| 224 | 221 | |
| 225 | 222 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +85 −1
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.math.BigDecimal; |
| 19 | 19 | import java.math.BigInteger; |
| 20 | +import java.nio.ByteBuffer; | |
| 20 | 21 | import java.util.Collection; |
| 21 | 22 | import java.util.List; |
| 22 | 23 | import java.util.Map; |
| @@ -25,7 +26,11 @@ | ||
| 25 | 26 | |
| 26 | 27 | import static com.google.common.base.Preconditions.checkNotNull; |
| 27 | 28 | |
| 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; | |
| 29 | 34 | |
| 30 | 35 | // Static utilities private to the query builder |
| 31 | 36 | abstract class Utils { |
| @@ -263,6 +268,85 @@ | ||
| 263 | 268 | return sb; |
| 264 | 269 | } |
| 265 | 270 | |
| 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 | + | |
| 266 | 350 | static abstract class Appendeable { |
| 267 | 351 | abstract void appendTo(StringBuilder sb, List<Object> values, CodecRegistry codecRegistry); |
| 268 | 352 | abstract boolean containsBindMarker(); |
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +5 −8
| @@ -230,24 +230,21 @@ | ||
| 230 | 230 | @SuppressWarnings("serial") |
| 231 | 231 | @Test(groups = "unit") |
| 232 | 232 | 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}}}"; | |
| 235 | 234 | |
| 236 | 235 | final UserType udt1 = new UserType("ks", "t", Arrays.asList(new UserType.Field("a", DataType.blob())), protocolVersion, codecRegistry); |
| 237 | 236 | UserType udt2 = new UserType("ks", "t", Arrays.asList( |
| 238 | 237 | new UserType.Field("t", DataType.text()), |
| 239 | 238 | new UserType.Field("i", DataType.cint()), |
| 240 | - new UserType.Field("l", DataType.list(DataType.text())), | |
| 239 | + new UserType.Field("L", DataType.list(DataType.text())), | |
| 241 | 240 | new UserType.Field("s", DataType.map(DataType.cint(), udt1)) |
| 242 | 241 | ), protocolVersion, codecRegistry); |
| 243 | 242 | |
| 244 | 243 | UDTValue toFormat = udt2.newValue(); |
| 245 | 244 | toFormat.setString("t", "fo'o"); |
| 246 | 245 | 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}))); }}); | |
| 251 | 248 | |
| 252 | 249 | assertEquals(codecRegistry.codecFor(udt2).parse(toParse), toFormat); |
| 253 | 250 | assertEquals(codecRegistry.codecFor(udt2).format(toFormat), toParse); |
| @@ -257,7 +254,7 @@ | ||
| 257 | 254 | @Test(groups = "unit") |
| 258 | 255 | public void parseFormatTupleTest() { |
| 259 | 256 | |
| 260 | - String toParse = "(1, 'foo', 1.0)"; | |
| 257 | + String toParse = "(1,'foo',1.0)"; | |
| 261 | 258 | TupleType t = new TupleType(newArrayList(DataType.cint(), DataType.text(), DataType.cfloat()), protocolVersion, codecRegistry); |
| 262 | 259 | TupleValue toFormat = t.newValue(1, "foo", 1.0f); |
| 263 | 260 |
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 @@ | ||
| 37 | 37 | import static com.google.common.collect.Lists.newArrayList; |
| 38 | 38 | import static org.assertj.core.api.Assertions.assertThat; |
| 39 | 39 | |
| 40 | -import static com.datastax.driver.core.CodecUtils.listOf; | |
| 40 | +import static com.datastax.driver.core.TypeTokens.listOf; | |
| 41 | 41 | import static com.datastax.driver.core.TestUtils.getValue; |
| 42 | 42 | import static com.datastax.driver.core.TestUtils.setValue; |
| 43 | 43 | |
| @@ -173,7 +173,7 @@ | ||
| 173 | 173 | byName.setMap("m", map, mapping.javaType, mapping.javaType); |
| 174 | 174 | if(is21) { |
| 175 | 175 | byName.setTupleValue("t", tupleValue); |
| 176 | - byName.setSet("s", set, listOf(mapping.javaType)); | |
| 176 | + byName.setSet("s", set, TypeTokens.listOf(mapping.javaType)); | |
| 177 | 177 | } |
| 178 | 178 | session.execute(byName); |
| 179 | 179 | |
| @@ -187,7 +187,7 @@ | ||
| 187 | 187 | byIndex.setMap(3, map, mapping.javaType, mapping.javaType); |
| 188 | 188 | if(is21) { |
| 189 | 189 | byIndex.setTupleValue(4, tupleValue); |
| 190 | - byIndex.setSet(5, set, listOf(mapping.javaType)); | |
| 190 | + byIndex.setSet(5, set, TypeTokens.listOf(mapping.javaType)); | |
| 191 | 191 | } |
| 192 | 192 | session.execute(byIndex); |
| 193 | 193 | |
| @@ -214,7 +214,7 @@ | ||
| 214 | 214 | assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)).isEqualTo(mapping.value); |
| 215 | 215 | assertThat(getValue(returnedTuple, 1, mapping.outerType, registry)).isEqualTo(mapping.value); |
| 216 | 216 | |
| 217 | - assertThat(row.getSet("s", listOf(mapping.javaType))).isEqualTo(set); | |
| 217 | + assertThat(row.getSet("s", TypeTokens.listOf(mapping.javaType))).isEqualTo(set); | |
| 218 | 218 | } |
| 219 | 219 | |
| 220 | 220 | // Retrieve by index. |
| @@ -227,7 +227,7 @@ | ||
| 227 | 227 | assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)).isEqualTo(mapping.value); |
| 228 | 228 | assertThat(getValue(returnedTuple, 1, mapping.outerType, registry)).isEqualTo(mapping.value); |
| 229 | 229 | |
| 230 | - assertThat(row.getSet(4, listOf(mapping.javaType))).isEqualTo(set); | |
| 230 | + assertThat(row.getSet(4, TypeTokens.listOf(mapping.javaType))).isEqualTo(set); | |
| 231 | 231 | } |
| 232 | 232 | } |
| 233 | 233 | } |
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<timestamp,varchar></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<timestamp,varchar></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 | -} |
modified driver-core/src/test/java/com/datastax/driver/core/MappingCodec.java +14 −16
| @@ -19,51 +19,49 @@ | ||
| 19 | 19 | |
| 20 | 20 | import com.google.common.reflect.TypeToken; |
| 21 | 21 | |
| 22 | +import com.datastax.driver.core.ProtocolVersion; | |
| 23 | +import com.datastax.driver.core.TypeCodec; | |
| 22 | 24 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 23 | 25 | |
| 24 | 26 | /** |
| 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. | |
| 31 | 29 | */ |
| 32 | -public abstract class MappingCodec<T, U> extends TypeCodec<T> { | |
| 30 | +public abstract class MappingCodec<O, I> extends TypeCodec<O> { | |
| 33 | 31 | |
| 34 | - protected final TypeCodec<U> innerCodec; | |
| 32 | + protected final TypeCodec<I> innerCodec; | |
| 35 | 33 | |
| 36 | - public MappingCodec(TypeCodec<U> innerCodec, Class<T> javaType) { | |
| 34 | + public MappingCodec(TypeCodec<I> innerCodec, Class<O> javaType) { | |
| 37 | 35 | this(innerCodec, TypeToken.of(javaType)); |
| 38 | 36 | } |
| 39 | 37 | |
| 40 | - public MappingCodec(TypeCodec<U> innerCodec, TypeToken<T> javaType) { | |
| 38 | + public MappingCodec(TypeCodec<I> innerCodec, TypeToken<O> javaType) { | |
| 41 | 39 | super(innerCodec.getCqlType(), javaType); |
| 42 | 40 | this.innerCodec = innerCodec; |
| 43 | 41 | } |
| 44 | 42 | |
| 45 | 43 | @Override |
| 46 | - public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 44 | + public ByteBuffer serialize(O value, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 47 | 45 | return innerCodec.serialize(serialize(value), protocolVersion); |
| 48 | 46 | } |
| 49 | 47 | |
| 50 | 48 | @Override |
| 51 | - public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 49 | + public O deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 52 | 50 | return deserialize(innerCodec.deserialize(bytes, protocolVersion)); |
| 53 | 51 | } |
| 54 | 52 | |
| 55 | 53 | @Override |
| 56 | - public T parse(String value) throws InvalidTypeException { | |
| 54 | + public O parse(String value) throws InvalidTypeException { | |
| 57 | 55 | return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ? null : deserialize(innerCodec.parse(value)); |
| 58 | 56 | } |
| 59 | 57 | |
| 60 | 58 | @Override |
| 61 | - public String format(T value) throws InvalidTypeException { | |
| 59 | + public String format(O value) throws InvalidTypeException { | |
| 62 | 60 | return value == null ? null : innerCodec.format(serialize(value)); |
| 63 | 61 | } |
| 64 | 62 | |
| 65 | - protected abstract T deserialize(U value); | |
| 63 | + protected abstract O deserialize(I value); | |
| 66 | 64 | |
| 67 | - protected abstract U serialize(T value); | |
| 65 | + protected abstract I serialize(O value); | |
| 68 | 66 | |
| 69 | 67 | } |
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 @@ | ||
| 55 | 55 | assertEquals(v.getString(1), "a"); |
| 56 | 56 | assertEquals(v.getFloat(2), 1.0f); |
| 57 | 57 | |
| 58 | - assertEquals(TypeCodec.tuple(t).format(v), "(1, 'a', 1.0)"); | |
| 58 | + assertEquals(TypeCodec.tuple(t).format(v), "(1,'a',1.0)"); | |
| 59 | 59 | } |
| 60 | 60 | |
| 61 | 61 | @Test(groups = "short") |
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecAssert.java +5 −1
| @@ -75,7 +75,11 @@ | ||
| 75 | 75 | @SuppressWarnings("unchecked") |
| 76 | 76 | public TypeCodecAssert canSerialize(Object value) { |
| 77 | 77 | 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 | + } | |
| 79 | 83 | return this; |
| 80 | 84 | } |
| 81 | 85 |
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java +21 −21
| @@ -35,9 +35,9 @@ | ||
| 35 | 35 | |
| 36 | 36 | import com.datastax.driver.core.querybuilder.BuiltStatement; |
| 37 | 37 | |
| 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; | |
| 41 | 41 | import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker; |
| 42 | 42 | import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; |
| 43 | 43 | |
| @@ -128,12 +128,12 @@ | ||
| 128 | 128 | public void should_use_collection_codecs_with_prepared_statements_3() { |
| 129 | 129 | session.execute(session.prepare(insertQuery).bind() |
| 130 | 130 | .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)) | |
| 137 | 137 | ); |
| 138 | 138 | PreparedStatement ps = session.prepare(selectQuery); |
| 139 | 139 | ResultSet rows = session.execute(ps.bind() |
| @@ -147,12 +147,12 @@ | ||
| 147 | 147 | public void should_use_collection_codecs_with_built_statements() { |
| 148 | 148 | session.execute(session.prepare(insertStmt).bind() |
| 149 | 149 | .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)) | |
| 156 | 156 | ); |
| 157 | 157 | PreparedStatement ps = session.prepare(selectStmt); |
| 158 | 158 | ResultSet rows = session.execute(ps.bind() |
| @@ -170,12 +170,12 @@ | ||
| 170 | 170 | assertThat(row.getMap(5, Integer.class, BigInteger.class)).isEqualTo(m_varint); |
| 171 | 171 | assertThat(row.getMap(6, Integer.class, BigDecimal.class)).isEqualTo(m_decimal); |
| 172 | 172 | // 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); | |
| 179 | 179 | // with getObject |
| 180 | 180 | assertThat(row.getObject(1)).isEqualTo(l_int); |
| 181 | 181 | 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<timestamp,text></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/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 +4 −15
| @@ -36,7 +36,7 @@ | ||
| 36 | 36 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 37 | 37 | |
| 38 | 38 | import static com.datastax.driver.core.Assertions.assertThat; |
| 39 | -import static com.datastax.driver.core.CodecUtils.listOf; | |
| 39 | +import static com.datastax.driver.core.TypeTokens.listOf; | |
| 40 | 40 | import static com.datastax.driver.core.DataType.*; |
| 41 | 41 | import static com.datastax.driver.core.ProtocolVersion.V3; |
| 42 | 42 | |
| @@ -171,13 +171,6 @@ | ||
| 171 | 171 | .accepts(u4); |
| 172 | 172 | } |
| 173 | 173 | |
| 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 | - | |
| 181 | 174 | @Test(groups = "unit") |
| 182 | 175 | public void test_inheritance() { |
| 183 | 176 | CodecRegistry codecRegistry = new CodecRegistry(); |
| @@ -227,7 +220,7 @@ | ||
| 227 | 220 | |
| 228 | 221 | @Test(groups = "unit") |
| 229 | 222 | public void should_deserialize_empty_buffer_as_tuple_with_null_values() { |
| 230 | - CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE; | |
| 223 | + CodecRegistry codecRegistry = new CodecRegistry(); | |
| 231 | 224 | TupleType tupleType = new TupleType(newArrayList(DataType.cint(), DataType.varchar(), DataType.cfloat()), ProtocolVersion.NEWEST_SUPPORTED, codecRegistry); |
| 232 | 225 | TupleValue expected = tupleType.newValue(null, null, null); |
| 233 | 226 | |
| @@ -238,7 +231,7 @@ | ||
| 238 | 231 | |
| 239 | 232 | @Test(groups = "unit") |
| 240 | 233 | public void should_deserialize_empty_buffer_as_udt_with_null_values() { |
| 241 | - CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE; | |
| 234 | + CodecRegistry codecRegistry = new CodecRegistry(); | |
| 242 | 235 | UserType udt = new UserType("ks", "t", Arrays.asList( |
| 243 | 236 | new UserType.Field("t", DataType.text()), |
| 244 | 237 | new UserType.Field("i", DataType.cint()), |
| @@ -278,7 +271,7 @@ | ||
| 278 | 271 | private final TypeCodec<List<String>> codec = TypeCodec.list(TypeCodec.varchar()); |
| 279 | 272 | |
| 280 | 273 | protected ListVarcharToListListInteger() { |
| 281 | - super(DataType.list(DataType.varchar()), listOf(listOf(Integer.class))); | |
| 274 | + super(DataType.list(DataType.varchar()), TypeTokens.listOf(TypeTokens.listOf(Integer.class))); | |
| 282 | 275 | } |
| 283 | 276 | |
| 284 | 277 | @Override |
| @@ -363,10 +356,6 @@ | ||
| 363 | 356 | } |
| 364 | 357 | } |
| 365 | 358 | |
| 366 | - enum FooBarQix { | |
| 367 | - FOO, BAR, QIX | |
| 368 | - } | |
| 369 | - | |
| 370 | 359 | class A { |
| 371 | 360 | |
| 372 | 361 | int i = 0; |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java +1 −1
| @@ -55,7 +55,7 @@ | ||
| 55 | 55 | public void should_handle_collections_of_tuples() { |
| 56 | 56 | String query; |
| 57 | 57 | BuiltStatement statement; |
| 58 | - query = "UPDATE foo SET l=[(1, 2)] WHERE k=1;"; | |
| 58 | + query = "UPDATE foo SET l=[(1,2)] WHERE k=1;"; | |
| 59 | 59 | TupleType tupleType = cluster.getMetadata().newTupleType(cint(), cint()); |
| 60 | 60 | List<TupleValue> list = ImmutableList.of(tupleType.newValue(1, 2)); |
| 61 | 61 | 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 @@ | ||
| 207 | 207 | <skip>true</skip> |
| 208 | 208 | </configuration> |
| 209 | 209 | </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> | |
| 218 | 210 | </plugins> |
| 219 | 211 | </build> |
| 220 | 212 | </profile> |
added driver-extras/pom.xml +254 −0
| @@ -0,0 +1,254 @@ | ||
| 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>com.datastax.cassandra</groupId> | |
| 70 | + <artifactId>cassandra-driver-core</artifactId> | |
| 71 | + <version>${project.parent.version}</version> | |
| 72 | + <type>test-jar</type> | |
| 73 | + <scope>test</scope> | |
| 74 | + </dependency> | |
| 75 | + | |
| 76 | + <dependency> | |
| 77 | + <groupId>com.datastax.cassandra</groupId> | |
| 78 | + <artifactId>cassandra-driver-mapping</artifactId> | |
| 79 | + <version>${project.parent.version}</version> | |
| 80 | + <scope>test</scope> | |
| 81 | + </dependency> | |
| 82 | + | |
| 83 | + <dependency> | |
| 84 | + <groupId>org.testng</groupId> | |
| 85 | + <artifactId>testng</artifactId> | |
| 86 | + <version>${testng.version}</version> | |
| 87 | + <scope>test</scope> | |
| 88 | + </dependency> | |
| 89 | + | |
| 90 | + <dependency> | |
| 91 | + <groupId>org.assertj</groupId> | |
| 92 | + <artifactId>assertj-core</artifactId> | |
| 93 | + <version>${assertj.version}</version> | |
| 94 | + <scope>test</scope> | |
| 95 | + </dependency> | |
| 96 | + | |
| 97 | + <dependency> | |
| 98 | + <groupId>org.mockito</groupId> | |
| 99 | + <artifactId>mockito-all</artifactId> | |
| 100 | + <version>${mockito.version}</version> | |
| 101 | + <scope>test</scope> | |
| 102 | + </dependency> | |
| 103 | + | |
| 104 | + <dependency> | |
| 105 | + <groupId>org.apache.commons</groupId> | |
| 106 | + <artifactId>commons-exec</artifactId> | |
| 107 | + <version>${commons-exec.version}</version> | |
| 108 | + <scope>test</scope> | |
| 109 | + </dependency> | |
| 110 | + | |
| 111 | + </dependencies> | |
| 112 | + | |
| 113 | + <build> | |
| 114 | + | |
| 115 | + <plugins> | |
| 116 | + | |
| 117 | + <plugin> | |
| 118 | + <groupId>org.apache.maven.plugins</groupId> | |
| 119 | + <artifactId>maven-compiler-plugin</artifactId> | |
| 120 | + <configuration> | |
| 121 | + <excludes> | |
| 122 | + <exclude>${jdk8.excludes}</exclude> | |
| 123 | + </excludes> | |
| 124 | + <testExcludes> | |
| 125 | + <exclude>${jdk8.excludes}</exclude> | |
| 126 | + </testExcludes> | |
| 127 | + </configuration> | |
| 128 | + </plugin> | |
| 129 | + | |
| 130 | + <plugin> | |
| 131 | + <groupId>org.codehaus.mojo</groupId> | |
| 132 | + <artifactId>animal-sniffer-maven-plugin</artifactId> | |
| 133 | + <configuration> | |
| 134 | + <!-- | |
| 135 | + There is no support for JDK 8 yet, see | |
| 136 | + https://github.com/mojohaus/animal-sniffer/issues/1 | |
| 137 | + --> | |
| 138 | + <skip>true</skip> | |
| 139 | + <signature> | |
| 140 | + <groupId>org.codehaus.mojo.signature</groupId> | |
| 141 | + <artifactId>java18</artifactId> | |
| 142 | + <version>1.0</version> | |
| 143 | + </signature> | |
| 144 | + </configuration> | |
| 145 | + </plugin> | |
| 146 | + | |
| 147 | + <plugin> | |
| 148 | + <groupId>org.apache.maven.plugins</groupId> | |
| 149 | + <artifactId>maven-surefire-plugin</artifactId> | |
| 150 | + <version>2.16</version> | |
| 151 | + <configuration> | |
| 152 | + <groups>${test.groups}</groups> | |
| 153 | + <useFile>false</useFile> | |
| 154 | + <systemPropertyVariables> | |
| 155 | + <cassandra.version>${cassandra.version}</cassandra.version> | |
| 156 | + <ipprefix>${ipprefix}</ipprefix> | |
| 157 | + </systemPropertyVariables> | |
| 158 | + <classpathDependencyExcludes> | |
| 159 | + <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes> | |
| 160 | + </classpathDependencyExcludes> | |
| 161 | + <excludes> | |
| 162 | + <exclude>${jdk8.excludes}</exclude> | |
| 163 | + </excludes> | |
| 164 | + </configuration> | |
| 165 | + </plugin> | |
| 166 | + | |
| 167 | + <plugin> | |
| 168 | + <groupId>org.apache.felix</groupId> | |
| 169 | + <artifactId>maven-bundle-plugin</artifactId> | |
| 170 | + <extensions>true</extensions> | |
| 171 | + <version>2.4.0</version> | |
| 172 | + <executions> | |
| 173 | + <execution> | |
| 174 | + <id>bundle-manifest</id> | |
| 175 | + <phase>process-classes</phase> | |
| 176 | + <goals> | |
| 177 | + <goal>manifest</goal> | |
| 178 | + </goals> | |
| 179 | + </execution> | |
| 180 | + </executions> | |
| 181 | + <configuration> | |
| 182 | + <instructions> | |
| 183 | + <Bundle-SymbolicName>com.datastax.driver.extras</Bundle-SymbolicName> | |
| 184 | + <Bundle-Version>${project.version}</Bundle-Version> | |
| 185 | + <_include>-osgi.bnd</_include> | |
| 186 | + </instructions> | |
| 187 | + <supportedProjectTypes> | |
| 188 | + <supportedProjectType>jar</supportedProjectType> | |
| 189 | + <supportedProjectType>bundle</supportedProjectType> | |
| 190 | + <supportedProjectType>pom</supportedProjectType> | |
| 191 | + </supportedProjectTypes> | |
| 192 | + </configuration> | |
| 193 | + </plugin> | |
| 194 | + | |
| 195 | + </plugins> | |
| 196 | + | |
| 197 | + </build> | |
| 198 | + | |
| 199 | + <profiles> | |
| 200 | + | |
| 201 | + <profile> | |
| 202 | + <id>short</id> | |
| 203 | + <properties> | |
| 204 | + <test.groups>unit,short</test.groups> | |
| 205 | + </properties> | |
| 206 | + </profile> | |
| 207 | + | |
| 208 | + <profile> | |
| 209 | + <id>long</id> | |
| 210 | + <properties> | |
| 211 | + <test.groups>unit,short,long</test.groups> | |
| 212 | + </properties> | |
| 213 | + </profile> | |
| 214 | + | |
| 215 | + <!-- | |
| 216 | + This profile excludes all JDK 8 dependent classes from | |
| 217 | + compilation. Use this when running tests with a legacy JDK (6 or 7) | |
| 218 | + --> | |
| 219 | + <profile> | |
| 220 | + <id>legacy-jdks</id> | |
| 221 | + <activation> | |
| 222 | + <jdk>[,1.8)</jdk> | |
| 223 | + </activation> | |
| 224 | + <properties> | |
| 225 | + <jdk8.excludes>**/jdk8/*.java</jdk8.excludes> | |
| 226 | + </properties> | |
| 227 | + </profile> | |
| 228 | + | |
| 229 | + </profiles> | |
| 230 | + | |
| 231 | + <licenses> | |
| 232 | + <license> | |
| 233 | + <name>Apache 2</name> | |
| 234 | + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> | |
| 235 | + <distribution>repo</distribution> | |
| 236 | + <comments>Apache License Version 2.0</comments> | |
| 237 | + </license> | |
| 238 | + </licenses> | |
| 239 | + | |
| 240 | + <scm> | |
| 241 | + <connection>scm:git:git@github.com:datastax/java-driver.git</connection> | |
| 242 | + <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection> | |
| 243 | + <url>https://github.com/datastax/java-driver</url> | |
| 244 | + <tag>HEAD</tag> | |
| 245 | + </scm> | |
| 246 | + | |
| 247 | + <developers> | |
| 248 | + <developer> | |
| 249 | + <name>Various</name> | |
| 250 | + <organization>DataStax</organization> | |
| 251 | + </developer> | |
| 252 | + </developers> | |
| 253 | + | |
| 254 | +</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/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/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<timestamp,varchar></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<timestamp,varchar></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/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 +298 −0
| @@ -0,0 +1,298 @@ | ||
| 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.EnumType; | |
| 35 | +import com.datastax.driver.mapping.Mapper; | |
| 36 | +import com.datastax.driver.mapping.MappingManager; | |
| 37 | +import com.datastax.driver.mapping.annotations.Enumerated; | |
| 38 | +import com.datastax.driver.mapping.annotations.PartitionKey; | |
| 39 | +import com.datastax.driver.mapping.annotations.Table; | |
| 40 | + | |
| 41 | +import static com.datastax.driver.core.DataType.cint; | |
| 42 | +import static com.datastax.driver.core.DataType.text; | |
| 43 | +import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Bar.BAR_1; | |
| 44 | +import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Bar.BAR_2; | |
| 45 | +import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Foo.FOO_1; | |
| 46 | +import static com.datastax.driver.extras.codecs.enums.EnumCodecsTest.Foo.FOO_2; | |
| 47 | + | |
| 48 | +/** | |
| 49 | + * A test that validates that Enums are correctly mapped to varchars (with EnumNameCodec) | |
| 50 | + * and ints (with EnumOrdinalCodec). | |
| 51 | + * It also validates that both codecs may coexist in the same CodecRegistry. | |
| 52 | + */ | |
| 53 | +@CassandraVersion(major=2.1) | |
| 54 | +public class EnumCodecsTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 55 | + | |
| 56 | + private final String insertQuery = "INSERT INTO t1 (pk, foo, foos, bar, bars, foobars, tup, udt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; | |
| 57 | + private final String selectQuery = "SELECT pk, foo, foos, bar, bars, foobars, tup, udt FROM t1 WHERE pk = ?"; | |
| 58 | + | |
| 59 | + private final int pk = 42; | |
| 60 | + | |
| 61 | + private final List<Foo> foos = newArrayList(FOO_1, FOO_2); | |
| 62 | + private final Set<Bar> bars = newHashSet(BAR_1, BAR_2); | |
| 63 | + private final Map<Foo, Bar> foobars = ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2); | |
| 64 | + | |
| 65 | + private TupleValue tupleValue; | |
| 66 | + private UDTValue udtValue; | |
| 67 | + | |
| 68 | + @Override | |
| 69 | + protected Collection<String> getTableDefinitions() { | |
| 70 | + return newArrayList( | |
| 71 | + "CREATE TYPE IF NOT EXISTS udt1 (" | |
| 72 | + + "foo int," | |
| 73 | + + "bar text)", | |
| 74 | + "CREATE TABLE IF NOT EXISTS t1 (" | |
| 75 | + + "pk int PRIMARY KEY, " | |
| 76 | + + "foo int, " | |
| 77 | + + "foos list<int>, " | |
| 78 | + + "bar text, " | |
| 79 | + + "bars set<text>, " | |
| 80 | + + "foobars map<int,text>, " | |
| 81 | + + "tup frozen<tuple<int,varchar>>, " | |
| 82 | + + "udt frozen<udt1>" | |
| 83 | + + ")" | |
| 84 | + ); | |
| 85 | + } | |
| 86 | + | |
| 87 | + @Override | |
| 88 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 89 | + return builder.withCodecRegistry( | |
| 90 | + new CodecRegistry() | |
| 91 | + .register(new EnumOrdinalCodec<Foo>(Foo.class)) | |
| 92 | + .register(new EnumNameCodec<Bar>(Bar.class)) | |
| 93 | + ); | |
| 94 | + } | |
| 95 | + | |
| 96 | + @BeforeMethod(groups="short") | |
| 97 | + public void before() { | |
| 98 | + TupleType tup = cluster.getMetadata().newTupleType(cint(), text()); | |
| 99 | + tupleValue = tup.newValue() | |
| 100 | + .set(0, FOO_1, Foo.class) | |
| 101 | + .set(1, BAR_1, Bar.class); | |
| 102 | + UserType udt = cluster.getMetadata().getKeyspace(keyspace).getUserType("udt1"); | |
| 103 | + udtValue = udt.newValue() | |
| 104 | + .set("foo", FOO_1, Foo.class) | |
| 105 | + .set("bar", BAR_1, Bar.class); | |
| 106 | + } | |
| 107 | + | |
| 108 | + @Test(groups = "short") | |
| 109 | + public void should_use_enum_codecs_with_simple_statements() { | |
| 110 | + session.execute(insertQuery, pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue); | |
| 111 | + ResultSet rows = session.execute(selectQuery, pk); | |
| 112 | + Row row = rows.one(); | |
| 113 | + assertRow(row); | |
| 114 | + } | |
| 115 | + | |
| 116 | + @Test(groups = "short") | |
| 117 | + public void should_use_enum_codecs_with_prepared_statements_1() { | |
| 118 | + session.execute(session.prepare(insertQuery).bind(pk, FOO_1, foos, BAR_1, bars, foobars, tupleValue, udtValue)); | |
| 119 | + PreparedStatement ps = session.prepare(selectQuery); | |
| 120 | + ResultSet rows = session.execute(ps.bind(pk)); | |
| 121 | + Row row = rows.one(); | |
| 122 | + assertRow(row); | |
| 123 | + } | |
| 124 | + | |
| 125 | + @Test(groups = "short") | |
| 126 | + public void should_use_enum_codecs_with_prepared_statements_2() { | |
| 127 | + session.execute(session.prepare(insertQuery).bind() | |
| 128 | + .setInt(0, pk) | |
| 129 | + .set(1, FOO_1, Foo.class) | |
| 130 | + .setList(2, foos, Foo.class) | |
| 131 | + .set(3, BAR_1, Bar.class) | |
| 132 | + .set(4, bars, new TypeToken<Set<Bar>>(){}) | |
| 133 | + .setMap(5, foobars, Foo.class, Bar.class) | |
| 134 | + .setTupleValue(6, tupleValue) | |
| 135 | + .setUDTValue(7, udtValue) | |
| 136 | + ); | |
| 137 | + PreparedStatement ps = session.prepare(selectQuery); | |
| 138 | + ResultSet rows = session.execute(ps.bind() | |
| 139 | + .setInt(0, pk) | |
| 140 | + ); | |
| 141 | + Row row = rows.one(); | |
| 142 | + assertRow(row); | |
| 143 | + } | |
| 144 | + | |
| 145 | + @Test(groups = "short") | |
| 146 | + public void should_use_mapper_to_store_and_retrieve_values_with_enum_codecs() { | |
| 147 | + // given | |
| 148 | + MappingManager manager = new MappingManager(session); | |
| 149 | + Mapper<Mapped> mapper = manager.mapper(Mapped.class); | |
| 150 | + // when | |
| 151 | + Mapped pojo = new Mapped(); | |
| 152 | + mapper.save(pojo); | |
| 153 | + Mapped actual = mapper.get(42); | |
| 154 | + // then | |
| 155 | + assertThat(actual).isEqualToComparingFieldByField(pojo); | |
| 156 | + } | |
| 157 | + | |
| 158 | + private void assertRow(Row row) { | |
| 159 | + | |
| 160 | + assertThat(row.getInt(0)).isEqualTo(pk); | |
| 161 | + | |
| 162 | + assertThat(row.getObject(1)).isEqualTo(FOO_1.ordinal()); // uses the built-in IntCodec because CQL type is int | |
| 163 | + assertThat(row.getInt("foo")).isEqualTo(FOO_1.ordinal()); // uses the built-in IntCodec | |
| 164 | + assertThat(row.get(1, Integer.class)).isEqualTo(FOO_1.ordinal()); // forces IntCodec | |
| 165 | + assertThat(row.get("foo", Foo.class)).isEqualTo(FOO_1); // forces EnumOrdinalCodec | |
| 166 | + | |
| 167 | + assertThat(row.getObject(2)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal())); // uses the built-in ListCodec(IntCodec) because CQL type is list<int> | |
| 168 | + assertThat(row.getList(2, Integer.class)).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal())); | |
| 169 | + assertThat(row.getList("foos", Foo.class)).isEqualTo(newArrayList(FOO_1, FOO_2)); | |
| 170 | + assertThat(row.get(2, new TypeToken<List<Integer>>(){})).isEqualTo(newArrayList(FOO_1.ordinal(), FOO_2.ordinal())); | |
| 171 | + assertThat(row.get("foos", new TypeToken<List<Foo>>(){})).isEqualTo(newArrayList(FOO_1, FOO_2)); | |
| 172 | + | |
| 173 | + assertThat(row.getObject(3)).isEqualTo(BAR_1.name()); // uses the built-in VarcharCodec because CQL type is varchar | |
| 174 | + assertThat(row.getString("bar")).isEqualTo(BAR_1.name()); // forces VarcharCodec | |
| 175 | + assertThat(row.get(3, String.class)).isEqualTo(BAR_1.name()); // forces VarcharCodec | |
| 176 | + assertThat(row.get("bar", Bar.class)).isEqualTo(BAR_1); // forces EnumNameCodec | |
| 177 | + | |
| 178 | + assertThat(row.getObject(4)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name())); // uses the built-in SetCodec(VarcharCodec) because CQL type is set<varchar> | |
| 179 | + assertThat(row.getSet(4, String.class)).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name())); | |
| 180 | + assertThat(row.getSet("bars", Bar.class)).isEqualTo(newHashSet(BAR_1, BAR_2)); | |
| 181 | + assertThat(row.get(4, new TypeToken<Set<String>>(){})).isEqualTo(newHashSet(BAR_1.name(), BAR_2.name())); | |
| 182 | + assertThat(row.get("bars", new TypeToken<Set<Bar>>(){})).isEqualTo(newHashSet(BAR_1, BAR_2)); | |
| 183 | + | |
| 184 | + // uses default built-in codec MapCodec(IntCodec, VarcharCodec) because CQL type is map<int, varchar> | |
| 185 | + assertThat(row.getObject(5)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name())); | |
| 186 | + | |
| 187 | + // getMap with combinations of built-in or EnumX codecs | |
| 188 | + assertThat(row.getMap(5, Integer.class, String.class)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name())); | |
| 189 | + assertThat(row.getMap(5, Foo.class, String.class)).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name())); | |
| 190 | + assertThat(row.getMap(5, Integer.class, Bar.class)).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2)); | |
| 191 | + assertThat(row.getMap(5, Foo.class, Bar.class)).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2)); | |
| 192 | + | |
| 193 | + // get + TypeToken with combinations of built-in or EnumX codecs | |
| 194 | + assertThat(row.get("foobars", new TypeToken<Map<Integer, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1.name(), FOO_2.ordinal(), BAR_2.name())); | |
| 195 | + assertThat(row.get("foobars", new TypeToken<Map<Foo, String>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1.name(), FOO_2, BAR_2.name())); | |
| 196 | + assertThat(row.get("foobars", new TypeToken<Map<Integer, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1.ordinal(), BAR_1, FOO_2.ordinal(), BAR_2)); | |
| 197 | + assertThat(row.get("foobars", new TypeToken<Map<Foo, Bar>>(){})).isEqualTo(ImmutableMap.of(FOO_1, BAR_1, FOO_2, BAR_2)); | |
| 198 | + | |
| 199 | + assertThat(row.getTupleValue(6).getInt(0)).isEqualTo(FOO_1.ordinal()); | |
| 200 | + assertThat(row.get(6, TupleValue.class).get(0, Foo.class)).isEqualTo(FOO_1); | |
| 201 | + assertThat(row.getTupleValue("tup").getString(1)).isEqualTo(BAR_1.name()); | |
| 202 | + assertThat(row.get("tup", TupleValue.class).get(1, Bar.class)).isEqualTo(BAR_1); | |
| 203 | + | |
| 204 | + assertThat(row.getUDTValue(7).getInt("foo")).isEqualTo(FOO_1.ordinal()); | |
| 205 | + assertThat(row.get(7, UDTValue.class).get("foo", Foo.class)).isEqualTo(FOO_1); | |
| 206 | + assertThat(row.getUDTValue("udt").getString("bar")).isEqualTo(BAR_1.name()); | |
| 207 | + assertThat(row.get("udt", UDTValue.class).get("bar", Bar.class)).isEqualTo(BAR_1); | |
| 208 | + | |
| 209 | + } | |
| 210 | + | |
| 211 | + @SuppressWarnings("unused") | |
| 212 | + @Table(name = "t1") | |
| 213 | + public static class Mapped { | |
| 214 | + | |
| 215 | + @PartitionKey | |
| 216 | + private int pk; | |
| 217 | + | |
| 218 | + // note that we need to specify @Enumerated here | |
| 219 | + // because the mapper already has a partial support for enums | |
| 220 | + // that kicks in for fields of type Enum | |
| 221 | + @Enumerated(EnumType.ORDINAL) | |
| 222 | + private Foo foo; | |
| 223 | + | |
| 224 | + private List<Foo> foos; | |
| 225 | + | |
| 226 | + private Bar bar; | |
| 227 | + | |
| 228 | + private Set<Bar> bars; | |
| 229 | + | |
| 230 | + private Map<Foo, Bar> foobars; | |
| 231 | + | |
| 232 | + public Mapped(){ | |
| 233 | + pk = 42; | |
| 234 | + foo = FOO_1; | |
| 235 | + bar = BAR_1; | |
| 236 | + foos = newArrayList(FOO_2, FOO_1); | |
| 237 | + bars = newHashSet(BAR_1, BAR_2); | |
| 238 | + foobars = ImmutableMap.of(FOO_1, BAR_2); | |
| 239 | + } | |
| 240 | + | |
| 241 | + public int getPk() { | |
| 242 | + return pk; | |
| 243 | + } | |
| 244 | + | |
| 245 | + public void setPk(int pk) { | |
| 246 | + this.pk = pk; | |
| 247 | + } | |
| 248 | + | |
| 249 | + public Foo getFoo() { | |
| 250 | + return foo; | |
| 251 | + } | |
| 252 | + | |
| 253 | + public void setFoo(Foo foo) { | |
| 254 | + this.foo = foo; | |
| 255 | + } | |
| 256 | + | |
| 257 | + public List<Foo> getFoos() { | |
| 258 | + return foos; | |
| 259 | + } | |
| 260 | + | |
| 261 | + public void setFoos(List<Foo> foos) { | |
| 262 | + this.foos = foos; | |
| 263 | + } | |
| 264 | + | |
| 265 | + public Bar getBar() { | |
| 266 | + return bar; | |
| 267 | + } | |
| 268 | + | |
| 269 | + public void setBar(Bar bar) { | |
| 270 | + this.bar = bar; | |
| 271 | + } | |
| 272 | + | |
| 273 | + public Set<Bar> getBars() { | |
| 274 | + return bars; | |
| 275 | + } | |
| 276 | + | |
| 277 | + public void setBars(Set<Bar> bars) { | |
| 278 | + this.bars = bars; | |
| 279 | + } | |
| 280 | + | |
| 281 | + public Map<Foo, Bar> getFoobars() { | |
| 282 | + return foobars; | |
| 283 | + } | |
| 284 | + | |
| 285 | + public void setFoobars(Map<Foo, Bar> foobars) { | |
| 286 | + this.foobars = foobars; | |
| 287 | + } | |
| 288 | + } | |
| 289 | + | |
| 290 | + enum Foo { | |
| 291 | + FOO_1, FOO_2 | |
| 292 | + } | |
| 293 | + | |
| 294 | + enum Bar { | |
| 295 | + BAR_1, BAR_2 | |
| 296 | + } | |
| 297 | + | |
| 298 | +} |
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/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<timestamp,text></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/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 @@ | ||
| 50 | 50 | <dependency> |
| 51 | 51 | <groupId>org.testng</groupId> |
| 52 | 52 | <artifactId>testng</artifactId> |
| 53 | - <version>6.8.1</version> | |
| 53 | + <version>${testng.version}</version> | |
| 54 | 54 | <scope>test</scope> |
| 55 | 55 | </dependency> |
| 56 | 56 | |
| 57 | 57 | <dependency> |
| 58 | 58 | <groupId>org.assertj</groupId> |
| 59 | 59 | <artifactId>assertj-core</artifactId> |
| 60 | - <version>1.7.0</version> | |
| 60 | + <version>${assertj.version}</version> | |
| 61 | 61 | <scope>test</scope> |
| 62 | 62 | </dependency> |
| 63 | 63 | |
| 64 | 64 | <dependency> |
| 65 | 65 | <groupId>org.mockito</groupId> |
| 66 | 66 | <artifactId>mockito-all</artifactId> |
| 67 | - <version>1.10.8</version> | |
| 67 | + <version>${mockito.version}</version> | |
| 68 | 68 | <scope>test</scope> |
| 69 | 69 | </dependency> |
| 70 | 70 | |
| 71 | 71 | <dependency> |
| 72 | 72 | <groupId>org.apache.commons</groupId> |
| 73 | 73 | <artifactId>commons-exec</artifactId> |
| 74 | - <version>1.3</version> | |
| 74 | + <version>${commons-exec.version}</version> | |
| 75 | 75 | <scope>test</scope> |
| 76 | 76 | </dependency> |
| 77 | 77 | |
| @@ -151,14 +151,6 @@ | ||
| 151 | 151 | </systemPropertyVariables> |
| 152 | 152 | </configuration> |
| 153 | 153 | </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> | |
| 162 | 154 | </plugins> |
| 163 | 155 | </build> |
| 164 | 156 | </profile> |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCustomCodecTest.java +44 −1
| @@ -19,10 +19,12 @@ | ||
| 19 | 19 | import java.util.Collection; |
| 20 | 20 | import java.util.Map; |
| 21 | 21 | |
| 22 | -import com.datastax.driver.core.utils.CassandraVersion; | |
| 23 | 22 | import com.google.common.base.Optional; |
| 23 | +import com.google.common.base.Predicate; | |
| 24 | 24 | import com.google.common.collect.ImmutableMap; |
| 25 | 25 | import com.google.common.collect.Lists; |
| 26 | +import com.google.common.reflect.TypeParameter; | |
| 27 | +import com.google.common.reflect.TypeToken; | |
| 26 | 28 | import org.testng.annotations.Test; |
| 27 | 29 | |
| 28 | 30 | import static org.assertj.core.api.Assertions.assertThat; |
| @@ -30,6 +32,7 @@ | ||
| 30 | 32 | |
| 31 | 33 | import com.datastax.driver.core.*; |
| 32 | 34 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 35 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 33 | 36 | import com.datastax.driver.mapping.annotations.*; |
| 34 | 37 | |
| 35 | 38 | @CassandraVersion(major=2.1) |
| @@ -556,6 +559,46 @@ | ||
| 556 | 559 | } |
| 557 | 560 | } |
| 558 | 561 | |
| 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 | + | |
| 559 | 602 | private static class NoDefaultConstructorCodec extends TypeCodec<String> { |
| 560 | 603 | |
| 561 | 604 | public NoDefaultConstructorCodec(DataType cqlType, Class<String> javaClass) { |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperEnumTest.java +4 −4
| @@ -17,15 +17,15 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.Collection; |
| 19 | 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 | 20 | import com.google.common.collect.Lists; |
| 24 | 21 | import org.testng.annotations.Test; |
| 25 | 22 | |
| 26 | -import static org.junit.Assert.assertNull; | |
| 23 | +import static org.testng.Assert.assertNull; | |
| 27 | 24 | |
| 28 | 25 | import com.datastax.driver.core.CCMBridge; |
| 26 | +import com.datastax.driver.mapping.annotations.Enumerated; | |
| 27 | +import com.datastax.driver.mapping.annotations.PartitionKey; | |
| 28 | +import com.datastax.driver.mapping.annotations.Table; | |
| 29 | 29 | |
| 30 | 30 | /** |
| 31 | 31 | * Covers handling of enum fields by the mapper. |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +4 −4
| @@ -39,7 +39,7 @@ | ||
| 39 | 39 | public class MapperUDTTest extends CCMBridge.PerClassSingleNodeCluster { |
| 40 | 40 | |
| 41 | 41 | 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>)", | |
| 43 | 43 | "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)"); |
| 44 | 44 | } |
| 45 | 45 | |
| @@ -135,7 +135,7 @@ | ||
| 135 | 135 | @Field // not strictly required, but we want to check that the annotation works without a name |
| 136 | 136 | private String city; |
| 137 | 137 | |
| 138 | - @Field(name = "zip_code") | |
| 138 | + @Field(name = "ZIP_code", caseSensitive = true) | |
| 139 | 139 | private int zipCode; |
| 140 | 140 | |
| 141 | 141 | private Set<String> phones; |
| @@ -286,9 +286,9 @@ | ||
| 286 | 286 | UUID userId = UUIDs.random(); |
| 287 | 287 | |
| 288 | 288 | // Create a user. |
| 289 | - session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', zip_code: 89898, phones: {'8675309'}} " + | |
| 289 | + session.execute("update users SET other_addresses['condo']={street: '101 Ocean Ln', city: 'Jacksonville, FL', \"ZIP_code\": 89898, phones: {'8675309'}} " + | |
| 290 | 290 | " 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'}} " + | |
| 291 | + session.execute("update users SET mainaddress={street: '42 Middle of Nowhere', city: 'Lake of the Woods', \"ZIP_code\": 49553, phones: {'8675039'}} " + | |
| 292 | 292 | " WHERE user_Id=" + TypeCodec.uuid().format(userId)); |
| 293 | 293 | |
| 294 | 294 | // Get the user. |
modified pom.xml +80 −6
| @@ -36,6 +36,7 @@ | ||
| 36 | 36 | <modules> |
| 37 | 37 | <module>driver-core</module> |
| 38 | 38 | <module>driver-mapping</module> |
| 39 | + <module>driver-extras</module> | |
| 39 | 40 | <module>driver-examples</module> |
| 40 | 41 | <module>driver-dse</module> |
| 41 | 42 | <module>driver-dist</module> |
| @@ -57,8 +58,11 @@ | ||
| 57 | 58 | <testng.version>6.8.8</testng.version> |
| 58 | 59 | <assertj.version>1.7.0</assertj.version> |
| 59 | 60 | <mockito.version>1.10.8</mockito.version> |
| 61 | + <commons-exec.version>1.3</commons-exec.version> | |
| 60 | 62 | <scassandra.version>0.10.0</scassandra.version> |
| 61 | 63 | <main.basedir>${project.basedir}</main.basedir> |
| 64 | + <!-- Set default javadoc.opts, overriden by profiles --> | |
| 65 | + <javadoc.opts></javadoc.opts> | |
| 62 | 66 | </properties> |
| 63 | 67 | |
| 64 | 68 | <dependencies> |
| @@ -78,6 +82,7 @@ | ||
| 78 | 82 | </dependencies> |
| 79 | 83 | |
| 80 | 84 | <profiles> |
| 85 | + | |
| 81 | 86 | <profile> |
| 82 | 87 | <id>doclint-java8-disable</id> |
| 83 | 88 | <activation> |
| @@ -87,19 +92,55 @@ | ||
| 87 | 92 | <javadoc.opts>-Xdoclint:none</javadoc.opts> |
| 88 | 93 | </properties> |
| 89 | 94 | </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 | + | |
| 90 | 124 | </profiles> |
| 91 | 125 | |
| 92 | 126 | <build> |
| 93 | 127 | <plugins> |
| 94 | 128 | <plugin> |
| 95 | 129 | <artifactId>maven-compiler-plugin</artifactId> |
| 96 | - <version>3.1</version> | |
| 130 | + <version>3.3</version> | |
| 97 | 131 | <configuration> |
| 98 | 132 | <source>${java.version}</source> |
| 99 | 133 | <target>${java.version}</target> |
| 100 | 134 | <optimize>true</optimize> |
| 101 | 135 | <showDeprecation>true</showDeprecation> |
| 102 | 136 | <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> | |
| 103 | 144 | </configuration> |
| 104 | 145 | </plugin> |
| 105 | 146 | <plugin> |
| @@ -120,8 +161,9 @@ | ||
| 120 | 161 | <artifactId>maven-javadoc-plugin</artifactId> |
| 121 | 162 | <version>2.9.1</version> |
| 122 | 163 | <configuration> |
| 164 | + <verbose>false</verbose> | |
| 123 | 165 | <!-- I can haz math in my javadoc (see http://zverovich.net/2012/01/14/beautiful-math-in-javadoc.html) --> |
| 124 | - <additionalparam>-header '<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>'</additionalparam> | |
| 166 | + <additionalparam>${javadoc.opts} -header '<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>'</additionalparam> | |
| 125 | 167 | </configuration> |
| 126 | 168 | <executions> |
| 127 | 169 | <execution> |
| @@ -129,9 +171,6 @@ | ||
| 129 | 171 | <goals> |
| 130 | 172 | <goal>jar</goal> |
| 131 | 173 | </goals> |
| 132 | - <configuration> | |
| 133 | - <additionalparam>${javadoc.opts}</additionalparam> | |
| 134 | - </configuration> | |
| 135 | 174 | </execution> |
| 136 | 175 | </executions> |
| 137 | 176 | </plugin> |
| @@ -141,12 +180,13 @@ | ||
| 141 | 180 | <version>2.5</version> |
| 142 | 181 | <configuration> |
| 143 | 182 | <tagNameFormat>@{project.version}</tagNameFormat> |
| 183 | + <arguments>-Penforce-java8</arguments> | |
| 144 | 184 | </configuration> |
| 145 | 185 | </plugin> |
| 146 | 186 | <plugin> |
| 147 | 187 | <groupId>org.codehaus.mojo</groupId> |
| 148 | 188 | <artifactId>clirr-maven-plugin</artifactId> |
| 149 | - <version>2.6.1</version> | |
| 189 | + <version>2.7</version> | |
| 150 | 190 | <executions> |
| 151 | 191 | <execution> |
| 152 | 192 | <phase>compile</phase> |
| @@ -166,6 +206,19 @@ | ||
| 166 | 206 | <exclude>com/datastax/driver/core/Connection$*</exclude> |
| 167 | 207 | </excludes> |
| 168 | 208 | </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> | |
| 169 | 222 | </plugin> |
| 170 | 223 | <plugin> |
| 171 | 224 | <groupId>org.codehaus.mojo</groupId> |
| @@ -226,6 +279,27 @@ | ||
| 226 | 279 | </execution> |
| 227 | 280 | </executions> |
| 228 | 281 | </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> | |
| 229 | 303 | </plugins> |
| 230 | 304 | </build> |
| 231 | 305 |