Elffuss BraidHub

kikocis/java-driver public

a3dbacfe2a6d · 19.8 KiBRenderedRawPermalink
1## Custom Codecs
2
3Custom codecs support transparent, user-configurable mapping of CQL types to arbitrary Java objects.
4
5Practical use cases that justify such a feature are numerous:
6
7* Ability to map CQL timestamp, date and time columns to Java 8 or Joda Time classes (rather than the built-in mappings for Date, [LocalDate] and Long);
8* Ability to map CQL varchar columns directly to JSON or XML mapped objects (i.e. using frameworks such as Jackson);
9* Ability to map CQL user-defined types to Java objects;
10* Ability to map CQL lists directly to Java arrays;
11* Ability to map CQL collections directly to Scala collections;
12* etc.
13
14This page explains the implementation and how to write your own custom codecs. Note that the driver also provides a set
15of [optional codecs](extras/) that might fit your needs.
16
17### Overview of the serialization mechanism
18
19The central piece in the serialization mechanism is [TypeCodec].
20
21Each `TypeCodec` supports a bidirectional mapping between a Java type and a CQL type. A `TypeCodec` is thus capable of 4 basic operations:
22
23* [Serialize][serialize] a Java object into a CQL value;
24* [Deserialize][deserialize] a CQL value into a Java object;
25* [Format][TypeCodec.format] a Java object into a CQL literal;
26* [Parse][TypeCodec.parse] a CQL literal into a Java object.
27
28Additionally, it implements inspection methods that verify if the codec is suitable for a specific
29CQL type and/or Java object.
30
31`TypeCodec` can be freely subclassed by users willing to implement their own serialization logic.
32However, users are only required to do so when they want to extend
33the driver's default set of codecs by registering additional codecs that handle
34Java types that the driver is otherwise unable to process. For all other users,
35the built-in set of codecs that is bundled with the driver provides
36exactly the same functionality that the driver used to offer so far,
37with out-of-the-box conversion from all CQL types to standard Java equivalents.
38
39Refer to the [javadocs][TypeCodec] of `TypeCodec` for more information.
40
41`TypeCodec`s are centralized in a [CodecRegistry] instance.
42Whenever the driver needs to perform one of the aforementioned operations,
43it will lookup for an appropriate codec in a `CodecRegistry`.
44`CodecRegistry` is also used to manually register user-created codecs (see below for detailed instructions).
45It also caches codec lookup results for faster execution whenever possible.
46
47Refer to the [javadocs][CodecRegistry] of `CodecRegistry` for more information.
48
49### Implementing and using custom codecs
50
51Let's consider the following scenario: a user has JSON documents stored in a varchar column, and wants
52the driver to automatically map that column to a Java object using the [Jackson] library,
53instead of returning the raw JSON string.
54
55The (admittedly simplistic) table structure is as follows:
56
57```sql
58CREATE TABLE t (id int PRIMARY KEY, json VARCHAR);
59```
60
61The first step is to implement a suitable codec. Using Jackson, here is what a Json codec could look like:
62
63```java
64/**
65 * A simple Json codec.
66 */
67public class JsonCodec<T> extends TypeCodec<T> {
68
69 private final ObjectMapper objectMapper = new ObjectMapper();
70
71 public JsonCodec(Class<T> javaType) {
72 super(DataType.varchar(), javaType);
73 }
74
75 @Override
76 public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
77 if (value == null)
78 return null;
79 try {
80 return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
81 } catch (JsonProcessingException e) {
82 throw new InvalidTypeException(e.getMessage(), e);
83 }
84 }
85
86 @Override
87 @SuppressWarnings("unchecked")
88 public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
89 if (bytes == null)
90 return null;
91 try {
92 byte[] b = new byte[bytes.remaining()];
93 // always duplicate the ByteBuffer instance before consuming it!
94 bytes.duplicate().get(b);
95 return (T) objectMapper.readValue(b, toJacksonJavaType());
96 } catch (IOException e) {
97 throw new InvalidTypeException(e.getMessage(), e);
98 }
99 }
100
101 @Override
102 public String format(T value) throws InvalidTypeException {
103 if (value == null)
104 return "NULL";
105 String json;
106 try {
107 json = objectMapper.writeValueAsString(value);
108 } catch (IOException e) {
109 throw new InvalidTypeException(e.getMessage(), e);
110 }
111 return '\'' + json.replace("\'", "''") + '\'';
112 }
113
114 @Override
115 @SuppressWarnings("unchecked")
116 public T parse(String value) throws InvalidTypeException {
117 if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
118 return null;
119 if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
120 throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
121 String json = value.substring(1, value.length() - 1).replace("''", "'");
122 try {
123 return (T) objectMapper.readValue(json, toJacksonJavaType());
124 } catch (IOException e) {
125 throw new InvalidTypeException(e.getMessage(), e);
126 }
127 }
128
129 protected JavaType toJacksonJavaType() {
130 return TypeFactory.defaultInstance().constructType(getJavaType().getType());
131 }
132
133}
134```
135
136A few implementation guidelines:
137
138* Your codecs should be thread-safe, or better yet, immutable;
139* Your codecs should be fast: do not forget that codecs are executed often and are usually very "hot" pieces of code;
140* Your codecs should never block.
141
142The second step is to register your codec with a `CodecRegistry` instance:
143
144```java
145JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class);
146CodecRegistry myCodecRegistry = cluster.getConfiguration().getCodecRegistry();
147myCodecRegistry.register(myJsonCodec);
148```
149
150As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`.
151By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
152which should be adequate for most users.
153
154It is however possible to create a `Cluster` using a different `CodecRegistry`:
155
156```java
157CodecRegistry myCodecRegistry = new CodecRegistry();
158Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
159```
160
161Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver.
162This ensures that the new registry will not lack of an essential codec. *You cannot deregister nor override
163an already-registered codec, only register new ones*. If you try to register a codec that would override
164an existing one, the driver will log a warning and ignore it.
165
166From now on, your custom codec is fully operational. It will be used every time the driver encounters
167a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
168
169For example, here is how to save a `MyPojo` object:
170
171```java
172Cluster cluster = ...
173Session session = ...
174MyPojo myPojo = ...
175// Using SimpleStatement
176Statement stmt = new SimpleStatement("INSERT INTO t (id, json) VALUES (?, ?)", 42, myPojo));
177// Using the Query Builder
178BuiltStatement insertStmt = QueryBuilder.insertInto("t")
179 .value("id", 42)
180 .value("json", myPojo);
181// Using BoundStatements
182PreparedStatement ps = session.prepare("INSERT INTO t (id, json) VALUES (?, ?)");
183BoundStatement bs1 = ps.bind(42, myPojo); // or alternatively...
184BoundStatement bs2 = ps.bind()
185 .setInt(0, 42)
186 .set(1, myPojo, MyPojo.class);
187```
188
189And here is how to retrieve a `MyPojo` object converted from a JSON document:
190
191```java
192ResultSet rs = session.execute(...);
193Row row = rs.one();
194// Let the driver convert the string for you...
195MyPojo myPojo = row.get(1, MyPojo.class);
196// ... or retrieve the raw string if you need it
197String json = row.get(1, String.class); // row.getString(1) would have worked too
198```
199
200Tip: `Row` and `BoundStatement` have several methods to set and retrieve values.
201But if you plan to use custom codecs,
202make sure that you use preferably the `get()` and `set()` methods: they
203avoid any ambiguity by requiring the user to explicitly specify the desired Java type,
204thus forcing the driver to pick the right codec for the right task.
205
206Custom codecs also work with the driver's [object mapper](../object_mapper/custom_codecs/).
207
208### On-the-fly codec generation
209
210`CodecRegistry` instances not only store default codecs and user-defined codecs;
211they can also create new codecs on the fly, based on the set of codecs they currently hold.
212They can manage the following mappings:
213
214* 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;
215* [UserType] instances are automatically mapped to [UDTValue] objects. All registered codecs are available recursively to the UDT's fields;
216* [TupleType] instances are automatically mapped to [TupleValue] objects (with the same rules for nested fields);
217* [CustomType] instances are automatically mapped to [ByteBuffer] instances.
218
219This way, the user does not have to manually register all derived codecs for a given "base" codec.
220However, other combinations of Java and CQL types not listed above cannot have their codecs created on the fly;
221such codecs must be manually registered.
222
223If the codec registry encounters a mapping that it can't handle automatically, a [CodecNotFoundException]
224is thrown.
225
226Thanks to on-the-fly codec generation, it is possible to leverage the `JsonCodec` from our previous
227example to retrieve lists of `MyPojo` objects stored in a CQL column of type `list<text>`, without
228the need to explicitly declare a codec for this specific CQL type:
229
230```java
231JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class);
232myCodecRegistry.register(myJsonCodec);
233Row row = ...
234List<MyPojo> myPojos = row.getList("jsonList", MyPojo.class); // works out of the box!
235```
236
237### Creating custom codecs for user-defined types (UDTs)
238
239By default, the driver maps user-defined type values to [UDTValue] instances.
240
241If you want to register a custom codec for a specific user-defined type,
242follow these steps:
243
244Let's suppose you have a keyspace containing the following type and table:
245
246```sql
247CREATE TYPE address (street VARCHAR, zipcode INT);
248CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR, address frozen<address>);
249```
250
251And let's suppose that you want to map the type `address` to an `Address` class:
252
253```java
254public class Address {
255
256 private final String street;
257
258 private final int zipcode;
259
260 public Address(String street, int zipcode) {
261 this.street = street;
262 this.zipcode = zipcode;
263 }
264
265 // getters, setters, equals() and hashcode() omitted
266}
267```
268
269First of all, create a codec that knows how to serialize this class; one possible solution
270(but not necessarily the most efficient one) would be to convert `Address` instances into `UDTValue`
271instances, then serialize them with another codec:
272
273
274```java
275public class AddressCodec extends TypeCodec<Address> {
276
277 private final TypeCodec<UDTValue> innerCodec;
278
279 private final UserType userType;
280
281 public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) {
282 super(innerCodec.getCqlType(), javaType);
283 this.innerCodec = innerCodec;
284 this.userType = (UserType)innerCodec.getCqlType();
285 }
286
287 @Override
288 public ByteBuffer serialize(Address value, ProtocolVersion protocolVersion) throws InvalidTypeException {
289 return innerCodec.serialize(toUDTValue(value), protocolVersion);
290 }
291
292 @Override
293 public Address deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
294 return toAddress(innerCodec.deserialize(bytes, protocolVersion));
295 }
296
297 @Override
298 public Address parse(String value) throws InvalidTypeException {
299 return value == null || value.isEmpty() || value.equals(NULL) ? null : toAddress(innerCodec.parse(value));
300 }
301
302 @Override
303 public String format(Address value) throws InvalidTypeException {
304 return value == null ? null : innerCodec.format(toUDTValue(value));
305 }
306
307 protected Address toAddress(UDTValue value) {
308 return value == null ? null : new Address(
309 value.getString("street"),
310 value.getInt("zipcode")
311 );
312 }
313
314 protected UDTValue toUDTValue(Address value) {
315 return value == null ? null : userType.newValue()
316 .setString("street", value.getStreet())
317 .setInt("zipcode", value.getZipcode());
318 }
319}
320```
321
322Now (and only if you intend to use your own `CodecRegistry`),
323create it and register it on your `Cluster` instance:
324
325```java
326// only if you do not intend to use CodecRegistry.DEFAULT_INSTANCE
327CodecRegistry codecRegistry = new CodecRegistry();
328Cluster cluster = Cluster.builder()
329 .addContactPoints(...)
330 .withCodecRegistry(codecRegistry)
331 .build();
332```
333
334Now, retrieve the metadata for type `address`:
335
336```java
337UserType addressType = cluster.getMetadata().getKeyspace(...).getUserType("address");
338TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType);
339```
340
341And finally, register your `AddressCodec` with the `CodecRegistry`. Note that
342your codec simply delegates the hard work to an inner codec that knows how to deal with
343user type values:
344
345```java
346AddressCodec addressCodec = new AddressCodec(addressTypeCodec, Address.class);
347codecRegistry.register(addressCodec);
348```
349
350And voilà! You can now retrieve `address` values as `Address` instances:
351
352```java
353ResultSet rows = session.execute(...);
354Row row = rows.one();
355// let the driver convert it for you...
356Address address = row.get("address", Address.class);
357// ...or access the low-level UDTValue, if you need
358UDTValue addressUdt = row.get("address", UDTValue.class); // row.getUDTValue("address") would have worked too
359```
360
361Note that this solution creates an intermediary `UDTValue` object when
362serializing and deserializing. It's possible to bypass this step with a
363lower-level implementation that manipulates the binary stream directly.
364That's also how the object mapper handles UDTs, and you can rely on the
365mapper to generate UDT codecs for you; see
366[this page](../object_mapper/custom_codecs/#implicit-udt-codecs) for more
367information.
368
369### Support for generic (parameterized) types
370
371Java generic (parameterized) types are fully supported, through Guava's [TypeToken] API.
372Be sure to only use `get()` and `set()` methods that take a `TypeToken` argument:
373
374```java
375// this works
376Foo<Bar> foo = row.get(0, new TypeToken<Foo<Bar>>(){})
377// this does not work due to type erasure
378Foo<Bar> foo = row.get(0, Foo.class);
379```
380
381### Support for subtype polymorphism
382
383Suppose the following class hierarchy:
384
385```java
386class Animal {}
387class Cat extends Animal {}
388```
389
390By default, a codec will accept to serialize any object that extends or
391implements its declared Java type: a codec such as
392`AnimalCodec extends TypeCodec<Animal>` will accept `Cat` instances as well.
393
394This allows a codec to handle interfaces and superclasses
395in a generic way, regardless of the actual implementation being
396used by client code; for example, the driver has a built-in codec
397that handles `List` instances, and this codec is capable of
398serializing any concrete `List` implementation.
399
400But this has one caveat: when setting or retrieving values
401with `get()` and `set()`, *it is vital to pass the exact
402Java type the codec handles*:
403
404```java
405codecRegistry.register(new AnimalCodec());
406BoundStatement bs = ...
407bs.set(0, new Cat(), Animal.class); // works
408bs.set(0, new Cat(), Cat.class); // throws CodecNotFoundException
409```
410
411The same is valid when retrieving values:
412
413```java
414codecRegistry.register(new AnimalCodec());
415Row row = ...
416Animal animal = row.get(0, Animal.class); // works
417Cat cat = row.get(0, Cat.class); // throws CodecNotFoundException
418```
419
420### Performance considerations
421
422A codec lookup operation may be costly; to mitigate this, the `CodecRegistry`
423caches lookup results whenever possible.
424
425When the cache can be used and the registry looks up a codec, the following rules apply:
426
4271. if a result was previously cached for that mapping, it is returned;
4282. otherwise, the registry checks the list of "basic" codecs: the default ones,
429and the ones that were explicitly registered (in the order that they were registered).
430It calls each codec's [accepts] methods to determine if it can handle the mapping,
431and if so, adds it to the cache and returns it;
4323. otherwise, the registry tries to generate a codec on the fly, according to the rules outlined above;
4334. if the creation succeeds, the registry adds the created codec to the cache and returns it;
4345. otherwise, the registry throws [CodecNotFoundException].
435
436The cache can be used as long as *at least the CQL type is known*. The following situations
437are exceptions where it is *not* possible to cache lookup results:
438
439* With [SimpleStatement] instances;
440* With [BuiltStatement] instances (created via the Query Builder).
441
442In these places, the driver has no way to determine the right CQL type to use, so it performs
443a best-effort heuristic to guess which codec to use. The result of this heuristic is never cached.
444
445Beware that in these cases, the lookup performs in average 10x worse. If performance is a key factor for your application,
446consider using prepared statements all the time.
447
448[JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721
449[TypeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html
450[LocalDate]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/LocalDate.html
451[ByteBuffer]: http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html
452[serialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#serialize-T-com.datastax.driver.core.ProtocolVersion-
453[deserialize]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#deserialize-java.nio.ByteBuffer-com.datastax.driver.core.ProtocolVersion-
454[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#format-T-
455[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#parse-java.lang.String-
456[accepts]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TypeCodec.html#accepts-com.datastax.driver.core.DataType-
457[CodecRegistry]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/CodecRegistry.html
458[CodecNotFoundException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/CodecNotFoundException.html
459[Jackson]: http://wiki.fasterxml.com/JacksonHome
460[AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
461[UserType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UserType.html
462[UDTValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/UDTValue.html
463[TupleType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleType.html
464[TupleValue]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TupleValue.html
465[CustomType]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/DataType.CustomType.html
466[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
467[SimpleStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SimpleStatement.html
468[BuiltStatement]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/querybuilder/BuiltStatement.html
469[setList]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setList-int-java.util.List-
470[setSet]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setSet-int-java.util.Set-
471[setMap]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SettableByIndexData.html#setMap-int-java.util.Map-