|
| 1 | ++++ |
| 2 | +date = "2015-03-19T14:27:51-04:00" |
| 3 | +title = "Codec and CodecRegistry" |
| 4 | +[menu.main] |
| 5 | + parent = "BSON" |
| 6 | + weight = 10 |
| 7 | + pre = "<i class='fa'></i>" |
| 8 | ++++ |
| 9 | + |
| 10 | +## Codec and CodecRegistry |
| 11 | + |
| 12 | +In the last section we saw how to use the [`BsonReader`]({{< apiref "org/bson/BsonReader" >}}) and |
| 13 | +[`BsonWriter`]({{< apiref "org/bson/BsonWriter" >}}) API to read and write BSON documents. But writing code at that |
| 14 | +low a level is tedious and error-prone, so in practice these algorithms are packaged in implementations of the |
| 15 | +[`Codec`]({{< apiref "org/bson/codecs/Codec" >}}) interface. |
| 16 | + |
| 17 | +### Codec |
| 18 | + |
| 19 | +The `Codec` interface abstracts the processes of decoding a BSON value into a Java object using a `BsonReader` and encoding a Java object |
| 20 | + into a BSON value using a `BsonWriter`. The BSON value can be as simple as a boolean or as complex as a document or array. |
| 21 | + |
| 22 | +Let's look at a simple `Codec` implementation that encodes a Java `Integer` to a BSON Int32, and vice versa: |
| 23 | + |
| 24 | +```java |
| 25 | +public class IntegerCodec implements Codec<Integer> { |
| 26 | + @Override |
| 27 | + public void encode(final BsonWriter writer, final Integer value, final EncoderContext encoderContext) { |
| 28 | + writer.writeInt32(value); |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public Integer decode(final BsonReader reader, final DecoderContext decoderContext) { |
| 33 | + return reader.readInt32(); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public Class<Integer> getEncoderClass() { |
| 38 | + return Integer.class; |
| 39 | + } |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +The `encode` method takes a `BsonWriter` and an `Integer` and calls the `writeInt32` method on the `BsonWriter` with the value of the |
| 44 | +`Integer`, while the `decode` method takes a `BsonReader` and calls the `readInt32` method on the `BsonReader`, returning the value as an |
| 45 | +`Integer`. |
| 46 | + |
| 47 | +A `Codec` implementation than encodes to and decodes from a BSON document or array is more complicated, and would typically |
| 48 | +rely on a set of simpler `Codec` implementations for the basic BSON value types. For this, it can rely on a `CodecRegistry`. |
| 49 | + |
| 50 | +### CodecRegistry |
| 51 | + |
| 52 | +A [`CodecRegistry`]({{< apiref "org/bson/codecs/configuration/CodecRegistry" >}}) contains a set of `Codec` instances that are accessed |
| 53 | +according to the Java classes that they encode from and decode to. Instances of `CodecRegistry` are generally created via static factory |
| 54 | +methods on the [`CodecRegistries`]({{< apiref "org/bson/codecs/configuration/CodecRegistries" >}}) class. Consider the simplest of these |
| 55 | +methods, one that takes a list of `Codec`s: |
| 56 | + |
| 57 | +```java |
| 58 | +CodecRegistry registry = CodecRegistries.fromCodecs(new IntegerCodec(), new LongCodec(), ...); |
| 59 | +``` |
| 60 | + |
| 61 | +This returns an immutable `CodecRegistry` instance containing all the `Codec` instances passed to the `fromCodecs` method. They can be |
| 62 | +accessed like this: |
| 63 | + |
| 64 | +```java |
| 65 | +Codec<Integer> integerCodec = codecRegistry.get(Integer.class); |
| 66 | +Codec<Long> longCodec = codecRegistry.get(Long.class); |
| 67 | +``` |
| 68 | + |
| 69 | +Now consider a `Codec` for the `Document` class. This `Codec` implementation, in order to decode and |
| 70 | +encode the values for each field in the document, must be constructed with a `CodecRegistry` to look up the `Codec` instances for each type |
| 71 | +of value. But how could one construct an instance of that `Codec`? You would have to pass an instance to the |
| 72 | +`CodecRegistries.fromCodecs` method, but you don't have a `CodecRegistry` yet to pass to the constructor. You need some way to delay the |
| 73 | +construction of the `Document` `Codec` until after the `CodecRegistry` has been constructed. For that we use a `CodecProvider`. |
| 74 | + |
| 75 | +### CodecProvider |
| 76 | + |
| 77 | +A [`CodecProvider`]({{< apiref "org/bson/codecs/configuration/CodecProvider" >}}) is a factory for `Codec` instances. Unlike |
| 78 | +`CodecRegistry`, its `get` method takes not only a Class, but also a `CodecRegistry`, allowing a `CodecProvider` implementation to |
| 79 | +construct `Codec` instances that require a `CodecRegistry` to look up `Codec` instances for the values contained within it. Consider a |
| 80 | +`CodecProvider` for the `Document` class: |
| 81 | + |
| 82 | +```java |
| 83 | +public class DocumentCodecProvider implements CodecProvider { |
| 84 | + @Override |
| 85 | + public <T> Codec<T> get(final Class<T> clazz, final CodecRegistry registry) { |
| 86 | + if (clazz == Document.class) { |
| 87 | + // construct DocumentCodec with a CodecRegistry |
| 88 | + return (Codec<T>) new DocumentCodec(registry); |
| 89 | + } |
| 90 | + |
| 91 | + // CodecProvider returns null if it's not a provider for the requresed Class |
| 92 | + return null; |
| 93 | + } |
| 94 | +} |
| 95 | +``` |
| 96 | + |
| 97 | +The `DocumentCodec`, because it is constructed with a `CodecRegistry`, can now use that registry to look up `Codec` instances for the |
| 98 | +values contained in each Document that it encodes. |
| 99 | + |
| 100 | +One more problem remains, however. Consider the problem of encoding values to a BSON DateTime. An application may want to |
| 101 | +encode to a BSON DateTime instances of both the original Java `Date` class as well as the Java 8 `Instance` class. It's easy to create |
| 102 | +implemenations of `Codec<Date>` and `Codec<Instant>`, and either one can be used for encoding. But when decoding, a Document `Codec` |
| 103 | +also has to choose which Java type to decode a BSON DateTime to. Rather than hard-coding it in the `DocumentCodec`, the decision is |
| 104 | +abstracted via the `BsonTypeClassMap` class. |
| 105 | + |
| 106 | +### BsonTypeClassMap |
| 107 | + |
| 108 | +The [`BsonTypeClassMap`]({{< apiref "org/bson/codecs/BsonTypeClassMap" >}}) class simply maps each value in the `BsonType` |
| 109 | +enumeration to a Java class. It contains a sensible set of default mappings that can easily be changed by passing an a `Map<BsonType, |
| 110 | +Class<?>>` instance to the constructor with any replacement mappings to apply. Consider the case where an application wants to decode |
| 111 | +all BSON DateTime values to a Java 8 `Instant` instead of the default `Date`: |
| 112 | + |
| 113 | +```java |
| 114 | +Map<BsonType, Class<?>> replacements = new HashMap<BsonType, Class<?>>(); |
| 115 | +replacements.put(BsonType.DATE_TIME, Instant.class); |
| 116 | +BsonTypeClassMap bsonTypeClassMap = new BsonTypeClassMap(replacements); |
| 117 | +``` |
| 118 | + |
| 119 | +This will replace the default mapping of BSON DateTime to `Date` to one from BSON DateTime to `Instant`. |
| 120 | + |
| 121 | +Putting it all together, we can added a BsonTypeClassMap to the DocumentCodecProvider shown above: |
| 122 | + |
| 123 | +```java |
| 124 | +public class DocumentCodecProvider implements CodecProvider { |
| 125 | + private final BsonTypeClassMap bsonTypeClassMap; |
| 126 | + |
| 127 | + public DocumentCodecProvider(final BsonTypeClassMap bsonTypeClassMap) { |
| 128 | + this.bsonTypeClassMap = bsonTypeClassMap; |
| 129 | + } |
| 130 | + |
| 131 | + @Override |
| 132 | + public <T> Codec<T> get(final Class<T> clazz, final CodecRegistry registry) { |
| 133 | + if (clazz == Document.class) { |
| 134 | + // construct DocumentCodec with a CodecRegistry and a BsonTypeClassMap |
| 135 | + return (Codec<T>) new DocumentCodec(registry, bsonTypeClassMap); |
| 136 | + } |
| 137 | + |
| 138 | + return null; |
| 139 | + } |
| 140 | +} |
| 141 | +``` |
| 142 | + |
| 143 | +The `DocumentCodec`, because it is constructed with both a `BsonTypeClassMap` and a `CodecRegistry`, can first use the `BsonTypeClassMap` |
| 144 | +to determine with type to decode each BSON value to, then use the `CodecRegistry` to look up the `Codec` for that Java type. |
| 145 | + |
| 146 | +Finally, we create a `CodecRegistry` instance |
| 147 | + |
| 148 | +```java |
| 149 | + CodecRegistry defaultCodecRegistry = ... |
| 150 | + DocumentCodecProvider documentCodecProvider = ... |
| 151 | + Codec<Instant> instantCodec = ... |
| 152 | + codecRegistry = CodecRegistries.fromRegistries(CodecRegistries.fromCodecs(instantCodec), |
| 153 | + CodecRegistries.fromProviders(documentCodecProvider), |
| 154 | + defaultCodecRegistry); |
| 155 | +``` |
| 156 | + |
| 157 | +using two additional static factory methods from the `CodecRegistries` class: one that takes a list of `CodecProvider`s and one which |
| 158 | +takes a list of `CodecRegistry`s. |
| 159 | + |
| 160 | + |
| 161 | + |
0 commit comments