aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/clamp/policy/operational/OperationalPolicyRepresentationBuilder.java
blob: b1aa4ad186048d9c3b27d72ae19c367d68da8dd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*-
 * ============LICENSE_START=======================================================
 * ONAP CLAMP
 * ================================================================================
 * Copyright (C) 2019 AT&T Intellectual Property. All rights
 *                             reserved.
 * Modifications Copyright (C) 2020 Huawei Technologies Co., Ltd.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END============================================
 * ===================================================================
 *
 */

package org.onap.clamp.policy.operational;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.onap.clamp.clds.util.JsonUtils;
import org.onap.clamp.clds.util.ResourceFileUtil;
import org.onap.clamp.loop.service.Service;

public class OperationalPolicyRepresentationBuilder {

    private static final EELFLogger logger =
            EELFManager.getInstance().getLogger(OperationalPolicyRepresentationBuilder.class);

    public static final String PROPERTIES = "properties";
    public static final String TYPE = "type";
    public static final String TYPE_LIST = "list";

    /**
     * This method generates the operational policy json representation that will be
     * used by ui for rendering. It uses the model (VF and VFModule) defined in the
     * loop object to do so, so it's dynamic. It also uses the operational policy
     * schema template defined in the resource folder.
     *
     * @param modelJson The loop model json
     * @return The json representation
     */
    public static JsonObject generateOperationalPolicySchema(Service modelJson) {

        JsonObject jsonSchema = null;
        try {
            jsonSchema = JsonUtils.GSON.fromJson(
                    ResourceFileUtil
                            .getResourceAsString("clds/json-schema/operational_policies/operational_policy.json"),
                    JsonObject.class);
            jsonSchema.get("properties").getAsJsonObject()
                    .get("operational_policy").getAsJsonObject().get("properties").getAsJsonObject().get("policies")
                    .getAsJsonObject().get("items").getAsJsonObject().get("properties").getAsJsonObject().get("target")
                    .getAsJsonObject().get("anyOf").getAsJsonArray().addAll(createAnyOfArray(modelJson, true));

            // update CDS recipe and payload information to schema
            JsonArray actors = jsonSchema.get("properties").getAsJsonObject()
                    .get("operational_policy").getAsJsonObject().get("properties").getAsJsonObject().get("policies")
                    .getAsJsonObject().get("items").getAsJsonObject().get("properties").getAsJsonObject().get("actor")
                    .getAsJsonObject().get("anyOf").getAsJsonArray();

            for (JsonElement actor : actors) {
                if ("CDS".equalsIgnoreCase(actor.getAsJsonObject().get("title").getAsString())) {
                    actor.getAsJsonObject().get("properties").getAsJsonObject().get("recipe").getAsJsonObject()
                            .get("anyOf").getAsJsonArray()
                            .addAll(createAnyOfArrayForCdsRecipe(modelJson));
                }
            }
            return jsonSchema;
        } catch (IOException e) {
            logger.error("Unable to generate the json schema because of an exception", e);
            return new JsonObject();
        }
    }

    private static JsonObject createSchemaProperty(String title, String type, String defaultValue, String readOnlyFlag,
                                                   String[] enumArray) {
        JsonObject property = new JsonObject();
        property.addProperty("title", title);
        property.addProperty("type", type);
        property.addProperty("default", defaultValue);
        property.addProperty("readOnly", readOnlyFlag);

        if (enumArray != null) {
            JsonArray jsonArray = new JsonArray();
            property.add("enum", jsonArray);
            for (String val : enumArray) {
                jsonArray.add(val);
            }
        }
        return property;
    }

    private static JsonArray createVnfSchema(Service modelService, boolean generateType) {
        JsonArray vnfSchemaArray = new JsonArray();
        JsonObject modelVnfs = modelService.getResourceByType("VF");

        for (Entry<String, JsonElement> entry : modelVnfs.entrySet()) {
            JsonObject vnfOneOfSchema = new JsonObject();
            vnfOneOfSchema.addProperty("title", "VNF" + "-" + entry.getKey());
            JsonObject properties = new JsonObject();
            if (generateType) {
                properties.add("type", createSchemaProperty("Type", "string", "VNF", "True", null));
            }
            properties.add("resourceID", createSchemaProperty("Resource ID", "string",
                    modelVnfs.get(entry.getKey()).getAsJsonObject().get("name").getAsString(), "True", null));

            vnfOneOfSchema.add("properties", properties);
            vnfSchemaArray.add(vnfOneOfSchema);
        }
        return vnfSchemaArray;
    }

