]> git.basschouten.com Git - openhab-addons.git/blob
3c881fcb5e678e5ee295ba557f01c0b65ddde848
[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.freeboxos.internal.api.deserialization;
14
15 import java.io.IOException;
16 import java.io.StringReader;
17 import java.util.Objects;
18
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22
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;
29
30 /**
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.
33  *
34  * @author GaĆ«l L'hopital - Initial contribution
35  */
36 @NonNullByDefault
37 public class StrictEnumTypeAdapterFactory implements TypeAdapterFactory {
38     private static final StringReader UNKNOWN = new StringReader("\"UNKNOWN\"");
39
40     @Override
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;
46     }
47
48     private <T> TypeAdapter<T> newStrictEnumAdapter(TypeAdapter<T> delegateAdapter) {
49         return new TypeAdapter<T>() {
50             @Override
51             public void write(JsonWriter out, @Nullable T value) throws IOException {
52                 delegateAdapter.write(out, value);
53             }
54
55             @Override
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 + '"'));
59                 @Nullable
60                 T value = delegateAdapter.read(delegateReader);
61                 delegateReader.close();
62                 if (value == null) {
63                     UNKNOWN.reset();
64                     value = delegateAdapter.read(new JsonReader(UNKNOWN));
65                 }
66                 return Objects.requireNonNull(value);
67             }
68         };
69     }
70 }