Restructure for authorative models
[policy/models.git] / models-tosca / src / main / java / org / onap / policy / models / tosca / simple / serialization / ToscaPolicyJsonAdapter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.models.tosca.simple.serialization;
23
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonDeserializationContext;
27 import com.google.gson.JsonDeserializer;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonObject;
30 import com.google.gson.JsonSerializationContext;
31 import com.google.gson.JsonSerializer;
32
33 import java.lang.reflect.Type;
34 import java.util.HashMap;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import javax.ws.rs.core.Response;
38
39 import lombok.NonNull;
40
41 import org.onap.policy.models.base.PfConceptKey;
42 import org.onap.policy.models.base.PfModelRuntimeException;
43 import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * GSON type adapter for TOSCA policies.
49  *
50  * @author Liam Fallon (liam.fallon@est.tech)
51  * @author Chenfei Gao (cgao@research.att.com)
52  */
53 public class ToscaPolicyJsonAdapter implements JsonSerializer<JpaToscaPolicy>, JsonDeserializer<JpaToscaPolicy> {
54     // Logger for this class
55     private static final Logger LOGGER = LoggerFactory.getLogger(ToscaPolicyJsonAdapter.class);
56
57     private static final String TYPE = "type";
58     private static final String DESCRIPTION = "description";
59     private static final String VERSION = "version";
60     private static final String METADATA = "metadata";
61     private static final String PROPERTIES = "properties";
62
63     private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
64
65     @Override
66     public JpaToscaPolicy deserialize(@NonNull final JsonElement policyElement, @NonNull final Type type,
67             @NonNull final JsonDeserializationContext context) {
68
69         // The incoming JSON
70         final JsonObject policyJsonMapObject = policyElement.getAsJsonObject();
71
72         // We should only have a single entry for the policy
73         if (policyJsonMapObject.entrySet().size() != 1) {
74             String errorMessage = "a policy list entry may only contain one and only one policy";
75             LOGGER.debug(errorMessage);
76             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
77         }
78
79         final String policyName = policyJsonMapObject.entrySet().iterator().next().getKey();
80         final JsonObject policyJsonObject = policyJsonMapObject.entrySet().iterator().next()
81                                             .getValue().getAsJsonObject();
82
83         // Set keys
84         PfConceptKey policyKey = new PfConceptKey(policyName, policyJsonObject.get(VERSION).getAsString());
85         PfConceptKey policyTypeKey = new PfConceptKey(
86                 policyJsonObject.get(TYPE).getAsString(),
87                 policyJsonObject.get(VERSION).getAsString());
88         JpaToscaPolicy policy = new JpaToscaPolicy(policyKey, policyTypeKey);
89
90         // Set description
91         if (policyJsonObject.has(DESCRIPTION)) {
92             final String policyDescription = policyJsonObject.get(DESCRIPTION).getAsString();
93             policy.setDescription(policyDescription);
94         }
95
96         // Set metadata
97         if (policyJsonObject.has(METADATA)) {
98             final JsonObject policyMetadataMapObject = policyJsonObject.get(METADATA).getAsJsonObject();
99             Map<String, String> policyMetadataMap = new HashMap<>();
100             for (Entry<String, JsonElement> entry : policyMetadataMapObject.entrySet()) {
101                 policyMetadataMap.put(entry.getKey(), entry.getValue().getAsString());
102             }
103             policy.setMetadata(policyMetadataMap);
104         }
105
106         // Set properties
107         if (policyJsonObject.has(PROPERTIES)) {
108             final JsonObject policyPropertiesMapObject = policyJsonObject.get(PROPERTIES).getAsJsonObject();
109             Map<String, String> propertiesMap = new HashMap<>();
110             for (Entry<String, JsonElement> entry : policyPropertiesMapObject.entrySet()) {
111                 // TODO: This is a HACK, we need to validate the properties against their
112                 // TODO: their data type in their policy type definition in TOSCA, which means reading
113                 // TODO: the policy type from the database and parsing the property value object correctly
114                 // TODO: Here we are simply serializing the property value into a string and storing it
115                 // TODO: unvalidated into the database
116                 propertiesMap.put(entry.getKey(), gson.toJson(entry.getValue()));
117             }
118             policy.setProperties(propertiesMap);
119         }
120         return policy;
121     }
122
123     @Override
124     public JsonElement serialize(@NonNull final JpaToscaPolicy policy, @NonNull final Type type,
125             @NonNull final JsonSerializationContext context) {
126
127         JsonObject policyValJsonObject = new JsonObject();
128
129         // Add type
130         policyValJsonObject.addProperty(TYPE, policy.getType().getName());
131
132         // Add version
133         policyValJsonObject.addProperty(VERSION, policy.getType().getVersion());
134
135         // Add description
136         if (policy.getDescription() != null) {
137             policyValJsonObject.addProperty(DESCRIPTION, policy.getDescription());
138         }
139
140         // Add metadata
141         if (policy.getMetadata() != null) {
142             JsonObject metadataMapObject = new JsonObject();
143             for (Entry<String, String> entry : policy.getMetadata().entrySet()) {
144                 metadataMapObject.addProperty(entry.getKey(), entry.getValue());
145             }
146             policyValJsonObject.add(METADATA, metadataMapObject);
147         }
148
149         // Add properties
150         if (policy.getProperties() != null) {
151             JsonObject propertiesMapObject = new JsonObject();
152             for (Entry<String, String> entry : policy.getProperties().entrySet()) {
153                 // TODO: This is the other direction of the HACK
154                 JsonElement valueObject = gson.fromJson(entry.getValue(), JsonElement.class);
155                 propertiesMapObject.add(entry.getKey(), valueObject);
156             }
157             policyValJsonObject.add(PROPERTIES, propertiesMapObject);
158         }
159
160         JsonObject policyJsonObject = new JsonObject();
161         policyJsonObject.add(policy.getKey().getName(), policyValJsonObject);
162         return policyJsonObject;
163     }
164 }