]> git.basschouten.com Git - openhab-addons.git/blob
862601a6d3587e288f93ea53757029a71fa23f4d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.mqtt.homeassistant.internal.config;
14
15 import java.io.IOException;
16 import java.lang.reflect.Field;
17 import java.util.Arrays;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.binding.mqtt.homeassistant.internal.MappingJsonReader;
22 import org.openhab.binding.mqtt.homeassistant.internal.config.dto.AbstractChannelConfiguration;
23 import org.openhab.binding.mqtt.homeassistant.internal.config.dto.Device;
24
25 import com.google.gson.Gson;
26 import com.google.gson.TypeAdapter;
27 import com.google.gson.TypeAdapterFactory;
28 import com.google.gson.annotations.SerializedName;
29 import com.google.gson.reflect.TypeToken;
30 import com.google.gson.stream.JsonReader;
31 import com.google.gson.stream.JsonWriter;
32
33 /**
34  * This a Gson type adapter factory.
35  *
36  * <p>
37  * It will create a type adapter for every class derived from {@link
38  * AbstractChannelConfiguration} and ensures,
39  * that abbreviated names are replaces with their long versions during the read.
40  *
41  * <p>
42  * In elements, whose JSON name end in'_topic' '~' replacement is performed.
43  *
44  * <p>
45  * The adapters also handle {@link Device}
46  *
47  * @author Jochen Klein - Initial contribution
48  */
49 @NonNullByDefault
50 public class ChannelConfigurationTypeAdapterFactory implements TypeAdapterFactory {
51     private static final String MQTT_TOPIC_FIELD_SUFFIX = "_topic";
52
53     @Override
54     @Nullable
55     public <T> TypeAdapter<T> create(@Nullable Gson gson, @Nullable TypeToken<T> type) {
56         if (gson == null || type == null) {
57             return null;
58         }
59         if (AbstractChannelConfiguration.class.isAssignableFrom(type.getRawType())) {
60             return createHAConfig(gson, type);
61         }
62         if (Device.class.isAssignableFrom(type.getRawType())) {
63             return createHADevice(gson, type);
64         }
65         return null;
66     }
67
68     /**
69      * Handle {@link
70      * AbstractChannelConfiguration}
71      *
72      * @param gson parser
73      * @param type type
74      * @return adapter
75      */
76     private <T> TypeAdapter<T> createHAConfig(Gson gson, TypeToken<T> type) {
77         /* The delegate is the 'default' adapter */
78         final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
79
80         return new TypeAdapter<T>() {
81             @Override
82             public @Nullable T read(JsonReader in) throws IOException {
83                 /* read the object using the default adapter, but translate the names in the reader */
84                 T result = delegate.read(MappingJsonReader.getConfigMapper(in));
85                 /* do the '~' expansion afterwards */
86                 expandTidleInTopics(AbstractChannelConfiguration.class.cast(result));
87                 return result;
88             }
89
90             @Override
91             public void write(JsonWriter out, @Nullable T value) throws IOException {
92                 delegate.write(out, value);
93             }
94         };
95     }
96
97     private <T> TypeAdapter<T> createHADevice(Gson gson, TypeToken<T> type) {
98         /* The delegate is the 'default' adapter */
99         final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
100
101         return new TypeAdapter<T>() {
102             @Override
103             public @Nullable T read(JsonReader in) throws IOException {
104                 /* read the object using the default adapter, but translate the names in the reader */
105                 T result = delegate.read(MappingJsonReader.getDeviceMapper(in));
106                 return result;
107             }
108
109             @Override
110             public void write(JsonWriter out, @Nullable T value) throws IOException {
111                 delegate.write(out, value);
112             }
113         };
114     }
115
116     private void expandTidleInTopics(AbstractChannelConfiguration config) {
117         Class<?> type = config.getClass();
118
119         String parentTopic = config.getParentTopic();
120
121         while (type != Object.class) {
122             Arrays.stream(type.getDeclaredFields()).filter(this::isMqttTopicField)
123                     .forEach(field -> replacePlaceholderByParentTopic(config, field, parentTopic));
124             type = type.getSuperclass();
125         }
126     }
127
128     private boolean isMqttTopicField(Field field) {
129         if (String.class.isAssignableFrom(field.getType())) {
130             final var serializedNameAnnotation = field.getAnnotation(SerializedName.class);
131             if (serializedNameAnnotation != null && serializedNameAnnotation.value() != null
132                     && serializedNameAnnotation.value().endsWith(MQTT_TOPIC_FIELD_SUFFIX)) {
133                 return true;
134             }
135         }
136         return false;
137     }
138
139     private void replacePlaceholderByParentTopic(AbstractChannelConfiguration config, Field field, String parentTopic) {
140         field.setAccessible(true);
141
142         try {
143             final String oldValue = (String) field.get(config);
144
145             String newValue = oldValue;
146             if (oldValue != null && !oldValue.isBlank()) {
147                 if (oldValue.charAt(0) == AbstractChannelConfiguration.PARENT_TOPIC_PLACEHOLDER) {
148                     newValue = parentTopic + oldValue.substring(1);
149                 } else if (oldValue
150                         .charAt(oldValue.length() - 1) == AbstractChannelConfiguration.PARENT_TOPIC_PLACEHOLDER) {
151                     newValue = oldValue.substring(0, oldValue.length() - 1) + parentTopic;
152                 }
153             }
154
155             field.set(config, newValue);
156         } catch (IllegalArgumentException | IllegalAccessException e) {
157             throw new RuntimeException(e);
158         }
159     }
160 }