Release 5.0.5
[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 createBlankEntry() {
132         JsonArray result = new JsonArray();
133         JsonObject blankObject = new JsonObject();
134         blankObject.addProperty("title", "User defined");
135         blankObject.add("properties", new JsonObject());
136         result.add(blankObject);
137         return result;
138     }
139
140     private static JsonArray createVfModuleSchema(Service modelService, boolean generateType) {
141         JsonArray vfModuleOneOfSchemaArray = new JsonArray();
142         JsonObject modelVfModules = modelService.getResourceByType("VFModule");
143
144         for (Entry<String, JsonElement> entry : modelVfModules.entrySet()) {
145             JsonObject vfModuleOneOfSchema = new JsonObject();
146             vfModuleOneOfSchema.addProperty("title", "VFMODULE" + "-" + entry.getKey());
147             JsonObject properties = new JsonObject();
148             if (generateType) {
149                 properties.add("type", createSchemaProperty("Type", "string", "VFMODULE", "True", null));
150             }
151             properties.add("resourceID",
152                     createSchemaProperty("Resource ID", "string",
153                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
154                             "True", null));
155             properties.add("modelInvariantId",
156                     createSchemaProperty("Model Invariant Id (ModelInvariantUUID)", "string",
157                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelInvariantUUID")
158                                     .getAsString(),
159                             "True", null));
160             properties.add("modelVersionId",
161                     createSchemaProperty("Model Version Id (ModelUUID)", "string",
162                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelUUID").getAsString(),
163                             "True", null));
164             properties.add("modelName",
165                     createSchemaProperty("Model Name", "string",
166                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
167                             "True", null));
168             properties.add("modelVersion", createSchemaProperty("Model Version", "string",
169                     modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelVersion").getAsString(),
170                     "True", null));
171             properties
172                     .add("modelCustomizationId",
173                             createSchemaProperty("Customization ID", "string",
174                                     modelVfModules.get(entry.getKey()).getAsJsonObject()
175                                             .get("vfModuleModelCustomizationUUID").getAsString(), "True",
176                                     null));
177
178             vfModuleOneOfSchema.add("properties", properties);
179             vfModuleOneOfSchemaArray.add(vfModuleOneOfSchema);
180         }
181         return vfModuleOneOfSchemaArray;
182     }
183
184     /**
185      * Create an anyOf array of possible structure we may have for Target.
186      *
187      * @param modelJson The service object
188      * @return A JsonArray with everything inside
189      */
190     public static JsonArray createAnyOfArray(Service modelJson, boolean generateType) {
191         JsonArray targetOneOfStructure = new JsonArray();
192         // First entry must be user defined
193         targetOneOfStructure.addAll(createBlankEntry());
194         targetOneOfStructure.addAll(createVnfSchema(modelJson, generateType));
195         targetOneOfStructure.addAll(createVfModuleSchema(modelJson, generateType));
196         return targetOneOfStructure;
197     }
198
199     private static JsonArray createAnyOfArrayForCdsRecipe(Service modelJson) {
200         JsonArray anyOfStructure = new JsonArray();
201         anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("VF")));
202         anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("PNF")));
203         return anyOfStructure;
204     }
205
206     private static JsonArray createAnyOfCdsRecipe(JsonObject jsonObject) {
207         JsonArray schemaArray = new JsonArray();
208         for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
209             JsonObject controllerProperties = entry.getValue().getAsJsonObject()
210                     .getAsJsonObject("controllerProperties");
211
212             if (controllerProperties != null && controllerProperties.getAsJsonObject("workflows") != null) {
213                 JsonObject workflows = controllerProperties.getAsJsonObject("workflows");
214                 for (Entry<String, JsonElement> workflowsEntry : workflows.entrySet()) {
215                     JsonObject obj = new JsonObject();
216                     obj.addProperty("title", workflowsEntry.getKey());
217                     obj.addProperty("type", "object");
218                     obj.add("properties", createPayloadProperty(workflowsEntry.getValue().getAsJsonObject(),
219                             controllerProperties, workflowsEntry.getKey()));
220                     schemaArray.add(obj);
221                 }
222
223             }
224         }
225         return schemaArray;
226     }
227
228     private static JsonObject createPayloadProperty(JsonObject workFlow,
229                                                     JsonObject controllerProperties, String workFlowName) {
230         JsonObject payload = new JsonObject();
231         payload.addProperty("title", "Payload");
232         payload.addProperty("type", "object");
233         payload.add("properties", createInputPropertiesForPayload(workFlow,
234                                                                   controllerProperties));
235         JsonObject properties = new JsonObject();
236         properties.add("recipe", createRecipeForCdsWorkflow(workFlowName));
237         properties.add("payload", payload);
238         return properties;
239     }
240
241     private static JsonObject createRecipeForCdsWorkflow(String workflow) {
242         JsonObject recipe = new JsonObject();
243         recipe.addProperty("title", "recipe");
244         recipe.addProperty("type", "string");
245         recipe.addProperty("default", workflow);
246         JsonObject options = new JsonObject();
247         options.addProperty("hidden", true);
248         recipe.add("options", options);
249         return recipe;
250     }
251
252     /**
253      * Returns the properties of payload based on the cds work flows.
254      *
255      * @param workFlow             cds work flows to update payload
256      * @param controllerProperties cds properties to get blueprint name and
257      *                             version
258      * @return returns the properties of payload
259      */
260     public static JsonObject createInputPropertiesForPayload(JsonObject workFlow,
261                                                              JsonObject controllerProperties) {
262         String artifactName = controllerProperties.get("sdnc_model_name").getAsString();
263         String artifactVersion = controllerProperties.get("sdnc_model_version").getAsString();
264         JsonObject inputs = workFlow.getAsJsonObject("inputs");
265         JsonObject jsonObject = new JsonObject();
266         jsonObject.add("artifact_name", createSchemaProperty(
267                 "artifact name", "string", artifactName, "True", null));
268         jsonObject.add("artifact_version", createSchemaProperty(
269                 "artifact version", "string", artifactVersion, "True", null));
270         jsonObject.add("mode", createCdsInputProperty(
271                 "mode", "string", "async" ,null));
272         jsonObject.add("data", createDataProperty(inputs));
273         return jsonObject;
274     }
275
276     private static JsonObject createDataProperty(JsonObject inputs) {
277         JsonObject data = new JsonObject();
278         data.addProperty("title", "data");
279         JsonObject dataObj = new JsonObject();
280         addDataFields(inputs, dataObj);
281         data.add(PROPERTIES, dataObj);
282         return data;
283     }
284
285     private static void addDataFields(JsonObject inputs,
286                                       JsonObject dataObj) {
287         Set<Map.Entry<String, JsonElement>> entrySet = inputs.entrySet();
288         for (Map.Entry<String, JsonElement> entry : entrySet) {
289             String key = entry.getKey();
290             JsonObject inputProperty = inputs.getAsJsonObject(key);
291             if (inputProperty.get(TYPE) == null) {
292                 addDataFields(entry.getValue().getAsJsonObject(), dataObj);
293             } else {
294                 dataObj.add(entry.getKey(),
295                             createCdsInputProperty(key,
296                                                    inputProperty.get(TYPE).getAsString(),
297                                                    null,
298                                                    entry.getValue().getAsJsonObject()));
299             }
300         }
301     }
302
303     private static JsonObject createCdsInputProperty(String title,
304                                                      String type,
305                                                      String defaultValue,
306                                                      JsonObject cdsProperty) {
307         JsonObject property = new JsonObject();
308         property.addProperty("title", title);
309
310         if (TYPE_LIST.equalsIgnoreCase(type)) {
311             property.addProperty(TYPE, "array");
312             if (cdsProperty.get(PROPERTIES) != null) {
313                 JsonObject dataObject = new JsonObject();
314                 addDataFields(cdsProperty.get(PROPERTIES).getAsJsonObject(),
315                               dataObject);
316                 JsonObject listProperties = new JsonObject();
317                 listProperties.add(PROPERTIES, dataObject);
318                 property.add("items", listProperties);
319             }
320         } else {
321             property.addProperty(TYPE, type);
322         }
323
324         if (defaultValue != null) {
325             property.addProperty("default", defaultValue);
326         }
327         return property;
328     }
329 }