]> git.basschouten.com Git - openhab-addons.git/blob
b6bd525fc0e9014f83492264bfa3d62c52536d03
[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.lametrictime.internal.api.common.impl.typeadapters;
14
15 import java.util.Map.Entry;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.binding.lametrictime.internal.api.common.impl.typeadapters.imported.CustomizedTypeAdapterFactory;
20 import org.openhab.binding.lametrictime.internal.api.local.dto.UpdateAction;
21
22 import com.google.gson.JsonElement;
23 import com.google.gson.JsonObject;
24
25 /**
26  * Adapter factory for update actions.
27  *
28  * @author Gregory Moyer - Initial contribution
29  */
30 @NonNullByDefault
31 public class UpdateActionTypeAdapterFactory extends CustomizedTypeAdapterFactory<UpdateAction> {
32     private static final String PROPERTY_PARAMETERS = "params";
33     private static final String PROPERTY_VALUE = "value";
34
35     public UpdateActionTypeAdapterFactory() {
36         super(UpdateAction.class);
37     }
38
39     @Override
40     protected void beforeWrite(UpdateAction source, JsonElement toSerialize) {
41         if (toSerialize == null || toSerialize.isJsonNull()) {
42             return;
43         }
44
45         JsonObject actionObj = toSerialize.getAsJsonObject();
46         if (actionObj == null || actionObj.isJsonNull()) {
47             return;
48         }
49
50         // rewrite parameters map from {name => Parameter} to {name => value}
51         JsonElement paramsElem = actionObj.get(PROPERTY_PARAMETERS);
52         if (paramsElem != null && !paramsElem.isJsonNull()) {
53             JsonObject paramsObj = paramsElem.getAsJsonObject();
54             actionObj.remove(PROPERTY_PARAMETERS);
55
56             JsonObject newParamsObj = new JsonObject();
57             for (Entry<String, JsonElement> entry : paramsObj.entrySet()) {
58                 newParamsObj.add(entry.getKey(), entry.getValue().getAsJsonObject().getAsJsonPrimitive(PROPERTY_VALUE));
59             }
60             actionObj.add(PROPERTY_PARAMETERS, newParamsObj);
61         }
62     }
63
64     @Override
65     protected void afterRead(@Nullable JsonElement deserialized) {
66         throw new UnsupportedOperationException(UpdateAction.class.getName() + " cannot be derialized");
67     }
68 }