1+ package net .lightcode .redis .codec ;
2+
3+ import com .fasterxml .jackson .annotation .JsonAutoDetect ;
4+ import com .fasterxml .jackson .annotation .JsonInclude ;
5+ import com .fasterxml .jackson .core .JsonGenerator ;
6+ import com .fasterxml .jackson .core .JsonProcessingException ;
7+ import com .fasterxml .jackson .databind .DeserializationFeature ;
8+ import com .fasterxml .jackson .databind .MapperFeature ;
9+ import com .fasterxml .jackson .databind .ObjectMapper ;
10+ import com .fasterxml .jackson .databind .SerializationFeature ;
11+ import io .lettuce .core .codec .RedisCodec ;
12+ import net .lightcode .packet .Packet ;
13+ import org .msgpack .jackson .dataformat .MessagePackFactory ;
14+
15+ import java .io .IOException ;
16+ import java .nio .ByteBuffer ;
17+ import java .nio .charset .Charset ;
18+ import java .nio .charset .StandardCharsets ;
19+
20+ public class MessagePackCodec implements RedisCodec <String , Packet > {
21+
22+ private final Charset charset = StandardCharsets .UTF_8 ;
23+
24+ private final ObjectMapper objectMapper ;
25+
26+ public MessagePackCodec () {
27+ this .objectMapper = new ObjectMapper (new MessagePackFactory ());
28+
29+ this .objectMapper .setSerializationInclusion (JsonInclude .Include .NON_NULL );
30+ this .objectMapper .setVisibility (
31+ this .objectMapper
32+ .getSerializationConfig ()
33+ .getDefaultVisibilityChecker ()
34+ .withFieldVisibility (JsonAutoDetect .Visibility .ANY )
35+ .withGetterVisibility (JsonAutoDetect .Visibility .NONE )
36+ .withSetterVisibility (JsonAutoDetect .Visibility .NONE )
37+ .withCreatorVisibility (JsonAutoDetect .Visibility .NONE ));
38+ this .objectMapper
39+ .disable (DeserializationFeature .FAIL_ON_UNKNOWN_PROPERTIES )
40+ .enable (JsonGenerator .Feature .WRITE_BIGDECIMAL_AS_PLAIN )
41+ .disable (SerializationFeature .FAIL_ON_EMPTY_BEANS )
42+ .enable (MapperFeature .SORT_PROPERTIES_ALPHABETICALLY );
43+
44+ this .objectMapper .registerSubtypes (Packet .class );
45+ }
46+
47+ @ Override
48+ public String decodeKey (ByteBuffer bytes ) {
49+ return charset .decode (bytes ).toString ();
50+ }
51+
52+ @ Override
53+ public Packet decodeValue (ByteBuffer bytes ) {
54+ byte [] buffer = new byte [bytes .remaining ()];
55+ bytes .get (buffer );
56+
57+ try {
58+ return this .objectMapper .readValue (buffer , Packet .class );
59+ } catch (IOException exception ) {
60+ throw new RuntimeException (exception );
61+ }
62+ }
63+
64+ @ Override
65+ public ByteBuffer encodeKey (String key ) {
66+ return charset .encode (key );
67+ }
68+
69+ @ Override
70+ public ByteBuffer encodeValue (Packet value ) {
71+ try {
72+ return ByteBuffer .wrap (this .objectMapper .writeValueAsBytes (value ));
73+ } catch (JsonProcessingException exception ) {
74+ throw new RuntimeException (exception );
75+ }
76+ }
77+ }
0 commit comments