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