6718475ca57e6e2dd78ca11b577da07efc537595
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP POLICY-CLAMP
4  * ================================================================================
5  * Copyright (C) 2019, 2021 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.policy.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 import java.io.IOException;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.Set;
36 import org.onap.policy.clamp.clds.util.JsonUtils;
37 import org.onap.policy.clamp.clds.util.ResourceFileUtils;
38 import org.onap.policy.clamp.loop.service.Service;
39
40 public class OperationalPolicyRepresentationBuilder {
41
42     private static final EELFLogger logger =
43             EELFManager.getInstance().getLogger(OperationalPolicyRepresentationBuilder.class);
44
45     public static final String PROPERTIES = "properties";
46     public static final String ITEMS = "items";
47     public static final String ANY_OF = "anyOf";
48     public static final String TITLE = "title";
49     public static final String RECIPE = "recipe";
50     public static final String DEFAULT = "default";
51     public static final String STRING = "string";
52     public static final String TYPE = "type";
53     public static final String TYPE_LIST = "list";
54     public static final String TYPE_OBJECT = "object";
55     public static final String TYPE_ARRAY = "array";
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                     ResourceFileUtils
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             for (JsonElement actor : 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                 if ("CDS".equalsIgnoreCase(actor.getAsJsonObject().get(TITLE).getAsString())) {
89                     actor.getAsJsonObject().get(PROPERTIES).getAsJsonObject().get(RECIPE).getAsJsonObject()
90                             .get(ANY_OF).getAsJsonArray()
91                             .addAll(createAnyOfArrayForCdsRecipe(modelJson));
92                 }
93             }
94             return jsonSchema;
95         } catch (IOException e) {
96             logger.error("Unable to generate the json schema because of an exception", e);
97             return new JsonObject();
98         }
99     }
100
101     private static JsonObject createSchemaProperty(String title, String type, String defaultValue, String readOnlyFlag,
102                                                    String[] enumArray) {
103         JsonObject property = new JsonObject();
104         property.addProperty(TITLE, title);
105         property.addProperty(TYPE, type);
106         property.addProperty(DEFAULT, defaultValue);
107         property.addProperty("readOnly", readOnlyFlag);
108
109         if (enumArray != null) {
110             JsonArray jsonArray = new JsonArray();
111             property.add("enum", jsonArray);
112             for (String val : enumArray) {
113                 jsonArray.add(val);
114             }
115         }
116         return property;
117     }
118
119     private static JsonArray createVnfSchema(Service modelService, boolean generateType) {
120         JsonArray vnfSchemaArray = new JsonArray();
121         JsonObject modelVnfs = modelService.getResourceByType("VF");
122
123         for (Entry<String, JsonElement> entry : modelVnfs.entrySet()) {
124             JsonObject vnfOneOfSchema = new JsonObject();
125             vnfOneOfSchema.addProperty(TITLE, "VNF" + "-" + entry.getKey());
126             JsonObject properties = new JsonObject();
127             if (generateType) {
128                 properties.add(TYPE, createSchemaProperty("Type", STRING, "VNF", "True", null));
129             }
130             properties.add("resourceID", createSchemaProperty("Resource ID", STRING,
131                     modelVnfs.get(entry.getKey()).getAsJsonObject().get("invariantUUID").getAsString(), "True", null));
132
133             vnfOneOfSchema.add(PROPERTIES, properties);
134             vnfSchemaArray.add(vnfOneOfSchema);
135         }
136         return vnfSchemaArray;
137     }
138
139     private static JsonArray createBlankEntry() {
140         JsonArray result = new JsonArray();
141         JsonObject blankObject = new JsonObject();
142         blankObject.addProperty(TITLE, "User defined");
143         blankObject.add(PROPERTIES, new JsonObject());
144         result.add(blankObject);
145         return result;
146     }
147
148     private static JsonArray createVfModuleSchema(Service modelService, boolean generateType) {
149         JsonArray vfModuleOneOfSchemaArray = new JsonArray();
150         JsonObject modelVfModules = modelService.getResourceByType("VFModule");
151
152         for (Entry<String, JsonElement> entry : modelVfModules.entrySet()) {
153             JsonObject vfModuleOneOfSchema = new JsonObject();
154             vfModuleOneOfSchema.addProperty(TITLE, "VFMODULE" + "-" + entry.getKey());
155             JsonObject properties = new JsonObject();
156             if (generateType) {
157                 properties.add(TYPE, createSchemaProperty("Type", STRING, "VFMODULE", "True", null));
158             }
159             properties.add("resourceID",
160                     createSchemaProperty("Resource ID", STRING,
161                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
162                             "True", null));
163             properties.add("modelInvariantId",
164                     createSchemaProperty("Model Invariant Id (ModelInvariantUUID)", STRING,
165                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelInvariantUUID")
166                                     .getAsString(),
167                             "True", null));
168             properties.add("modelVersionId",
169                     createSchemaProperty("Model Version Id (ModelUUID)", STRING,
170                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelUUID").getAsString(),
171                             "True", null));
172             properties.add("modelName",
173                     createSchemaProperty("Model Name", STRING,
174                             modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
175                             "True", null));
176             properties.add("modelVersion", createSchemaProperty("Model Version", STRING,
177                     modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelVersion").getAsString(),
178                     "True", null));
179             properties
180                     .add("modelCustomizationId",
181                             createSchemaProperty("Customization ID", STRING,
182                                     modelVfModules.get(entry.getKey()).getAsJsonObject()
183                                             .get("vfModuleModelCustomizationUUID").getAsString(), "True",
184                                     null));
185
186             vfModuleOneOfSchema.add(PROPERTIES, properties);
187             vfModuleOneOfSchemaArray.add(vfModuleOneOfSchema);
188         }
189         return vfModuleOneOfSchemaArray;
190     }
191
192     /**
193      * Create an anyOf array of possible structure we may have for Target.
194      *
195      * @param modelJson The service object
196      * @return A JsonArray with everything inside
197      */
198     public static JsonArray createAnyOfArray(Service modelJson, boolean generateType) {
199         JsonArray targetOneOfStructure = new JsonArray();
200         // First entry must be user defined
201         targetOneOfStructure.addAll(createBlankEntry());
202         targetOneOfStructure.addAll(createVnfSchema(modelJson, generateType));
203         targetOneOfStructure.addAll(createVfModuleSchema(modelJson, generateType));
204         return targetOneOfStructure;
205     }
206
207     private static JsonArray createAnyOfArrayForCdsRecipe(Service modelJson) {
208         JsonArray anyOfStructure = new JsonArray();
209         anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("VF")));
210         anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("PNF")));
211         return anyOfStructure;
212     }
213
214     private static JsonArray createAnyOfCdsRecipe(JsonObject jsonObject) {
215         JsonArray schemaArray = new JsonArray();
216         for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
217             JsonObject controllerProperties = entry.getValue().getAsJsonObject()
218                     .getAsJsonObject("controllerProperties");
219
220             if (controllerProperties != null && controllerProperties.getAsJsonObject("workflows") != null) {
221                 JsonObject workflows = controllerProperties.getAsJsonObject("workflows");
222                 for (Entry<String, JsonElement> workflowsEntry : workflows.entrySet()) {
223                     JsonObject obj = new JsonObject();
224                     obj.addProperty(TITLE, workflowsEntry.getKey());
225                     obj.addProperty(TYPE, TYPE_OBJECT);
226                     obj.add(PROPERTIES, createPayloadProperty(workflowsEntry.getValue().getAsJsonObject(),
227                             controllerProperties, workflowsEntry.getKey()));
228                     schemaArray.add(obj);
229                 }
230
231             }
232         }
233         return schemaArray;
234     }
235
236     private static JsonObject createPayloadProperty(JsonObject workFlow,
237                                                     JsonObject controllerProperties, String workFlowName) {
238         JsonObject payload = new JsonObject();
239         payload.addProperty(TITLE, "Payload");
240         payload.addProperty(TYPE, TYPE_OBJECT);
241         payload.add(PROPERTIES, createInputPropertiesForPayload(workFlow, controllerProperties,
242                                                                 workFlowName));
243         JsonObject properties = new JsonObject();
244         properties.add(RECIPE, createRecipeForCdsWorkflow(workFlowName));
245         properties.add("payload", payload);
246         return properties;
247     }
248
249     private static JsonObject createRecipeForCdsWorkflow(String workflow) {
250         JsonObject recipe = new JsonObject();
251         recipe.addProperty(TITLE, RECIPE);
252         recipe.addProperty(TYPE, STRING);
253         recipe.addProperty(DEFAULT, workflow);
254         JsonObject options = new JsonObject();
255         options.addProperty("hidden", true);
256         recipe.add("options", options);
257         return recipe;
258     }
259
260     /**
261      * Returns the properties of payload based on the cds work flows.
262      *
263      * @param workFlow             cds work flows to update payload
264      * @param controllerProperties cds properties to get blueprint name and
265      *                             version
266      * @param workFlowName         work flow name
267      * @return returns the properties of payload
268      */
269     public static JsonObject createInputPropertiesForPayload(JsonObject workFlow,
270                                                              JsonObject controllerProperties,
271                                                              String workFlowName) {
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, workFlowName));
283         return jsonObject;
284     }
285
286     private static JsonObject createDataProperty(JsonObject inputs, String workflowName) {
287         JsonObject data = new JsonObject();
288         data.addProperty(TITLE, "data");
289         JsonObject dataObj = new JsonObject();
290         addDataFields(inputs, dataObj, workflowName);
291         data.add(PROPERTIES, dataObj);
292         return data;
293     }
294
295     private static void addDataFields(JsonObject inputs,
296                                       JsonObject dataObj,
297                                       String workFlowName) {
298         Set<Map.Entry<String, JsonElement>> entrySet = inputs.entrySet();
299         for (Map.Entry<String, JsonElement> entry : entrySet) {
300             String key = entry.getKey();
301             JsonObject inputProperty = inputs.getAsJsonObject(key);
302             if (key.equalsIgnoreCase(workFlowName + "-properties")) {
303                 addDataFields(entry.getValue().getAsJsonObject().get(PROPERTIES).getAsJsonObject(),
304                         dataObj, workFlowName);
305             } else {
306                 dataObj.add(entry.getKey(),
307                         createCdsInputProperty(key, inputProperty.get(TYPE).getAsString(), 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, TYPE_ARRAY);
322             if (cdsProperty != null && cdsProperty.get(PROPERTIES) != null) {
323                 JsonObject listProperties = new JsonObject();
324                 listProperties.add(PROPERTIES, getProperties(cdsProperty.get(PROPERTIES).getAsJsonObject()));
325                 property.add(ITEMS, listProperties);
326             }
327         } else if (cdsProperty != null && TYPE_OBJECT.equalsIgnoreCase(type)) {
328             property.addProperty(TYPE, TYPE_OBJECT);
329             property.add(PROPERTIES, getProperties(cdsProperty.get(PROPERTIES).getAsJsonObject()));
330         } else {
331             property.addProperty(TYPE, type);
332         }
333
334         if (defaultValue != null) {
335             property.addProperty(DEFAULT, defaultValue);
336         }
337         return property;
338     }
339
340     private static JsonObject getProperties(JsonObject inputProperties) {
341         if (inputProperties == null) {
342             return null;
343         }
344         JsonObject dataObject = new JsonObject();
345         addDataFields(inputProperties, dataObject, null);
346         return dataObject;
347     }
348 }