cb67590f7ea53a77269b0164e820718cc7f0b40a
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.model.basicmodel.handling;
22
23 import com.google.gson.JsonArray;
24 import com.google.gson.JsonDeserializationContext;
25 import com.google.gson.JsonDeserializer;
26 import com.google.gson.JsonElement;
27 import com.google.gson.JsonObject;
28 import com.google.gson.JsonParseException;
29 import com.google.gson.JsonSerializationContext;
30 import com.google.gson.JsonSerializer;
31 import java.lang.reflect.ParameterizedType;
32 import java.lang.reflect.Type;
33 import java.util.AbstractMap;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.TreeMap;
37 import java.util.stream.Collectors;
38 import java.util.stream.StreamSupport;
39
40 @SuppressWarnings("rawtypes")
41 public class ApexModelCustomGsonMapAdapter implements JsonSerializer<Map>, JsonDeserializer<Map> {
42     private static final String MAP_ENTRY_KEY = "entry";
43
44     @SuppressWarnings("unchecked")
45     @Override
46     public Map deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context)
47         throws JsonParseException {
48
49         if (!(jsonElement instanceof JsonObject)) {
50             throw new JsonParseException("could not parse JSON map, map is not a JsonObject");
51         }
52
53         JsonObject jsonObject = (JsonObject) jsonElement;
54
55         if (jsonObject.size() != 1) {
56             throw new JsonParseException("could not parse JSON map, map must be in a JsonObject with a single member");
57         }
58
59         JsonArray mapEntryArray = (JsonArray) jsonObject.get(MAP_ENTRY_KEY);
60         if (mapEntryArray == null) {
61             throw new JsonParseException("could not parse JSON map, map \"entry\" in JsonObject not found");
62         }
63
64         return new TreeMap(
65             StreamSupport
66                 .stream(mapEntryArray.spliterator(), true)
67                 .map(element -> deserializeMapEntry(element, typeOfT, context))
68                 .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()))
69         );
70     }
71
72     @Override
73     public JsonElement serialize(Map sourceMap, Type typeOfSrc, JsonSerializationContext context) {
74
75         // A map is stored in a JsonArray
76         JsonArray mapEntryArray = new JsonArray();
77
78         for (Object mapEntryObject : sourceMap.entrySet()) {
79             Entry mapEntry = (Entry) mapEntryObject;
80             mapEntryArray.add(serializeMapEntry(mapEntry, typeOfSrc, context));
81         }
82
83         JsonObject returnObject = new JsonObject();
84         returnObject.add(MAP_ENTRY_KEY, mapEntryArray);
85
86         return returnObject;
87     }
88
89     @SuppressWarnings("unchecked")
90     private static Entry deserializeMapEntry(JsonElement element, Type typeOfT, JsonDeserializationContext context) {
91         // Get the types of the map
92         ParameterizedType pt = (ParameterizedType) typeOfT;
93
94         // Type of the key and value of the map
95         Type keyType = pt.getActualTypeArguments()[0];
96         Type valueType = pt.getActualTypeArguments()[1];
97
98         // Deserialize the key and value
99         return new AbstractMap.SimpleEntry(
100             context.deserialize(element.getAsJsonObject().get("key"), keyType),
101             context.deserialize(element.getAsJsonObject().get("value"), valueType));
102     }
103
104     private static JsonElement serializeMapEntry(Entry sourceEntry, Type typeOfSrc, JsonSerializationContext context) {
105         // Get the types of the map
106         ParameterizedType pt = (ParameterizedType) typeOfSrc;
107
108         // Type of the key and value of the map
109         Type keyType = pt.getActualTypeArguments()[0];
110         Type valueType = pt.getActualTypeArguments()[1];
111
112         JsonObject entryObject = new JsonObject();
113         entryObject.add("key", context.serialize(sourceEntry.getKey(), keyType));
114         entryObject.add("value", context.serialize(sourceEntry.getValue(), valueType));
115
116         return entryObject;
117     }
118 }