]> git.basschouten.com Git - openhab-addons.git/blob
60856fc8d961c216d83c429b88897e22cfd5f44f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.netatmo.internal.deserialization;
14
15 import java.io.IOException;
16 import java.io.StringReader;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20
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;
27
28 /**
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.
31  *
32  * @author GaĆ«l L'hopital - Initial contribution
33  */
34 @NonNullByDefault
35 class StrictEnumTypeAdapterFactory implements TypeAdapterFactory {
36     private static final StringReader UNKNOWN = new StringReader("\"UNKNOWN\"");
37
38     @Override
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;
44     }
45
46     private <T> TypeAdapter<T> newStrictEnumAdapter(@NonNullByDefault({}) TypeAdapter<T> delegateAdapter) {
47         return new TypeAdapter<T>() {
48             @Override
49             public void write(JsonWriter out, @Nullable T value) throws IOException {
50                 delegateAdapter.write(out, value);
51             }
52
53             @Override
54             public @Nullable T read(JsonReader in) throws IOException {
55                 JsonReader delegateReader = new JsonReader(new StringReader('"' + in.nextString() + '"'));
56                 @Nullable
57                 T value = delegateAdapter.read(delegateReader);
58                 delegateReader.close();
59                 if (value == null) {
60                     UNKNOWN.reset();
61                     value = delegateAdapter.read(new JsonReader(UNKNOWN));
62                 }
63                 return value;
64             }
65         };
66     }
67 }