2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.boschshc.internal.services.dto;
15 import org.eclipse.jdt.annotation.Nullable;
16 import org.openhab.binding.boschshc.internal.serialization.GsonUtils;
17 import org.openhab.binding.boschshc.internal.services.userstate.dto.UserStateServiceState;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
21 import com.google.gson.JsonElement;
22 import com.google.gson.annotations.SerializedName;
25 * Base Bosch Smart Home Controller service state.
27 * @author Christian Oeing - Initial contribution
29 public class BoschSHCServiceState {
31 private final Logger logger = LoggerFactory.getLogger(getClass());
34 * State type. Initialized when instance is created.
36 private @Nullable String stateType = null;
38 @SerializedName("@type")
39 public final String type;
41 public BoschSHCServiceState(String type) {
44 if (stateType == null) {
49 public String getType() {
53 protected boolean isValid() {
54 String expectedType = stateType;
55 if (expectedType == null || !expectedType.equals(this.type)) {
56 var className = this.getClass().getName();
57 logger.debug("Expected state type {} for state class {}, received {}", expectedType, className, this.type);
64 public static <TState extends BoschSHCServiceState> @Nullable TState fromJson(String json,
65 Class<TState> stateClass) {
66 var state = getUserDefinedStateOrNull(json, stateClass);
67 if (state == null || !state.isValid()) {
68 state = GsonUtils.DEFAULT_GSON_INSTANCE.fromJson(json, stateClass);
69 if (state == null || !state.isValid()) {
77 public static <TState extends BoschSHCServiceState> @Nullable TState fromJson(JsonElement json,
78 Class<TState> stateClass) {
79 var state = getUserDefinedStateOrNull(json, stateClass);
80 if (state == null || !state.isValid()) {
81 state = GsonUtils.DEFAULT_GSON_INSTANCE.fromJson(json, stateClass);
82 if (state == null || !state.isValid()) {
89 private static <TState extends BoschSHCServiceState> TState getUserDefinedStateOrNull(JsonElement json,
90 Class<TState> stateClass) {
91 if (stateClass.isAssignableFrom(UserStateServiceState.class)) {
92 return BoschSHCServiceState.getUserDefinedStateOrNull(json.getAsString(), stateClass);
97 private static <TState extends BoschSHCServiceState> TState getUserDefinedStateOrNull(String json,
98 Class<TState> stateClass) {
99 if (stateClass.isAssignableFrom(UserStateServiceState.class)) {
100 var state = new UserStateServiceState();
101 state.setStateFromString(json);
102 return (TState) state;