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