Elffuss BraidHub

kikocis/java-driver public

Merge pull request #491 from datastax/java957

JAVA-957: Improve Custom Codecs documentation on Type Inheritance
Changeset0f2b58a1be54dcde5817e6f89254520cda57fb32314a01c677f705e4bd3ba93e
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-10-20 14:34 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-10-20 14:34 +02:00
Parents49e09e3df95c, c6378533a184

Browse the files at this changeset

3 files changed

modified driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +19 −13
@@ -72,12 +72,12 @@
7272 * <h3>Registering and using custom codecs</h3>
7373 *
7474 * To create a custom codec, write a class that extends {@link TypeCodec}, create an instance, and pass it to one of
75- * the {@link #register(TypeCodec) register} methods:
75+ * the {@link #register(TypeCodec) register} methods; for example, one could create a codec that maps CQL
76+ * timestamps to JDK8's {@code java.time.LocalDate}:
7677 *
7778 * <pre>
7879 * {@code
79- * // A codec that maps timestamps to JDK8's LocalDate
80- * class LocalDateCodec extends TypeCodec<LocalDate> {
80+ * class LocalDateCodec extends TypeCodec<java.time.LocalDate> {
8181 * ...
8282 * }
8383 * myCodecRegistry.register(new LocalDateCodec());
@@ -88,14 +88,14 @@
8888 * <li>all driver types that implement {@link GettableByIndexData}, {@link GettableByNameData},
8989 * {@link SettableByIndexData} and/or {@link SettableByNameData}. Namely: {@link Row},
9090 * {@link BoundStatement}, {@link UDTValue} and {@link TupleValue};</li>
91- * <li>{@link Session#newSimpleStatement(String, Object...) simple statements}.</li>
91+ * <li>{@link Session#newSimpleStatement(String, Object...) simple statements};</li>
92+ * <li>statements created with the {@link com.datastax.driver.core.querybuilder.QueryBuilder#QueryBuilder(Cluster) Query builder}.</li>
9293 * </ul>
9394 *
9495 * Example:
95- * <pre>
96- * {@code
96+ * <pre>{@code
9797 * Row row = session.executeQuery("select date from some_table where pk = 1").one();
98- * LocalDate date = row.get(0, LocalDate.class); // uses LocalDateCodec registered above
98+ * java.time.LocalDate date = row.get(0, java.time.LocalDate.class); // uses LocalDateCodec registered above
9999 * }</pre>
100100 *
101101 * You can also bypass the codec registry by passing a standalone codec instance to methods such as
@@ -103,15 +103,18 @@
103103 *
104104 * <h3>Codec generation</h3>
105105 *
106- * When a {@code CodecRegistry} cannot find a suitable codec among existing ones, it will attempt to create it on-the-fly:
106+ * When a {@code CodecRegistry} cannot find a suitable codec among existing ones, it will attempt to create it on-the-fly.
107107 * It can manage:
108108 *
109109 * <ul>
110- * <li>collections of known types. For example, if you registered a {@code TypeCodec<LocalDate>}, you get
111- * {@code List<LocalDate>>} handled for free. This works recursively for nested collections;</li>
110+ * <li>collections (lists, sets and maps) of known types. For example,
111+ * if you registered a codec for JDK8's {@code java.time.LocalDate} like in the example above, you get
112+ * {@code List<LocalDate>>} and {@code Set<LocalDate>>} handled for free,
113+ * as well as all {@code Map} types whose keys and/or values are {@code java.time.LocalDate}.
114+ * This works recursively for nested collections;</li>
112115 * <li>{@link UserType user types}, mapped to {@link UDTValue} objects. Custom codecs are available recursively
113116 * to the UDT's fields, so if one of your fields is a {@code timestamp} you can use your {@code LocaDateCodec} to retrieve
114- * it as a {@code LocalDate};</li>
117+ * it as a {@code java.time.LocalDate};</li>
115118 * <li>{@link TupleType tuple types}, mapped to {@link TupleValue} (with the same rules for nested fields);</li>
116119 * <li>{@link com.datastax.driver.core.DataType.CustomType custom types}, mapped to {@code ByteBuffer}.</li>
117120 * </ul>
@@ -354,7 +357,7 @@
354357 * Register the given codecs with this registry.
355358 *
356359 * @param codecs The codecs to add to the registry.
357- * @return this Builder (for method chaining).
360+ * @return this CodecRegistry (for method chaining).
358361 *
359362 * @see #register(TypeCodec)
360363 */
@@ -368,7 +371,7 @@
368371 * Register the given codecs with this registry.
369372 *
370373 * @param codecs The codecs to add to the registry.
371- * @return this Builder (for method chaining).
374+ * @return this CodecRegistry (for method chaining).
372375 *
373376 * @see #register(TypeCodec)
374377 */
@@ -532,6 +535,9 @@
532535 if (codec == null)
533536 throw notFound(cqlType, javaType);
534537 // double-check that the created codec satisfies the initial request
538+ // this check can fail specially when creating codecs for collections
539+ // e.g. if B extends A and there is a codec registered for A and
540+ // we request a codec for List<B>, the registry would generate a codec for List<A>
535541 if (!codec.accepts(cqlType) || (javaType != null && !codec.accepts(javaType)))
536542 throw notFound(cqlType, javaType);
537543 logger.trace("Codec created: {}", codec);
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +3 −3
@@ -96,8 +96,9 @@
9696 * In any case, the codec's behavior in respect to {@code null} values and empty ByteBuffers
9797 * should be clearly documented.</li>
9898 * <li>TypeCodec implementations that wish to handle Java primitive types <em>must</em> be instantiated with
99- * the wrapper Java class instead, and implement the appropriate interface (see {@link BooleanCodec}
100- * for an example).</li>
99+ * the wrapper Java class instead, and implement the appropriate interface
100+ * (e.g. {@link com.datastax.driver.core.TypeCodec.PrimitiveBooleanCodec} for primitive {@code boolean} types;
101+ * there is one such interface for each Java primitive type).</li>
101102 * <li>TypeCodec implementations should not consume {@link ByteBuffer} instances by performing read operations
102103 * that modify their current position; if necessary, codecs should {@link ByteBuffer#duplicate()} duplicate} them.</li>
103104 * </ol>
@@ -518,7 +519,6 @@
518519 if (javaType.isPrimitive()) {
519520 javaType = primitiveToWrapperMap.get(javaType);
520521 }
521- // TODO accept generics type covariance, i.e. a codec for List<Number> should accept List<Integer>
522522 return this.javaType.isAssignableFrom(javaType);
523523 }
524524
modified features/custom_codecs/README.md +69 −121
@@ -41,7 +41,7 @@
4141 `CodecRegistry` is also used to manually register user-created codecs (see below for detailed instructions).
4242 It also caches codec lookup results for faster execution whenever possible.
4343
44-Refer to the [javadocs][CodecRegistry] of User `CodecRegistry` for more information.
44+Refer to the [javadocs][CodecRegistry] of `CodecRegistry` for more information.
4545
4646 ### Implementing and using custom codecs
4747
@@ -55,7 +55,7 @@
5555 CREATE TABLE t (id int PRIMARY KEY, json VARCHAR);
5656 ```
5757
58-The first step is to implement a suitable codec. Using Jackson, here is what a Json codec could like like:
58+The first step is to implement a suitable codec. Using Jackson, here is what a Json codec could look like:
5959
6060 ```java
6161 /**
@@ -87,6 +87,7 @@
8787 return null;
8888 try {
8989 byte[] b = new byte[bytes.remaining()];
90+ // always duplicate the ByteBuffer instance before consuming it!
9091 bytes.duplicate().get(b);
9192 return (T)objectMapper.readValue(b, toJacksonJavaType());
9293 } catch (IOException e) {
@@ -145,7 +146,7 @@
145146 ```
146147
147148 As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`.
148-By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
149+By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
149150 which should be adequate for most users.
150151
151152 It is however possible to create a `Cluster` using a different `CodecRegistry`:
@@ -156,8 +157,9 @@
156157 ```
157158
158159 Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver.
159-This ensures that the new registry will not lack of an essential codec. *You cannot deregister default codecs, only
160-register new ones*.
160+This ensures that the new registry will not lack of an essential codec. *You cannot deregister nor override
161+an already-registered codec, only register new ones*. If you try to register a codec that would override
162+an existing one, the driver will log a warning and ignore it.
161163
162164 From now on, your custom codec is fully operational. It will be used every time the driver encounters
163165 a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
@@ -199,50 +201,41 @@
199201 avoid any ambiguity by requiring the user to explicitly specify the desired Java type,
200202 thus forcing the driver to pick the right codec for the right task.
201203
202-### Support for parameterized types
203-
204-`get()` and `set()` can even be used to retrieve collections or other
205-user-defined parameterized types; simply use the `get()` and `set()` variants that
206-take Guava's [TypeToken] parameter:
207-
208-```java
209-Row row = ...
210-List<MyPojo> myPojos = row.get("jsonList", new TypeToken<List<MyPojo>>(){});
211-// or alternatively, the following also works for collections:
212-List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class);
213-```
214-
215-### Support for collections, user types, tuples and Java Enums
204+### On-the-fly codec generation
216205
217206 `CodecRegistry` instances not only store default codecs and user-defined codecs;
218207 they can also create new codecs on the fly, based on the set of codecs they currently hold.
208+They can manage the following mappings:
219209
220-* Codecs for [UserType] instances are created on the fly using [UDTCodec];
221-* Codecs for [TupleType] instances are created on the fly using [TupleCodec];
222-* Codecs for Java Enums are created on the fly using [EnumStringCodec];
223-* Codecs for collections are created on the fly using [ListCodec],
224- [SetCodec] and [MapCodec], if their element types can be handled by
225- existing codecs (or codecs that can themselves be generated).
210+* Collections (list, sets and maps) of known types. For example, if you registered a `TypeCodec<A>`, you get `List<A>>` handled for free. This works recursively for nested collections;
211+* [UserType] instances are automatically mapped to [UDTValue] objects. All registered codecs are available recursively to the UDT's fields;
212+* [TupleType] instances are automatically mapped to [TupleValue] objects (with the same rules for nested fields);
213+* [CustomType] instances are automatically mapped to [ByteBuffer] instances.
226214
227215 This way, the user does not have to manually register all derived codecs for a given "base" codec.
228216 However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly;
229217 such codecs must be manually registered.
230218
231-The driver also provides another codec for Enums that converts Enum instances to CQL ints
232-representing their ordinal position: [EnumIntCodec]. If you plan to use this codec, make sure to register it
233-manually, otherwise Enums would be converted using [EnumStringCodec].
234-_It is not possible to mix both codecs in the same `CodecRegistry`_.
219+If the codec registry encounters a mapping that it can't handle automatically, a [CodecNotFoundException]
220+is thrown.
221+
222+Thanks to on-the-fly codec generation, it is possible to leverage the `JsonCodec` from our previous
223+example to retrieve lists of `MyPojo` objects stored in a CQL column of type `list<text>`, without
224+the need to explicitly declare a codec for this specific CQL type:
235225
236-Note that the default set of codecs has no support for
237-[Cassandra custom types][AbstractType];
238-to be able to deserialize values of such types, you need to manually register an appropriate codec.
226+```java
227+JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
228+myCodecRegistry.register(myJsonCodec);
229+Row row = ...
230+List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class); // works out of the box!
231+```
239232
240-### Using custom codecs with user types and tuples
233+### Creating custom codecs for user-defined types (UDTs)
241234
242-By default, the driver maps user-defined type values and tuple values to [UDTValue] and [TupleValue],
243-using the built-in codecs [UDTCodec] and [TupleCodec] respectively.
235+By default, the driver maps user-defined type values to [UDTValue] instances.
244236
245-If you want to register a custom codec for a specific user type, follow these steps:
237+If you want to register a custom codec for a specific user-defined type,
238+follow these steps:
246239
247240 Let's suppose you have a keyspace containing the following type and table:
248241
@@ -369,13 +362,10 @@
369362 [this page](../object_mapper/custom_codecs/#implicit-udt-codecs) for more
370363 information.
371364
372-### Limitations
373-
374-#### Generics
365+### Support for generic (parameterized) types
375366
376-Java generic types are fully supported, through Guava's [TypeToken] API.
377-Be sure to only use `get()` and `set()` methods
378-that take a `TypeToken` argument:
367+Java generic (parameterized) types are fully supported, through Guava's [TypeToken] API.
368+Be sure to only use `get()` and `set()` methods that take a `TypeToken` argument:
379369
380370 ```java
381371 // this works
@@ -384,98 +374,56 @@
384374 Foo<Bar> foo = row.get(0, Foo.class);
385375 ```
386376
387-#### Type inheritance
388-
389-If a codec accepts a Java type that is assignable to the
390-desired Java type, that codec may be returned if it is found first
391-in the registry, *even if another codec is a better match*.
392-
393-As a consequence, type inheritance and interfaces should be used with care.
394-Let's consider an example and assume that class `B` extends class `A`:
395-
396-1) If you register a codec for `A`, you can pass `B` as the target type,
397-because `B` instances are assignable to `A`, and the driver is capable
398-of detecting that:
399-
400-```java
401-codecRegistry.register(new ACodec());
402-// all work
403-A a1 = row.get(0, A.class);
404-B b = row.get(0, B.class);
405-A a2 = row.get(0, B.class);
406-```
407-
408-However, because `List<B>` is *not* assignable to `List<A>`:
409-
410-```java
411-codecRegistry.register(new ACodec());
412-// this works
413-List<A> as1 = row.getList(0, A.class);
414-// but this throws CodecNotFoundException
415-List<B> bs = row.getList(0, B.class);
416-List<? extends A> as2 = row.getList(0, B.class);
417-```
418-
419-2) If you register a codec for `B`, you can't pass `A` as the target type,
420-because no codec matches `A.class` exactly:
421-
422-```java
423-codecRegistry.register(new BCodec());
424-// this works
425-A a1 = row.get(0, B.class);
426-B b = row.get(0, B.class);
427-// but this throws CodecNotFoundException
428-A a2 = row.get(0, A.class);
429-// and with collections, this works
430-List<B> bs = row.getList(0, B.class);
431-// but this throws CodecNotFoundException
432-List<A> as = row.getList(0, A.class);
433-```
377+### Performance considerations
434378
435-The same apply for interfaces.
379+A codec lookup operation may be costly; to mitigate this, the `CodecRegistry`
380+caches lookup results whenever possible.
436381
437-### Performance considerations
382+When the cache can be used and the registry looks up a codec, the following rules apply:
438383
439-A codec lookup operation may be costly; to mitigate this, the `CodecRegistry` caches lookup results whenever possible.
384+1. if a result was previously cached for that mapping, it is returned;
385+2. otherwise, the registry checks the list of "basic" codecs: the default ones,
386+and the ones that were explicitly registered (in the order that they were registered).
387+It calls each codec's [accepts] methods to determine if it can handle the mapping,
388+and if so, adds it to the cache and returns it;
389+3. otherwise, the registry tries to generate a codec on the fly, according to the rules outlined above;
390+4. if the creation succeeds, the registry adds the created codec to the cache and returns it;
391+5. otherwise, the registry throws [CodecNotFoundException].
440392
441-The following situations are exceptions where it is not possible to cache lookup results:
393+The cache can be used as long as _at least the CQL type is known_. The following situations
394+are exceptions where it is _not_ possible to cache lookup results:
442395
443396 * With [SimpleStatement] instances;
444397 * With [BuiltStatement] instances (created via the Query Builder).
445398
446399 In these places, the driver has no way to determine the right CQL type to use, so it performs
447-a best-effort heuristic to guess which codec to use.
400+a best-effort heuristic to guess which codec to use. The result of this heuristic is never cached.
448401
449402 Beware that in these cases, the lookup performs in average 10x worse. If performance is a key factor for your application,
450-consider using prepared statements all the time, and avoid calling ambiguous methods (prefer `get()` and `set()`).
403+consider using prepared statements all the time.
451404
452405 [JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
453-[TypeCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html
454-[LocalDate]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/LocalDate.html
455-[serialize]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#serialize(T,%20com.datastax.driver.core.ProtocolVersion)
456-[deserialize]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#deserialize(java.nio.ByteBuffer,%20com.datastax.driver.core.ProtocolVersion)
457-[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#format(T)
458-[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.html#parse(java.lang.String)
459-[CodecRegistry]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/CodecRegistry.html
406+[TypeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html
407+[LocalDate]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/LocalDate.html
408+[ByteBuffer]: http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html
409+[serialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#serialize(T,%20com.datastax.driver.core.ProtocolVersion)
410+[deserialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#deserialize(java.nio.ByteBuffer,%20com.datastax.driver.core.ProtocolVersion)
411+[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#format(T)
412+[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#parse(java.lang.String)
413+[accepts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#accepts-com.datastax.driver.core.DataType-
414+[CodecRegistry]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/CodecRegistry.html
415+[CodecNotFoundException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/CodecNotFoundException.html
460416 [Jackson]: http://wiki.fasterxml.com/JacksonHome
461417 [AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
462-[EnumStringCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumStringCodec.html
463-[EnumIntCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.EnumIntCodec.html
464-[UserType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UserType.html
465-[UDTValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/UDTValue.html
466-[UDTCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.UDTCodec.html
467-[TupleType]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleType.html
468-[TupleValue]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TupleValue.html
469-[TupleCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.TupleCodec.html
470-[ListCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.ListCodec.html
471-[SetCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.SetCodec.html
472-[MapCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MapCodec.html
418+[UserType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UserType.html
419+[UDTValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UDTValue.html
420+[TupleType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleType.html
421+[TupleValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleValue.html
422+[CustomType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/DataType.CustomType.html
473423 [TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
474-[MappingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.MappingCodec.html
475-[StringParsingCodec]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/TypeCodec.StringParsingCodec.html
476-[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SimpleStatement.html
477-[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/BuiltStatement.html
478-[setList]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setList(int,%20java.util.List)
479-[setSet]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setSet(int,%20java.util.Set)
480-[setMap]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setMap(int,%20java.util.Map)
481-[setObject]: http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/SettableByIndexData.html#setObject(int,%20V)
424+[SimpleStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SimpleStatement.html
425+[BuiltStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BuiltStatement.html
426+[setList]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setList(int,%20java.util.List)
427+[setSet]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setSet(int,%20java.util.Set)
428+[setMap]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setMap(int,%20java.util.Map)
429+[setObject]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setObject(int,%20V)