c0e1c019eb3e32015360943384831744a05858bd
[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 ITEMS = "items";
49     public static final String ANY_OF = "anyOf";
50     public static final String TITLE = "title";
51     public static final String RECIPE = "recipe";
52     public static final String DEFAULT = "default";
53     public static final String STRING = "string";
54     public static final String TYPE = "type";
55     public static final String TYPE_LIST = "list";
56     public static final String TYPE_OBJECT = "object";
57     public static final String TYPE_ARRAY = "array";
58
59     private OperationalPolicyRepresentationBuilder() {
60         throw new IllegalStateException("This is Utility class, not supposed to be initiated.");
61     }
62
63     /**
64      * This method generates the operational policy json representation that will be
65      * used by ui for rendering. It uses the model (VF and VFModule) defined in the
66      * loop object to do so, so it's dynamic. It also uses the operational policy
67      * schema template defined in the resource folder.
68      *
69      * @param modelJson The loop model json
70      * @return The json representation
71      */
72     public static JsonObject generateOperationalPolicySchema(Service modelJson) {
73
74         JsonObject jsonSchema = null;
75         try {
76             jsonSchema = JsonUtils.GSON.fromJson(
77                     ResourceFileUtil
78                             .getResourceAsString("clds/json-schema/operational_policies/operational_policy.json"),
79                     JsonObject.class);
80             jsonSchema.get(PROPERTIES).getAsJsonObject()
81                     .get("operational_policy").getAsJsonObject().get(PROPERTIES).getAsJsonObject().get("policies")
82                     .getAsJsonObject().get(ITEMS).getAsJsonObject().get(PROPERTIES).getAsJsonObject().get("target")
83                     .getAsJsonObject().get(ANY_OF).getAsJsonArray().addAll(createAnyOfArray(modelJson, true));
84
85             // update CDS recipe and payload information to schema
86             JsonArray actors = jsonSchema.get(PROPERTIES).getAsJsonObject()
87                     .get("operational_policy").getAsJsonObject().get(PROPERTIES).getAsJsonObject().get("policies")
88                     .getAsJsonObject().get(ITEMS).getAsJsonObject().get(PROPERTIES).getAsJsonObject().get("actor")
89                     .getAsJsonObject().get(ANY_OF).getAsJsonArray();
90
91             for (JsonElement actor : actors) {
92                 if ("CDS".equalsIgnoreCase(actor.getAsJsonObject().get(TITLE).getAsString())) {
93                     actor.getAsJsonObject().get(PROPERTIES).getAsJsonObject().get(RECIPE).getAsJsonObject()
94                             .get(ANY_OF).getAsJsonArray()
95                             .addAll(createAnyOfArrayForCdsRecipe(modelJson));
96                 }
97             }
98             return jsonSchema;
99         } catch (IOException e) {
100             logger.error("Unable to generate the json schema because of an exception", e);
101             return new JsonObject();
102         }
103     }
104
105     private static JsonObject createSchemaProperty(String title, String type, String defaultValue, String readOnlyFlag,
106                                                    String[] enumArray) {
107         JsonObject property = new JsonObject();
108         property.addProperty(TITLE, title);
109         property.addProperty(TYPE, type);
110         property.addProperty(DEFAULT, defaultValue);
111         property.addProperty("readOnly", readOnlyFlag);
112
113         if (enumArray != null) {
114             JsonArray jsonArray = new JsonArray();
115             property.add("enum", jsonArray);
116             for (String val : enumArray) {
117                 jsonArray.add(val);
118             }
119         }
120         return property;
121     }
122
123     private static JsonArray createVnfSchema(Service modelService, boolean generateType) {
124         JsonArray vnfSchemaArray = new JsonArray();
125         JsonObject modelVnfs = modelService.getResourceByType("VF");
126
127         for (Entry<String, JsonElement> entry : modelVnfs.entrySet()) {
128             JsonObject vnfOneOfSchema = new JsonObject();
129             vnfOneOfSchema.addProperty(TITLE, "VNF" + "-" + entry.getKey());
130             JsonObject properties = new JsonObject();
131             if (generateType) {
132                 properties.add(TYPE, createSchemaProperty("Type", STRING, "VNF", "True", null));
133             }
134             properties.add("resourceID", createSchemaProperty("Resource ID", STRING,
135                     modelVnfs.get(entry.getKey()).getAsJsonObject().get("invariantUUID").getAsString(), "True", null));
136
137             vnfOneOfSchema.add(PROPERTIES, properties);
138             vnfSchemaArray.add(vnfOneOfSchema);
139         }
140         return vnfSchemaArray;
141     }
142
143     private static JsonArray createBlankEntry() {
144         JsonArray result = new JsonArray();
145         JsonObject blankObject = new JsonObject();
146         blankObject.addProperty("title", "User defined");
147         blankObject.add("properties", new JsonObject());
148         result.add(blankObject);
149         return result;
150     }
151
152     private static JsonArray createVfModuleSchema(Service modelService, boolean generateType) {
153         JsonArray vfModuleOneOfSchemaArray = new JsonArray();
154         JsonObject modelVfModules = modelService.getResourceByType("VFModule");
155
156         for (Entry<String, JsonElement> entry : modelVfModules.entrySet()) {
157             JsonObject vfModuleOneOfSchema = new JsonObject();
158             vfModuleOneOfSchema.addProperty(TITLE, "VFMODULE" + "-" + entry.getKey());
159             JsonObject properties = new JsonObject();
160             if (generateType) {
161                 properties.add(TYPE, createSchemaProperty("Type", STRING, "VFMODULE", "True", null));
162             }
163             properties.add("resourceID",
164                     createSchemaProperty("Resource ID", STRING,
165                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
166                             "True", null));
167             properties.add("modelInvariantId",
168                     createSchemaProperty("Model Invariant Id (ModelInvariantUUID)", STRING,
169                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelInvariantUUID")
170                                     .getAsString(),
171                             "True", null));
172             properties.add("modelVersionId",
173                     createSchemaProperty("Model Version Id (ModelUUID)", STRING,
174                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelUUID").getAsString(),
175                             "True", null));
176             properties.add("modelName",
177                     createSchemaProperty("Model Name", STRING,
178                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
179                             "True", null));
180             properties.add("modelVersion", createSchemaProperty("Model Version", STRING,
181                     modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelVersion").getAsString(),
182                     "True", null));
183             properties
184                     .add("modelCustomizationId",
185                             createSchemaProperty("Customization ID", STRING,
186                                     modelVfModules.get(entry.getKey()).getAsJsonObject()
187                                             .get("vfModuleModelCustomizationUUID").getAsString(), "True",
188                                     null));
189
190             vfModuleOneOfSchema.add(PROPERTIES, properties);
191             vfModuleOneOfSchemaArray.add(vfModuleOneOfSchema);
192         }
193         return vfModuleOneOfSchemaArray;
194     }
195
196     /**
197      * Create an anyOf array of possible structure we may have for Target.
198      *
199      * @param modelJson The service object
200      * @return A JsonArray with everything inside
201      */
202     public static JsonArray createAnyOfArray(Service modelJson, boolean generateType) {
203         JsonArray targetOneOfStructure = new JsonArray();
204         // First entry must be user defined
205         targetOneOfStructure.addAll(createBlankEntry());
206         targetOneOfStructure.addAll(createVnfSchema(modelJson, generateType));
207         targetOneOfStructure.addAll(createVfModuleSchema(modelJson, generateType));
208         return targetOneOfStructure;
209     }
210
211     private static JsonArray createAnyOfArrayForCdsRecipe(Service modelJson) {
212         JsonArray anyOfStructure = new JsonArray();
213         anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("VF")));
214         anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("PNF")));
215         return anyOfStructure;
216     }
217
218     private static JsonArray createAnyOfCdsRecipe(JsonObject jsonObject) {
219         JsonArray schemaArray = new JsonArray();
220         for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
221             JsonObject controllerProperties = entry.getValue().getAsJsonObject()
222                     .getAsJsonObject("controllerProperties");
223
224             if (controllerProperties != null && controllerProperties.getAsJsonObject("workflows") != null) {
225                 JsonObject workflows = controllerProperties.getAsJsonObject("workflows");
226                 for (Entry<String, JsonElement> workflowsEntry : workflows.entrySet()) {
227                     JsonObject obj = new JsonObject();
228                     obj.addProperty(TITLE, workflowsEntry.getKey());
229                     obj.addProperty(TYPE, "object");
230                     obj.add(PROPERTIES, createPayloadProperty(workflowsEntry.getValue().getAsJsonObject(),
231                             controllerProperties, workflowsEntry.getKey()));
232                     schemaArray.add(obj);
233                 }
234
235             }
236         }
237         return schemaArray;
238     }
239
240     private static JsonObject createPayloadProperty(JsonObject workFlow,
241                                                     JsonObject controllerProperties, String workFlowName) {
242         JsonObject payload = new JsonObject();
243         payload.addProperty(TITLE, "Payload");
244         payload.addProperty(TYPE, "object");
245         payload.add(PROPERTIES, createInputPropertiesForPayload(workFlow, controllerProperties,
246                                                                 workFlowName));
247         JsonObject properties = new JsonObject();
248         properties.add(RECIPE, createRecipeForCdsWorkflow(workFlowName));
249         properties.add("payload", payload);
250         return properties;
251     }
252
253     private static JsonObject createRecipeForCdsWorkflow(String workflow) {
254         JsonObject recipe = new JsonObject();
255         recipe.addProperty(TITLE, RECIPE);
256         recipe.addProperty(TYPE, STRING);
257         recipe.addProperty(DEFAULT, workflow);
258         JsonObject options = new JsonObject();
259         options.addProperty("hidden", true);
260         recipe.add("options", options);
261         return recipe;
262     }
263
264     /**
265      * Returns the properties of payload based on the cds work flows.
266      *
267      * @param workFlow             cds work flows to update payload
268      * @param controllerProperties cds properties to get blueprint name and
269      *                             version
270      * @param workFlowName         work flow name
271      * @return returns the properties of payload
272      */
273     public static JsonObject createInputPropertiesForPayload(JsonObject workFlow,
274                                                              JsonObject controllerProperties,
275                                                              String workFlowName) {
276         String artifactName = controllerProperties.get("sdnc_model_name").getAsString();
277         String artifactVersion = controllerProperties.get("sdnc_model_version").getAsString();
278         JsonObject inputs = workFlow.getAsJsonObject("inputs");
279         JsonObject jsonObject = new JsonObject();
280         jsonObject.add("artifact_name", createSchemaProperty(
281                 "artifact name", STRING, artifactName, "True", null));
282         jsonObject.add("artifact_version", createSchemaProperty(
283                 "artifact version", STRING, artifactVersion, "True", null));
284         jsonObject.add("mode", createCdsInputProperty(
285                 "mode", STRING, "async" ,null));
286         jsonObject.add("data", createDataProperty(inputs, workFlowName));
287         return jsonObject;
288     }
289
290     private static JsonObject createDataProperty(JsonObject inputs, String workflowName) {
291         JsonObject data = new JsonObject();
292         data.addProperty(TITLE, "data");
293         JsonObject dataObj = new JsonObject();
294         addDataFields(inputs, dataObj, workflowName);
295         data.add(PROPERTIES, dataObj);
296         return data;
297     }
298
299     private static void addDataFields(JsonObject inputs,
300                                       JsonObject dataObj,
301                                       String workFlowName) {
302         Set<Map.Entry<String, JsonElement>> entrySet = inputs.entrySet();
303         for (Map.Entry<String, JsonElement> entry : entrySet) {
304             String key = entry.getKey();
305             JsonObject inputProperty = inputs.getAsJsonObject(key);
306             if (key.equalsIgnoreCase(workFlowName + "-properties")) {
307                 addDataFields(entry.getValue().getAsJsonObject().get("properties").getAsJsonObject(),
308                         dataObj, workFlowName);
309             } else {
310                 dataObj.add(entry.getKey(),
311                         createCdsInputProperty(key, inputProperty.get(TYPE).getAsString(),null,
312                                 entry.getValue().getAsJsonObject()));
313             }
314         }
315     }
316
317     private static JsonObject createCdsInputProperty(String title,
318                                                      String type,
319                                                      String defaultValue,
320                                                      JsonObject cdsProperty) {
321         JsonObject property = new JsonObject();
322         property.addProperty(TITLE, title);
323
324         if (TYPE_LIST.equalsIgnoreCase(type)) {
325             property.addProperty(TYPE, TYPE_ARRAY);
326             if (cdsProperty != null && cdsProperty.get(PROPERTIES) != null) {
327                 JsonObject listProperties = new JsonObject();
328                 listProperties.add(PROPERTIES, getProperties(cdsProperty.get(PROPERTIES).getAsJsonObject()));
329                 property.add(ITEMS, listProperties);
330             }
331         } else if (TYPE_OBJECT.equalsIgnoreCase(type)) {
332             property.addProperty(TYPE, TYPE_OBJECT);
333             property.add(PROPERTIES, getProperties(cdsProperty.get(PROPERTIES).getAsJsonObject()));
334         } else {
335             property.addProperty(TYPE, type);
336         }
337
338         if (defaultValue != null) {
339             property.addProperty(DEFAULT, defaultValue);
340         }
341         return property;
342     }
343
344     private static JsonObject getProperties(JsonObject inputProperties) {
345         if (inputProperties == null) {
346             return null;
347         }
348         JsonObject dataObject = new JsonObject();
349         addDataFields(inputProperties, dataObject, null);
350         return dataObject;
351     }
352 }