57d13ef17d556155a9cc011d1fdd51eeb655bbd6
[clamp.git] / src / main / java / org / onap / clamp / policy / operational / OperationalPolicyRepresentationBuilder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * Modifications Copyright (C) 2020 Huawei Technologies Co., Ltd.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  * http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END============================================
21  * ===================================================================
22  *
23  */
24
25 package org.onap.clamp.policy.operational;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.google.gson.JsonArray;
30 import com.google.gson.JsonElement;
31 import com.google.gson.JsonObject;
32
33 import java.io.IOException;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Set;
37
38 import org.onap.clamp.clds.util.JsonUtils;
39 import org.onap.clamp.clds.util.ResourceFileUtil;
40 import org.onap.clamp.loop.service.Service;
41
42 public class OperationalPolicyRepresentationBuilder {
43
44     private static final EELFLogger logger =
45             EELFManager.getInstance().getLogger(OperationalPolicyRepresentationBuilder.class);
46
47     public static final String PROPERTIES = "properties";
48     public static final String TYPE = "type";
49     public static final String TYPE_LIST = "list";
50
51     /**
52      * This method generates the operational policy json representation that will be
53      * used by ui for rendering. It uses the model (VF and VFModule) defined in the
54      * loop object to do so, so it's dynamic. It also uses the operational policy
55      * schema template defined in the resource folder.
56      *
57      * @param modelJson The loop model json
58      * @return The json representation
59      */
60     public static JsonObject generateOperationalPolicySchema(Service modelJson) {
61
62         JsonObject jsonSchema = null;
63         try {
64             jsonSchema = JsonUtils.GSON.fromJson(
65                     ResourceFileUtil
66                             .getResourceAsString("clds/json-schema/operational_policies/operational_policy.json"),
67                     JsonObject.class);
68             jsonSchema.get("properties").getAsJsonObject()
69                     .get("operational_policy").getAsJsonObject().get("properties").getAsJsonObject().get("policies")
70                     .getAsJsonObject().get("items").getAsJsonObject().get("properties").getAsJsonObject().get("target")
71                     .getAsJsonObject().get("anyOf").getAsJsonArray().addAll(createAnyOfArray(modelJson, true));
72
73             // update CDS recipe and payload information to schema
74             JsonArray actors = jsonSchema.get("properties").getAsJsonObject()
75                     .get("operational_policy").getAsJsonObject().get("properties").getAsJsonObject().get("policies")
76                     .getAsJsonObject().get("items").getAsJsonObject().get("properties").getAsJsonObject().get("actor")
77                     .getAsJsonObject().get("anyOf").getAsJsonArray();
78
79             for (JsonElement actor : actors) {
80                 if ("CDS".equalsIgnoreCase(actor.getAsJsonObject().get("title").getAsString())) {
81                     actor.getAsJsonObject().get("properties").getAsJsonObject().get("recipe").getAsJsonObject()
82                             .get("anyOf").getAsJsonArray()
83                             .addAll(createAnyOfArrayForCdsRecipe(modelJson));
84                 }
85             }
86             return jsonSchema;
87         } catch (IOException e) {
88             logger.error("Unable to generate the json schema because of an exception", e);
89             return new JsonObject();
90         }
91     }
92
93     private static JsonObject createSchemaProperty(String title, String type, String defaultValue, String readOnlyFlag,
94                                                    String[] enumArray) {
95         JsonObject property = new JsonObject();
96         property.addProperty("title", title);
97         property.addProperty("type", type);
98         property.addProperty("default", defaultValue);
99         property.addProperty("readOnly", readOnlyFlag);
100
101         if (enumArray != null) {
102             JsonArray jsonArray = new JsonArray();
103             property.add("enum", jsonArray);
104             for (String val : enumArray) {
105                 jsonArray.add(val);
106             }
107         }
108         return property;
109     }
110
111     private static JsonArray createVnfSchema(Service modelService, boolean generateType) {
112         JsonArray vnfSchemaArray = new JsonArray();
113         JsonObject modelVnfs = modelService.getResourceByType("VF");
114
115         for (Entry<String, JsonElement> entry : modelVnfs.entrySet()) {
116             JsonObject vnfOneOfSchema = new JsonObject();
117             vnfOneOfSchema.addProperty("title", "VNF" + "-" + entry.getKey());
118             JsonObject properties = new JsonObject();
119             if (generateType) {
120                 properties.add("type", createSchemaProperty("Type", "string", "VNF", "True", null));
121             }
122             properties.add("resourceID", createSchemaProperty("Resource ID", "string",
123                     modelVnfs.get(entry.getKey()).getAsJsonObject().get("name").getAsString(), "True", null));
124
125             vnfOneOfSchema.add("properties", properties);
126             vnfSchemaArray.add(vnfOneOfSchema);
127         }
128         return vnfSchemaArray;
129     }
130
131     private static JsonArray createVfModuleSchema(Service modelService, boolean generateType) {
132         JsonArray vfModuleOneOfSchemaArray = new JsonArray();
133         JsonObject modelVfModules = modelService.getResourceByType("VFModule");
134
135         for (Entry<String, JsonElement> entry : modelVfModules.entrySet()) {
136             JsonObject vfModuleOneOfSchema = new JsonObject();
137             vfModuleOneOfSchema.addProperty("title", "VFMODULE" + "-" + entry.getKey());
138             JsonObject properties = new JsonObject();
139             if (generateType) {
140                 properties.add("type", createSchemaProperty("Type", "string", "VFMODULE", "True", null));
141             }
142             properties.add("resourceID",
143                     createSchemaProperty("Resource ID", "string",
144                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
145                             "True", null));
146             properties.add("modelInvariantId",
147                     createSchemaProperty("Model Invariant Id (ModelInvariantUUID)", "string",
148                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelInvariantUUID")
149                                     .getAsString(),
150                             "True", null));
151             properties.add("modelVersionId",
152                     createSchemaProperty("Model Version Id (ModelUUID)", "string",
153                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelUUID").getAsString(),
154                             "True", null));
155             properties.add("modelName",
156                     createSchemaProperty("Model Name", "string",
157                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
158                             "True", null));
159             properties.add("modelVersion", createSchemaProperty("Model Version", "string",
160                     modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelVersion").getAsString(),
161                     "True", null));
162             properties
163                     .add("modelCustomizationId",
164                             createSchemaProperty("Customization ID", "string",
165                                     modelVfModules.get(entry.getKey()).getAsJsonObject()
166                                             .get("vfModuleModelCustomizationUUID").getAsString(), "True",
167                                     null));
168
169             vfModuleOneOfSchema.add("properties", properties);
170             vfModuleOneOfSchemaArray.add(vfModuleOneOfSchema);
171         }
172         return vfModuleOneOfSchemaArray;
173     }
174
175     /**
176      * Create an anyOf array of possible structure we may have for Target.
177      *
178      * @param modelJson The service object
179      * @return A JsonArray with everything inside
180      */
181     public static JsonArray createAnyOfArray(Service modelJson, boolean generateType) {
182         JsonArray targetOneOfStructure = new JsonArray();
183         targetOneOfStructure.addAll(createVnfSchema(modelJson, generateType));
184         targetOneOfStructure.addAll(createVfModuleSchema(modelJson, generateType));
185         return targetOneOfStructure;
186     }
187
188     private static JsonArray createAnyOfArrayForCdsRecipe(Service modelJson) {
189         JsonArray anyOfStructure = new JsonArray();
190         anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("VF")));
191         anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("PNF")));
192         return anyOfStructure;
193     }
194
195     private static JsonArray createAnyOfCdsRecipe(JsonObject jsonObject) {
196         JsonArray schemaArray = new JsonArray();
197         for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
198             JsonObject controllerProperties = entry.getValue().getAsJsonObject()
199                     .getAsJsonObject("controllerProperties");
200
201             if (controllerProperties != null) {
202                 JsonObject workflows = controllerProperties.getAsJsonObject("workflows");
203                 for (Entry<String, JsonElement> workflowsEntry : workflows.entrySet()) {
204                     JsonObject obj = new JsonObject();
205                     obj.addProperty("title", workflowsEntry.getKey());
206                     obj.addProperty("type", "object");
207                     obj.add("properties", createPayloadProperty(workflowsEntry.getValue().getAsJsonObject(),
208                             controllerProperties, workflowsEntry.getKey()));
209                     schemaArray.add(obj);
210                 }
211
212             }
213         }
214         return schemaArray;
215     }
216
217     private static JsonObject createPayloadProperty(JsonObject workFlow,
218                                                     JsonObject controllerProperties, String workFlowName) {
219         JsonObject payload = new JsonObject();
220         payload.addProperty("title", "Payload");
221         payload.addProperty("type", "object");
222         payload.add("properties", createInputPropertiesForPayload(workFlow,
223                                                                   controllerProperties));
224         JsonObject properties = new JsonObject();
225         properties.add("recipe", createRecipeForCdsWorkflow(workFlowName));
226         properties.add("payload", payload);
227         return properties;
228     }
229
230     private static JsonObject createRecipeForCdsWorkflow(String workflow) {
231         JsonObject recipe = new JsonObject();
232         recipe.addProperty("title", "recipe");
233         recipe.addProperty("type", "string");
234         recipe.addProperty("default", workflow);
235         JsonObject options = new JsonObject();
236         options.addProperty("hidden", true);
237         recipe.add("options", options);
238         return recipe;
239     }
240
241     /**
242      * Returns the properties of payload based on the cds work flows.
243      *
244      * @param workFlow             cds work flows to update payload
245      * @param controllerProperties cds properties to get blueprint name and
246      *                             version
247      * @return returns the properties of payload
248      */
249     public static JsonObject createInputPropertiesForPayload(JsonObject workFlow,
250                                                              JsonObject controllerProperties) {
251         String artifactName = controllerProperties.get("sdnc_model_name").getAsString();
252         String artifactVersion = controllerProperties.get("sdnc_model_version").getAsString();
253         JsonObject inputs = workFlow.getAsJsonObject("inputs");
254         JsonObject jsonObject = new JsonObject();
255         jsonObject.add("artifact_name", createSchemaProperty(
256                 "artifact name", "string", artifactName, "True", null));
257         jsonObject.add("artifact_version", createSchemaProperty(
258                 "artifact version", "string", artifactVersion, "True", null));
259         jsonObject.add("mode", createCdsInputProperty(
260                 "mode", "string", "async" ,null));
261         jsonObject.add("data", createDataProperty(inputs));
262         return jsonObject;
263     }
264
265     private static JsonObject createDataProperty(JsonObject inputs) {
266         JsonObject data = new JsonObject();
267         data.addProperty("title", "data");
268         JsonObject dataObj = new JsonObject();
269         addDataFields(inputs, dataObj);
270         data.add(PROPERTIES, dataObj);
271         return data;
272     }
273
274     private static void addDataFields(JsonObject inputs,
275                                       JsonObject dataObj) {
276         Set<Map.Entry<String, JsonElement>> entrySet = inputs.entrySet();
277         for (Map.Entry<String, JsonElement> entry : entrySet) {
278             String key = entry.getKey();
279             JsonObject inputProperty = inputs.getAsJsonObject(key);
280             if (inputProperty.get(TYPE) == null) {
281                 addDataFields(entry.getValue().getAsJsonObject(), dataObj);
282             } else {
283                 dataObj.add(entry.getKey(),
284                             createCdsInputProperty(key,
285                                                    inputProperty.get(TYPE).getAsString(),
286                                                    null,
287                                                    entry.getValue().getAsJsonObject()));
288             }
289         }
290     }
291
292     private static JsonObject createCdsInputProperty(String title,
293                                                      String type,
294                                                      String defaultValue,
295                                                      JsonObject cdsProperty) {
296         JsonObject property = new JsonObject();
297         property.addProperty("title", title);
298
299         if (TYPE_LIST.equalsIgnoreCase(type)) {
300             property.addProperty(TYPE, "array");
301             if (cdsProperty.get(PROPERTIES) != null) {
302                 JsonObject dataObject = new JsonObject();
303                 addDataFields(cdsProperty.get(PROPERTIES).getAsJsonObject(),
304                               dataObject);
305                 JsonObject listProperties = new JsonObject();
306                 listProperties.add(PROPERTIES, dataObject);
307                 property.add("items", listProperties);
308             }
309         } else {
310             property.addProperty(TYPE, type);
311         }
312
313         if (defaultValue != null) {
314             property.addProperty("default", defaultValue);
315         }
316         return property;
317     }
318 }