View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.kryo;
15  
16  import com.esotericsoftware.kryo.kryo5.Kryo;
17  import com.esotericsoftware.kryo.kryo5.Serializer;
18  import com.esotericsoftware.kryo.kryo5.io.Input;
19  import com.esotericsoftware.kryo.kryo5.io.Output;
20  import org.slf4j.event.KeyValuePair;
21  
22  /**
23   * V5 serializer for a single {@link KeyValuePair}.
24   *
25   * <p>Keys use {@link BasicStringSerializer} (short repeating names, id cache).
26   * String values use the caller-supplied codec, typically the same
27   * {@link MultiEventCompressedStringSerializer} as the event message so there is one deflate stream.
28   */
29  public class KeyValuePairSerializerV5 extends Serializer<KeyValuePair> {
30  
31      private final Serializer<String> keySerializer;
32      private final Serializer<String> valueStringSerializer;
33  
34      public KeyValuePairSerializerV5(int stringCapacity) {
35          this(new BasicStringSerializer(stringCapacity), new MultiEventCompressedStringSerializer(stringCapacity));
36      }
37  
38      public KeyValuePairSerializerV5(Serializer<String> keySerializer,
39                                      Serializer<String> valueStringSerializer) {
40          if (keySerializer == null || valueStringSerializer == null) {
41              throw new IllegalArgumentException("key and value string serializers cannot be null");
42          }
43          this.keySerializer = keySerializer;
44          this.valueStringSerializer = valueStringSerializer;
45          setAcceptsNull(false);
46      }
47  
48      @Override
49      public void write(Kryo kryo, Output output, KeyValuePair keyValuePair) {
50          kryo.writeObject(output, keyValuePair.key, keySerializer);
51          SafeObjectCodec.write(kryo, output, valueStringSerializer, keyValuePair.value);
52      }
53  
54      @Override
55      public KeyValuePair read(Kryo kryo, Input input, Class<? extends KeyValuePair> type) {
56          String key = kryo.readObject(input, String.class, keySerializer);
57          Object value = SafeObjectCodec.read(kryo, input, valueStringSerializer);
58          return new KeyValuePair(key, value);
59      }
60  }