Elffuss BraidHub

kikocis/java-driver public

Document extra codecs.
Changeset6b20a0b8e2754b5e0c12181d911b259b7c76b244eef3bb637bddbc8c3831f506
Authorolim7t <omichallat+github@gmail.com> · 2016-01-25 18:15 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-01-26 22:39 +01:00
Parentsd844cea208b1

Browse the files at this changeset

2 files changed

modified manual/custom_codecs/README.md +3 −0
@@ -11,6 +11,9 @@
1111 * Ability to map CQL collections directly to Scala collections;
1212 * etc.
1313
14+This page explains the implementation and how to write your own custom codecs. Note that the driver also provides a set
15+of [optional codecs](extras/) that might fit your needs.
16+
1417 ### Overview of the serialization mechanism
1518
1619 The central piece in the serialization mechanism is [TypeCodec].
added manual/custom_codecs/extras/README.md +419 −0
@@ -0,0 +1,419 @@
1+## Optional codecs
2+
3+The driver's "extras" module provides additional [codec](../) implementations: these codecs are not required by core
4+driver features, but will probably prove useful in a lot of client applications. You can also study their source code as
5+a reference to write your own.
6+
7+The module is published as a separate Maven artifact:
8+
9+```xml
10+<dependency>
11+ <groupId>com.datastax.cassandra</groupId>
12+ <artifactId>cassandra-driver-extras</artifactId>
13+ <version>3.0.0-rc1</version>
14+</dependency>
15+```
16+
17+It also declares a number of optional dependencies, that you'll need to explicitly re-declare in your application
18+depending on which codecs you plan to use (this will be covered for each case below).
19+
20+### Temporal types
21+
22+JDK 8 and Joda Time support have often been requested; they're not in the core module because we want to preserve
23+compatibility with older JDKs and avoid extra dependencies.
24+
25+#### JDK 8
26+
27+[InstantCodec] maps [Instant] to CQL's `timestamp`:
28+
29+```java
30+import com.datastax.driver.extras.codecs.jdk8.InstantCodec;
31+import java.time.Instant;
32+
33+cluster.getConfiguration().getCodecRegistry()
34+ .register(InstantCodec.instance);
35+
36+// schema: CREATE TABLE example(id int PRIMARY KEY, t timestamp)
37+session.execute("INSERT INTO example (id, t) VALUES (1, ?)",
38+ Instant.parse("2010-06-30T01:20:30Z"));
39+```
40+
41+Similarly:
42+
43+* [LocalDateCodec] maps [LocalDate] to `date`;
44+* [LocalTimeCodec] maps [LocalTime] to `time`.
45+
46+One problem with `timestamp` is that it does not store time zones. [ZonedDateTimeCodec] addresses that, by mapping a
47+[ZonedDateTime] to a `tuple<timestamp,varchar>`:
48+
49+```java
50+// Due to internal implementation details, you have to retrieve the tuple type from a live cluster:
51+TupleType tupleType = cluster.getMetadata()
52+ .newTupleType(DataType.timestamp(), DataType.varchar());
53+cluster.getConfiguration().getCodecRegistry()
54+ .register(new ZonedDateTimeCodec(tupleType));
55+
56+// schema: CREATE TABLE example(id int PRIMARY KEY, t tuple<timestamp,varchar>)
57+session.execute("INSERT INTO example (id, t) VALUES (1, ?)",
58+ ZonedDateTime.parse("2010-06-30T01:20:47.999+01:00"));
59+```
60+
61+[InstantCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/InstantCodec.html
62+[LocalDateCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/LocalDateCodec.html
63+[LocalTimeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodec.html
64+[ZonedDateTimeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodec.html
65+[Instant]: https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
66+[LocalDate]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
67+[LocalTime]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html
68+[ZonedDateTime]: https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html
69+
70+
71+#### Joda time
72+
73+These codecs require an explicit dependency on Joda Time in your application:
74+
75+```xml
76+<dependency>
77+ <groupId>joda-time</groupId>
78+ <artifactId>joda-time</artifactId>
79+ <version>2.9.1</version>
80+</dependency>
81+```
82+
83+Like for JDK8, there is a codec for each time type:
84+
85+* [InstantCodec][InstantCodec_joda]: [Instant][Instant_joda] to `timestamp`;
86+* [LocalDateCodec][LocalDateCodec_joda]: [LocalDate][LocalDate_joda] to `date`;
87+* [LocalTime][LocalTime_joda]: [LocalTime][LocalTime_joda] to `time`.
88+
89+```java
90+import com.datastax.driver.extras.codecs.joda.InstantCodec;
91+import org.joda.time.Instant;
92+
93+cluster.getConfiguration().getCodecRegistry()
94+ .register(InstantCodec.instance);
95+
96+// schema: CREATE TABLE example(id int PRIMARY KEY, t timestamp)
97+session.execute("INSERT INTO example (id, t) VALUES (1, ?)",
98+ Instant.parse("2010-06-30T01:20:30Z"));
99+```
100+
101+And [DateTimeCodec] can save [DateTime] instances with a time zone:
102+
103+```java
104+TupleType tupleType = cluster.getMetadata()
105+ .newTupleType(DataType.timestamp(), DataType.varchar());
106+cluster.getConfiguration().getCodecRegistry()
107+ .register(new DateTimeCodec(tupleType));
108+
109+// schema: CREATE TABLE example(id int PRIMARY KEY, t tuple<timestamp,varchar>)
110+session.execute("INSERT INTO example (id, t) VALUES (1, ?)",
111+ DateTime.parse("2010-06-30T01:20:47.999+01:00"));
112+```
113+
114+[InstantCodec_joda]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/joda/InstantCodec.html
115+[LocalDateCodec_joda]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/joda/LocalDateCodec.html
116+[LocalTimeCodec_joda]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/joda/LocalTimeCodec.html
117+[DateTimeCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/joda/DateTimeCodec.html
118+[DateTime]: http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html
119+[Instant_joda]: http://www.joda.org/joda-time/apidocs/org/joda/time/Instant.html
120+[LocalDate_joda]: http://www.joda.org/joda-time/apidocs/org/joda/time/LocalDate.html
121+[LocalTime_joda]: http://www.joda.org/joda-time/apidocs/org/joda/time/LocalTime.html
122+
123+
124+#### Primitive types
125+
126+Time can also be expressed as simple durations:
127+
128+* [SimpleTimestampCodec] maps `timestamp` to a primitive Java `long` representing the number of milliseconds since the
129+ Epoch;
130+* [SimpleDateCodec] maps `date` to a primitive Java `int` representing the number of milliseconds since the Epoch.
131+
132+There is no extra codec for `time`, because by default the driver already maps that type to a `long` representing the
133+number of milliseconds since midnight.
134+
135+[SimpleTimestampCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/date/SimpleTimestampCodec.html
136+[SimpleDateCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/date/SimpleDateCodec.html
137+
138+
139+### Enums
140+
141+Enums can be mapped in two different ways:
142+
143+[EnumNameCodec] stores enum constants as a `varchar` representing their [name]:
144+
145+```java
146+enum State {INIT, RUNNING, STOPPING, STOPPED}
147+
148+cluster.getConfiguration().getCodecRegistry()
149+ .register(new EnumNameCodec<State>(State.class));
150+
151+// schema: create table name_example(id int PRIMARY KEY, state text)
152+session.execute("insert into name_example (id, state) values (1, ?)", State.INIT);
153+// state is saved as 'INIT'
154+```
155+
156+[EnumOrdinalCodec] stores enum constants as an `int` representing their [ordinal]:
157+
158+```java
159+enum State {INIT, RUNNING, STOPPING, STOPPED}
160+
161+cluster.getConfiguration().getCodecRegistry()
162+ .register(new EnumOrdinalCodec<State>(State.class));
163+
164+// schema: create table ordinal_example(id int PRIMARY KEY, state int)
165+session.execute("insert into ordinal_example (id, state) values (1, ?)", State.INIT);
166+// state saved as 0
167+```
168+
169+Note that if you registered both codecs at the same time, there would be a problem: because `session.execute` uses a
170+[simple statement](../../statements/simple/), the target CQL type is not known in advance, so the driver picks the first
171+codec that accepts a `State`. So one of the statements would serialize its value to the wrong type, and the request
172+would fail on the server side.
173+
174+In practice, this is unlikely to happen, because you'll probably stick to a single CQL type for a given enum type;
175+however, if you ever run into that issue, the workaround is to use [prepared statements](../../statements/prepared/),
176+for which the driver knows the CQL type and can pick the exact codec.
177+
178+[EnumNameCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/enums/EnumNameCodec.html
179+[EnumOrdinalCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/enums/EnumOrdinalCodec.html
180+[name]: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#name--
181+[ordinal]: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#ordinal--
182+
183+
184+### JSON
185+
186+#### Jackson
187+
188+[JacksonJsonCodec] maps a Java object to a JSON string stored into a `varchar` column, using the popular [Jackson]
189+library.
190+
191+It requires an explicit dependency on Jackson in your application:
192+
193+```xml
194+<dependency>
195+ <groupId>com.fasterxml.jackson.core</groupId>
196+ <artifactId>jackson-databind</artifactId>
197+ <version>2.6.3</version>
198+</dependency>
199+```
200+
201+```java
202+public class User {
203+ private int id;
204+ private String name;
205+
206+ @JsonCreator
207+ public User(@JsonProperty("id") int id, @JsonProperty("name") String name) {
208+ this.id = id;
209+ this.name = name;
210+ }
211+
212+ ... // getters and setters
213+}
214+
215+cluster.getConfiguration().getCodecRegistry()
216+ .register(new JacksonJsonCodec<User>(User.class));
217+
218+// schema: create table example(id int primary key, owner varchar);
219+session.execute("insert into example (id, owner) values (1, ?)",
220+ new User(1, "root"));
221+// owner saved as '{"id":1,"name":"root"}'
222+```
223+
224+[JacksonJsonCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/json/JacksonJsonCodec.html
225+[Jackson]: http://wiki.fasterxml.com/JacksonHome
226+
227+
228+#### JSR 353
229+
230+[Jsr353JsonCodec] maps a [JsonStructure] to a JSON string stored into a `varchar` column, using the JSR-353 standard.
231+
232+It requires an explicit dependency on the JSR-353 API and an implementation:
233+
234+```java
235+<dependency>
236+ <groupId>javax.json</groupId>
237+ <artifactId>javax.json-api</artifactId>
238+ <version>1.0</version>
239+</dependency>
240+
241+<!-- Reference implementation -->
242+<dependency>
243+ <groupId>org.glassfish</groupId>
244+ <artifactId>javax.json</artifactId>
245+ <version>1.0.4</version>
246+</dependency>
247+```
248+
249+```java
250+cluster.getConfiguration().getCodecRegistry()
251+ .register(new Jsr353JsonCodec());
252+
253+// schema: create table example(id int primary key, owner varchar);
254+session.execute("insert into example (id, owner) values (1, ?)",
255+ javax.json.Json.createObjectBuilder()
256+ .add("id", 1)
257+ .add("name", "root")
258+ .build());
259+// owner saved as '{"id":1,"name":"root"}'
260+```
261+
262+
263+[Jsr353JsonCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/json/Jsr353JsonCodec.html
264+[JsonStructure]: https://javaee-spec.java.net/nonav/javadocs/javax/json/JsonStructure.html
265+
266+
267+### Optional
268+
269+"Optional" types provide an alternate way to represent missing values, in an attempt to avoid null pointer errors. With
270+these codecs, missing values will be mapped to `NULL` in the database.
271+
272+#### JDK8
273+
274+[OptionalCodec] transforms another codec to wrap its Java type in a JDK8 [Optional].
275+
276+```java
277+import com.datastax.driver.extras.codecs.jdk8.OptionalCodec;
278+import com.google.common.reflect.TypeToken;
279+import java.util.Optional;
280+
281+// The built-in driver codec, that maps CQL's int to Java's Integer
282+TypeCodec<Integer> intCodec = TypeCodec.cint();
283+
284+// A codec that maps CQL's int to Java's Optional<Integer>
285+OptionalCodec<Integer> optionalIntCodec = new OptionalCodec<Integer>(intCodec);
286+
287+cluster.getConfiguration().getCodecRegistry()
288+ .register(optionalIntCodec);
289+
290+TypeToken<Optional<Integer>> optionalIntToken = new TypeToken<Optional<Integer>>() {};
291+
292+// schema: create table example (id int primary key, v int);
293+PreparedStatement pst = session.prepare("insert into example (id, v) values (?, ?)");
294+
295+Optional<Integer> v1 = Optional.empty();
296+session.execute(pst.bind()
297+ .setInt("id", 1)
298+ .set("v", v1, optionalIntToken));
299+// v1 saved as NULL
300+
301+Optional<Integer> v2 = Optional.of(12);
302+session.execute(pst.bind()
303+ .setInt("id", 2)
304+ .set("v", v2, optionalIntToken));
305+// v2 saved as 12
306+```
307+
308+This example is a bit more complex: `Optional<Integer>` is a generic type, so we can't use simple statements, because
309+they select codecs according to the runtime types of their values (and we would lose the `<Integer>` part with type
310+erasure).
311+
312+For the same reason, we need to give a type hint when setting "v", in the form of a [TypeToken]. Note that this is an
313+anonymous inner class; we recommend storing these tokens as constants in a utility class, to avoid creating them too
314+often.
315+
316+[OptionalCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/jdk8/OptionalCodec.html
317+[Optional]: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
318+[TypeToken]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html
319+
320+#### Guava
321+
322+[OptionalCodec][OptionalCodec_guava] transforms another codec to wrap its Java type in a Guava
323+[Optional][Optional_guava].
324+
325+
326+```java
327+import com.datastax.driver.extras.codecs.guava.OptionalCodec;
328+import com.google.common.base.Optional;
329+import com.google.common.reflect.TypeToken;
330+
331+// The built-in driver codec, that maps CQL's int to Java's Integer
332+TypeCodec<Integer> intCodec = TypeCodec.cint();
333+
334+// A codec that maps CQL's int to Guava's Optional<Integer>
335+OptionalCodec<Integer> optionalIntCodec = new OptionalCodec<Integer>(intCodec);
336+
337+cluster.getConfiguration().getCodecRegistry()
338+ .register(optionalIntCodec);
339+
340+TypeToken<Optional<Integer>> optionalIntToken = new TypeToken<Optional<Integer>>() {
341+};
342+
343+// schema: create table example (id int primary key, v int);
344+PreparedStatement pst = session.prepare("insert into example (id, v) values (?, ?)");
345+
346+Optional<Integer> v1 = Optional.absent();
347+session.execute(pst.bind()
348+ .setInt("id", 1)
349+ .set("v", v1, optionalIntToken));
350+// v1 saved as NULL
351+
352+Optional<Integer> v2 = Optional.of(12);
353+session.execute(pst.bind()
354+ .setInt("id", 2)
355+ .set("v", v2, optionalIntToken));
356+// v2 saved as 12
357+```
358+
359+See the JDK8 Optional section above for explanations about [TypeToken].
360+
361+[OptionalCodec_guava]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/guava/OptionalCodec.html
362+[Optional_guava]: http://docs.guava-libraries.googlecode.com/git-history/v16.0.1/javadoc/com/google/common/base/Optional.html
363+
364+
365+### Arrays
366+
367+By default, the driver maps CQL lists to collections of Java objects. For high-performance scenarios, and when the
368+element type maps to a Java primitive, you might want to map to an array instead, to avoid unnecessary boxing and
369+unboxing.
370+
371+[IntArrayCodec] allows you to do that for lists of integers:
372+
373+```java
374+cluster.getConfiguration().getCodecRegistry()
375+ .register(new IntArrayCodec());
376+
377+// schema: create table example (i int primary key, l list<int>)
378+session.execute("insert into example (i, l) values (1, ?)",
379+ new int[]{1, 2, 3});
380+// array saved as [1,2,3]
381+```
382+
383+Package [com.datastax.driver.extras.codecs.arrays][arrays] contains similar codecs for all primitive types, and
384+[ObjectArrayCodec] to map arrays of objects.
385+
386+[IntArrayCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/arrays/IntArrayCodec.html
387+[ObjectArrayCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/arrays/ObjectArrayCodec.html
388+[arrays]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/arrays/package-summary.html
389+
390+### Abstract utilities
391+
392+The module provides two abstract classes that act as building blocks for your own codecs:
393+
394+[MappingCodec] is useful when you can easily convert your Java type to another type that already has a codec.
395+For example, if you have a `Price` object that translates to a plain `Integer`, you can piggyback on the built-in
396+integer codec, and you'll only have to write two simple conversion methods:
397+
398+```java
399+public static class PriceCodec extends MappingCodec<Price, Integer> {
400+ public PriceCodec() { super(TypeCodec.cint(), Price.class); }
401+
402+ @Override
403+ protected Integer serialize(Price value) { ... }
404+
405+ @Override
406+ protected Price deserialize(Integer value) { ... }
407+}
408+```
409+
410+For a more detailed example, you can look at the `OptionalCodec` implementations in the source code.
411+
412+[ParsingCodec] is similar, but specialized for text columns. See `EnumNameCodec` for an example.
413+
414+These two classes are convenient, but since they perform conversions in two steps, extending them is not necessarily the
415+optimal approach. If performance is paramount, it's better to start from scratch and convert your objects to
416+`ByteBuffer` directly.
417+
418+[MappingCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/MappingCodec.html
419+[ParsingCodec]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/extras/codecs/ParsingCodec.html
No newline at the end of the file