    private static JsonArray createBlankEntry() {
        JsonArray result = new JsonArray();
        JsonObject blankObject = new JsonObject();
        blankObject.addProperty("title", "User defined");
        blankObject.add("properties", new JsonObject());
        result.add(blankObject);
        return result;
    }

    private static JsonArray createVfModuleSchema(Service modelService, boolean generateType) {
        JsonArray vfModuleOneOfSchemaArray = new JsonArray();
        JsonObject modelVfModules = modelService.getResourceByType("VFModule");

        for (Entry<String, JsonElement> entry : modelVfModules.entrySet()) {
            JsonObject vfModuleOneOfSchema = new JsonObject();
            vfModuleOneOfSchema.addProperty("title", "VFMODULE" + "-" + entry.getKey());
            JsonObject properties = new JsonObject();
            if (generateType) {
                properties.add("type", createSchemaProperty("Type", "string", "VFMODULE", "True", null));
            }
            properties.add("resourceID",
                    createSchemaProperty("Resource ID", "string",
                            modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
                            "True", null));
            properties.add("modelInvariantId",
                    createSchemaProperty("Model Invariant Id (ModelInvariantUUID)", "string",
                            modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelInvariantUUID")
                                    .getAsString(),
                            "True", null));
            properties.add("modelVersionId",
                    createSchemaProperty("Model Version Id (ModelUUID)", "string",
                            modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelUUID").getAsString(),
                            "True", null));
            properties.add("modelName",
                    createSchemaProperty("Model Name", "string",
                            modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(),
                            "True", null));
            properties.add("modelVersion", createSchemaProperty("Model Version", "string",
                    modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelVersion").getAsString(),
                    "True", null));
            properties
                    .add("modelCustomizationId",
                            createSchemaProperty("Customization ID", "string",
                                    modelVfModules.get(entry.getKey()).getAsJsonObject()
                                            .get("vfModuleModelCustomizationUUID").getAsString(), "True",
                                    null));

            vfModuleOneOfSchema.add("properties", properties);
            vfModuleOneOfSchemaArray.add(vfModuleOneOfSchema);
        }
        return vfModuleOneOfSchemaArray;
    }

    /**
     * Create an anyOf array of possible structure we may have for Target.
     *
     * @param modelJson The service object
     * @return A JsonArray with everything inside
     */
    public static JsonArray createAnyOfArray(Service modelJson, boolean generateType) {
        JsonArray targetOneOfStructure = new JsonArray();
        // First entry must be user defined
        targetOneOfStructure.addAll(createBlankEntry());
        targetOneOfStructure.addAll(createVnfSchema(modelJson, generateType));
        targetOneOfStructure.addAll(createVfModuleSchema(modelJson, generateType));
        return targetOneOfStructure;
    }

