]> git.basschouten.com Git - openhab-addons.git/blob
b70ee78f2868f8cdeb3bfe7dc9b45451f860a9e1
[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.persistence.mapdb.internal;
14
15 import java.io.IOException;
16 import java.util.List;
17
18 import org.openhab.core.types.State;
19 import org.openhab.core.types.TypeParser;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 import com.google.gson.TypeAdapter;
24 import com.google.gson.stream.JsonReader;
25 import com.google.gson.stream.JsonToken;
26 import com.google.gson.stream.JsonWriter;
27
28 /**
29  * A GSON TypeAdapter for openHAB State values.
30  *
31  * @author Martin Kühl - Initial contribution
32  */
33 public class StateTypeAdapter extends TypeAdapter<State> {
34     private static final String TYPE_SEPARATOR = "@@@";
35
36     private final Logger logger = LoggerFactory.getLogger(StateTypeAdapter.class);
37
38     @Override
39     public State read(JsonReader reader) throws IOException {
40         if (reader.peek() == JsonToken.NULL) {
41             reader.nextNull();
42             return null;
43         }
44         String value = reader.nextString();
45
46         try {
47             int index = value.indexOf(TYPE_SEPARATOR);
48             if (index == -1) {
49                 logger.warn("Couldn't deserialize state '{}': type separator '{}' not found", value, TYPE_SEPARATOR);
50                 return null;
51             }
52             String valueTypeName = value.substring(0, index);
53             String valueAsString = value.substring(index + TYPE_SEPARATOR.length());
54
55             @SuppressWarnings("unchecked")
56             Class<? extends State> valueType = (Class<? extends State>) Class.forName(valueTypeName);
57             return TypeParser.parseState(List.of(valueType), valueAsString);
58         } catch (Exception e) {
59             logger.warn("Couldn't deserialize state '{}': {}", value, e.getMessage());
60         }
61         return null;
62     }
63
64     @Override
65     public void write(JsonWriter writer, State state) throws IOException {
66         if (state == null) {
67             writer.nullValue();
68             return;
69         }
70         String value = state.getClass().getName() + TYPE_SEPARATOR + state.toFullString();
71         writer.value(value);
72     }
73 }