2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.freeboxos.internal.api.deserialization;
15 import java.io.IOException;
16 import java.io.StringReader;
17 import java.util.Objects;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
23 import com.google.gson.Gson;
24 import com.google.gson.TypeAdapter;
25 import com.google.gson.TypeAdapterFactory;
26 import com.google.gson.reflect.TypeToken;
27 import com.google.gson.stream.JsonReader;
28 import com.google.gson.stream.JsonWriter;
31 * Enforces a fallback to UNKNOWN when deserializing enum types, marked as @NonNull whereas they were valued
32 * to null if the appropriate value is absent.
34 * @author Gaƫl L'hopital - Initial contribution
37 public class StrictEnumTypeAdapterFactory implements TypeAdapterFactory {
38 private static final StringReader UNKNOWN = new StringReader("\"UNKNOWN\"");
41 public @Nullable <T> TypeAdapter<T> create(@NonNullByDefault({}) Gson gson,
42 @NonNullByDefault({}) TypeToken<T> type) {
43 @SuppressWarnings("unchecked")
44 Class<T> rawType = (Class<T>) type.getRawType();
45 return rawType.isEnum() ? newStrictEnumAdapter(gson.getDelegateAdapter(this, type)) : null;
48 private <T> TypeAdapter<T> newStrictEnumAdapter(TypeAdapter<T> delegateAdapter) {
49 return new TypeAdapter<T>() {
51 public void write(JsonWriter out, @Nullable T value) throws IOException {
52 delegateAdapter.write(out, value);
56 public @NonNull T read(JsonReader in) throws IOException {
57 String searched = in.nextString().toUpperCase().replace("/", "_").replace("-", "_");
58 JsonReader delegateReader = new JsonReader(new StringReader('"' + searched + '"'));
60 T value = delegateAdapter.read(delegateReader);
61 delegateReader.close();
64 value = delegateAdapter.read(new JsonReader(UNKNOWN));
66 return Objects.requireNonNull(value);