]> git.basschouten.com Git - openhab-addons.git/blob
ffe23619dc425fea356e5e4f01d24b6d6064ea2a
[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.boschshc.internal.services.dto;
14
15 import org.eclipse.jdt.annotation.Nullable;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 import com.google.gson.Gson;
20 import com.google.gson.JsonElement;
21 import com.google.gson.annotations.SerializedName;
22
23 /**
24  * Base Bosch Smart Home Controller service state.
25  *
26  * @author Christian Oeing - Initial contribution
27  */
28 public class BoschSHCServiceState {
29
30     /**
31      * gson instance to convert a class to json string and back.
32      */
33     private static final Gson GSON = new Gson();
34
35     /**
36      * Logger marked as transient to exclude the logger from JSON serialization.
37      */
38     private final transient Logger logger = LoggerFactory.getLogger(BoschSHCServiceState.class);
39
40     /**
41      * State type. Initialized when instance is created.
42      */
43     private @Nullable String stateType = null;
44
45     @SerializedName("@type")
46     public final String type;
47
48     protected BoschSHCServiceState(String type) {
49         this.type = type;
50
51         if (stateType == null) {
52             stateType = type;
53         }
54     }
55
56     public String getType() {
57         return type;
58     }
59
60     protected boolean isValid() {
61         String expectedType = stateType;
62         if (expectedType == null || !expectedType.equals(this.type)) {
63             var className = this.getClass().getName();
64             logger.debug("Expected state type {} for state class {}, received {}", expectedType, className, this.type);
65             return false;
66         }
67
68         return true;
69     }
70
71     public static <TState extends BoschSHCServiceState> @Nullable TState fromJson(String json,
72             Class<TState> stateClass) {
73         var state = GSON.fromJson(json, stateClass);
74         if (state == null || !state.isValid()) {
75             return null;
76         }
77
78         return state;
79     }
80
81     public static <TState extends BoschSHCServiceState> @Nullable TState fromJson(JsonElement json,
82             Class<TState> stateClass) {
83         var state = GSON.fromJson(json, stateClass);
84         if (state == null || !state.isValid()) {
85             return null;
86         }
87
88         return state;
89     }
90 }