]> git.basschouten.com Git - openhab-addons.git/blob
2503eb964e0755b045ddd4f9652c9c34bb9300c4
[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.sleepiq.internal.api.impl.typeadapters;
14
15 import java.io.IOException;
16 import java.util.Objects;
17 import java.util.function.Function;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21
22 import com.google.gson.TypeAdapter;
23 import com.google.gson.stream.JsonReader;
24 import com.google.gson.stream.JsonToken;
25 import com.google.gson.stream.JsonWriter;
26
27 /**
28  * Abstract type adapter for jsr310 date-time types.
29  *
30  * @author Christophe Bornet - Initial contribution
31  */
32 @NonNullByDefault
33 abstract class TemporalTypeAdapter<T> extends TypeAdapter<T> {
34
35     Function<String, T> parseFunction;
36
37     TemporalTypeAdapter(Function<String, T> parseFunction) {
38         Objects.requireNonNull(parseFunction);
39         this.parseFunction = parseFunction;
40     }
41
42     @Override
43     public void write(JsonWriter out, @Nullable T value) throws IOException {
44         if (value == null) {
45             out.nullValue();
46         } else {
47             out.value(value.toString());
48         }
49     }
50
51     @Override
52     public @Nullable T read(JsonReader in) throws IOException {
53         if (in.peek() == JsonToken.NULL) {
54             in.nextNull();
55             return null;
56         }
57         String temporalString = preProcess(in.nextString());
58         return parseFunction.apply(temporalString);
59     }
60
61     public String preProcess(String in) {
62         return in;
63     }
64 }