]> git.basschouten.com Git - openhab-addons.git/blob
6d0a28610c1db4ed192a94400e97c592538c68e1
[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     private static final Logger logger = LoggerFactory.getLogger(BoschSHCServiceState.class);
36
37     /**
38      * State type. Initialized when instance is created.
39      */
40     private @Nullable String stateType = null;
41
42     @SerializedName("@type")
43     public final String type;
44
45     protected BoschSHCServiceState(String type) {
46         this.type = type;
47
48         if (stateType == null) {
49             stateType = type;
50         }
51     }
52
53     public String getType() {
54         return type;
55     }
56
57     protected boolean isValid() {
58         String expectedType = stateType;
59         if (expectedType == null || !expectedType.equals(this.type)) {
60             var className = this.getClass().getName();
61             logger.debug("Expected state type {} for state class {}, received {}", expectedType, className, this.type);
62             return false;
63         }
64
65         return true;
66     }
67
68     public static <TState extends BoschSHCServiceState> @Nullable TState fromJson(String json,
69             Class<TState> stateClass) {
70         var state = gson.fromJson(json, stateClass);
71         if (state == null || !state.isValid()) {
72             return null;
73         }
74
75         return state;
76     }
77
78     public static <TState extends BoschSHCServiceState> @Nullable TState fromJson(JsonElement json,
79             Class<TState> stateClass) {
80         var state = gson.fromJson(json, stateClass);
81         if (state == null || !state.isValid()) {
82             return null;
83         }
84
85         return state;
86     }
87 }