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 java.util.Objects;
17  
18  /**
19   * Restricts objects to types that are cheap and safe to serialize (strings and
20   * primitive wrappers). Anything else is reduced via {@link Object#toString()}.
21   * Used for KVP values and similar free-form fields before Kryo encoding.
22   */
23  public class SafeObjectTransformer {
24  
25      /** Sentinel written in place of a null when a non-null object is required. */
26      final public static String NULL_PROXY = "0<|null|>1";
27  
28      /**
29       * Like {@link #asAllowedObject(Object)}, but maps {@code null} to {@link #NULL_PROXY}.
30       */
31      static Object asAllowedNonNullObject(Object o) {
32          if (o == null)
33              return NULL_PROXY;
34  
35          return asAllowedObject(o);
36      }
37  
38      /**
39       * {@code true} if {@code o} can be written by {@link SafeObjectCodec} without
40       * {@link Object#toString()}. {@code o} must not be null.
41       */
42      static boolean isAllowedType(Object o) {
43          return o instanceof String
44                  || o instanceof Integer
45                  || o instanceof Long
46                  || o instanceof Float
47                  || o instanceof Double
48                  || o instanceof Short;
49      }
50  
51      /**
52       * Returns {@code o} if it is a {@link String} or a numeric wrapper; otherwise
53       * {@code o.toString()}. {@code o} must not be null.
54       */
55      static Object asAllowedObject(Object o) {
56          Objects.requireNonNull(o);
57          if (isAllowedType(o)) {
58              return o;
59          }
60          return o.toString();
61      }
62  }