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