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.netatmo.internal.deserialization;
15 import java.io.IOException;
16 import java.io.StringReader;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
21 import com.google.gson.Gson;
22 import com.google.gson.TypeAdapter;
23 import com.google.gson.TypeAdapterFactory;
24 import com.google.gson.reflect.TypeToken;
25 import com.google.gson.stream.JsonReader;
26 import com.google.gson.stream.JsonWriter;
29 * Enforces a fallback to UNKNOWN when deserializing enum types, marked as @NonNull whereas they were valued
30 * to null if the appropriate value is absent. It will give more resilience to the binding when Netatmo API evolves.
32 * @author Gaƫl L'hopital - Initial contribution
35 class StrictEnumTypeAdapterFactory implements TypeAdapterFactory {
36 private static final StringReader UNKNOWN = new StringReader("\"UNKNOWN\"");
39 public @Nullable <T> TypeAdapter<T> create(@NonNullByDefault({}) Gson gson,
40 @NonNullByDefault({}) TypeToken<T> type) {
41 @SuppressWarnings("unchecked")
42 Class<T> rawType = (Class<T>) type.getRawType();
43 return rawType.isEnum() ? newStrictEnumAdapter(gson.getDelegateAdapter(this, type)) : null;
46 private <T> TypeAdapter<T> newStrictEnumAdapter(@NonNullByDefault({}) TypeAdapter<T> delegateAdapter) {
47 return new TypeAdapter<T>() {
49 public void write(JsonWriter out, @Nullable T value) throws IOException {
50 delegateAdapter.write(out, value);
54 public @Nullable T read(JsonReader in) throws IOException {
55 JsonReader delegateReader = new JsonReader(new StringReader('"' + in.nextString() + '"'));
57 T value = delegateAdapter.read(delegateReader);
58 delegateReader.close();
61 value = delegateAdapter.read(new JsonReader(UNKNOWN));