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.lametrictime.internal.api.common.impl.typeadapters;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.Map.Entry;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.binding.lametrictime.internal.api.common.impl.typeadapters.imported.CustomizedTypeAdapterFactory;
22 import org.openhab.binding.lametrictime.internal.api.local.dto.Action;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonObject;
28 * Adapter factory for actions.
30 * @author Gregory Moyer - Initial contribution
33 public class ActionTypeAdapterFactory extends CustomizedTypeAdapterFactory<Action> {
34 private static final String PROPERTY_ID = "id";
35 private static final String PROPERTY_PARAMETERS = "params";
37 public ActionTypeAdapterFactory() {
42 protected void beforeWrite(Action source, JsonElement toSerialize) {
43 if (toSerialize == null || toSerialize.isJsonNull()) {
47 JsonObject actionObj = toSerialize.getAsJsonObject();
48 if (actionObj == null || actionObj.isJsonNull()) {
52 // rewrite parameters from a nested object (map) to properties on the action
53 JsonElement paramsElem = actionObj.get(PROPERTY_PARAMETERS);
54 if (paramsElem != null && !paramsElem.isJsonNull()) {
55 JsonObject paramsObj = paramsElem.getAsJsonObject();
56 actionObj.remove(PROPERTY_PARAMETERS);
58 for (Entry<String, JsonElement> entry : paramsObj.entrySet()) {
59 actionObj.add(entry.getKey(), entry.getValue());
65 protected void afterRead(@Nullable JsonElement deserialized) {
66 if (deserialized == null || deserialized.isJsonNull()) {
70 JsonObject actionObj = deserialized.getAsJsonObject();
71 if (actionObj == null || actionObj.isJsonNull()) {
75 if (actionObj.has(PROPERTY_PARAMETERS)) {
76 throw new IllegalArgumentException(
77 "Attempting to deserialize Action that contains a colliding " + PROPERTY_PARAMETERS + " property");
80 // temporary list of field names
81 List<String> fields = new ArrayList<>();
83 // rewrite parameters to a nested object (map)
84 JsonObject paramsObj = new JsonObject();
85 for (Entry<String, JsonElement> entry : actionObj.entrySet()) {
87 if (PROPERTY_ID.equals(entry.getKey())) {
91 String paramId = entry.getKey();
92 fields.add(paramId); // to be removed later
94 paramsObj.add(paramId, entry.getValue());
96 actionObj.add(PROPERTY_PARAMETERS, paramsObj);
98 // remove all fields other than the list
99 fields.forEach(field -> actionObj.remove(field));