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