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