    private static JsonArray createAnyOfArrayForCdsRecipe(Service modelJson) {
        JsonArray anyOfStructure = new JsonArray();
        anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("VF")));
        anyOfStructure.addAll(createAnyOfCdsRecipe(modelJson.getResourceDetails().getAsJsonObject("PNF")));
        return anyOfStructure;
    }

    private static JsonArray createAnyOfCdsRecipe(JsonObject jsonObject) {
        JsonArray schemaArray = new JsonArray();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            JsonObject controllerProperties = entry.getValue().getAsJsonObject()
                    .getAsJsonObject("controllerProperties");

            if (controllerProperties != null && controllerProperties.getAsJsonObject("workflows") != null) {
                JsonObject workflows = controllerProperties.getAsJsonObject("workflows");
                for (Entry<String, JsonElement> workflowsEntry : workflows.entrySet()) {
                    JsonObject obj = new JsonObject();
                    obj.addProperty("title", workflowsEntry.getKey());
                    obj.addProperty("type", "object");
                    obj.add("properties", createPayloadProperty(workflowsEntry.getValue().getAsJsonObject(),
                            controllerProperties, workflowsEntry.getKey()));
                    schemaArray.add(obj);
                }

            }
        }
        return schemaArray;
    }

    private static JsonObject createPayloadProperty(JsonObject workFlow,
                                                    JsonObject controllerProperties, String workFlowName) {
        JsonObject payload = new JsonObject();
        payload.addProperty("title", "Payload");
        payload.addProperty("type", "object");
        payload.add("properties", createInputPropertiesForPayload(workFlow,
                                                                  controllerProperties));
        JsonObject properties = new JsonObject();
        properties.add("recipe", createRecipeForCdsWorkflow(workFlowName));
        properties.add("payload", payload);
        return properties;
    }

    private static JsonObject createRecipeForCdsWorkflow(String workflow) {
        JsonObject recipe = new JsonObject();
        recipe.addProperty("title", "recipe");
        recipe.addProperty("type", "string");
        recipe.addProperty("default", workflow);
        JsonObject options = new JsonObject();
        options.addProperty("hidden", true);
        recipe.add("options", options);
        return recipe;
    }

    /**
     * Returns the properties of payload based on the cds work flows.
     *
     * @param workFlow             cds work flows to update payload
     * @param controllerProperties cds properties to get blueprint name and
     *                             version
     * @return returns the properties of payload
     */
    public static JsonObject createInputPropertiesForPayload(JsonObject workFlow,
                                                             JsonObject controllerProperties) {
        String artifactName = controllerProperties.get("sdnc_model_name").getAsString();
        String artifactVersion = controllerProperties.get("sdnc_model_version").getAsString();
        JsonObject inputs = workFlow.getAsJsonObject("inputs");
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("artifact_name", createSchemaProperty(
                "artifact name", "string", artifactName, "True", null));
        jsonObject.add("artifact_version", createSchemaProperty(
                "artifact version", "string", artifactVersion, "True", null));
        jsonObject.add("mode", createCdsInputProperty(
                "mode", "string", "async" ,null));
        jsonObject.add("data", createDataProperty(inputs));
        return jsonObject;
    }

    private static JsonObject createDataProperty(JsonObject inputs) {
        JsonObject data = new JsonObject();
        data.addProperty("title", "data");
        JsonObject dataObj = new JsonObject();
        addDataFields(inputs, dataObj);
        data.add(PROPERTIES, dataObj);
        return data;
    }

    private static void addDataFields(JsonObject inputs,
                                      JsonObject dataObj) {
        Set<Map.Entry<String, JsonElement>> entrySet = inputs.entrySet();
        for (Map.Entry<String, JsonElement> entry : entrySet) {
            String key = entry.getKey();
            JsonObject inputProperty = inputs.getAsJsonObject(key);
            if (inputProperty.get(TYPE) == null) {
                addDataFields(entry.getValue().getAsJsonObject(), dataObj);
            } else {
                dataObj.add(entry.getKey(),
                            createCdsInputProperty(key,
                                                   inputProperty.get(TYPE).getAsString(),
                                                   null,
                                                   entry.getValue().getAsJsonObject()));
            }
        }
    }

    private static JsonObject createCdsInputProperty(String title,
                                                     String type,
                                                     String defaultValue,
                                                     JsonObject cdsProperty) {
        JsonObject property = new JsonObject();
        property.addProperty("title", title);

        if (TYPE_LIST.equalsIgnoreCase(type)) {
            property.addProperty(TYPE, "array");
            if (cdsProperty.get(PROPERTIES) != null) {
                JsonObject dataObject = new JsonObject();
                addDataFields(cdsProperty.get(PROPERTIES).getAsJsonObject(),
                              dataObject);
                JsonObject listProperties = new JsonObject();
                listProperties.add(PROPERTIES, dataObject);
                property.add("items", listProperties);
            }
        } else {
            property.addProperty(TYPE, type);
        }

        if (defaultValue != null) {
            property.addProperty("default", defaultValue);
        }
        return property;
    }
}