1d5ed26e0a8a4e18df6b974e3de6656385a37f5a
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  *
22  */
23
24 package org.onap.policy.clamp.clds.tosca.update.parser;
25
26 import com.google.gson.JsonArray;
27 import com.google.gson.JsonObject;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.LinkedHashMap;
31 import java.util.Map.Entry;
32 import org.onap.policy.clamp.clds.tosca.update.elements.ToscaElement;
33 import org.onap.policy.clamp.clds.tosca.update.elements.ToscaElementProperty;
34 import org.onap.policy.clamp.clds.tosca.update.parser.metadata.ToscaMetadataParser;
35 import org.onap.policy.clamp.clds.tosca.update.templates.JsonTemplate;
36 import org.onap.policy.clamp.loop.service.Service;
37
38 /**
39  * This class can be used to convert a tosca to a json schema.
40  * This class is not supposed to be used directly because it requires the json Schema templates
41  * (template conversion tosca type to json schema entry) but also the supported Tosca main type file.
42  * The class ToscaConverterWithDictionarySupport is more complete for the end user to be used (in the clamp context).
43  *
44  * @see org.onap.policy.clamp.clds.tosca.update.ToscaConverterWithDictionarySupport#convertToscaToJsonSchemaObject
45  * @see org.onap.policy.clamp.clds.tosca.update.parser.ToscaConverterToJsonSchema#getJsonSchemaOfToscaElement
46  */
47 public class ToscaConverterToJsonSchema {
48     private static final String ARRAY = "array";
49     private static final String CONSTRAINTS = "constraints";
50     private static final String DESCRIPTION = "description";
51     private static final String ENTRY_SCHEMA = "entry_schema";
52     private static final String FORMAT = "format";
53     private static final String LIST = "list";
54     private static final String MAP = "map";
55     private static final String METADATA = "metadata";
56     private static final String OBJECT = "object";
57     private static final String PROPERTIES = "properties";
58     private static final String REQUIRED = "required";
59     private static final String TITLE = "title";
60     private static final String TYPE = "type";
61
62     private LinkedHashMap<String, ToscaElement> components;
63     private LinkedHashMap<String, JsonTemplate> templates;
64
65     private ToscaMetadataParser metadataParser;
66
67     private Service serviceModel;
68
69     /**
70      * Constructor.
71      *
72      * @param toscaElementsMap All the tosca elements found (policy type + data types + native tosca datatypes)
73      * @param jsonSchemaTemplates All Json schema templates to use
74      * @param metadataParser The metadata parser to use for metadata section
75      * @param serviceModel The service model for clamp enrichment
76      */
77     public ToscaConverterToJsonSchema(LinkedHashMap<String, ToscaElement> toscaElementsMap,
78             LinkedHashMap<String, JsonTemplate> jsonSchemaTemplates, ToscaMetadataParser metadataParser,
79             Service serviceModel) {
80         this.components = toscaElementsMap;
81         this.templates = jsonSchemaTemplates;
82         this.metadataParser = metadataParser;
83         this.serviceModel = serviceModel;
84     }
85
86     /**
87      * For a given component, launch process to parse it in Json.
88      *
89      * @param toscaElementKey name components
90      * @return return
91      */
92     public JsonObject getJsonSchemaOfToscaElement(String toscaElementKey) {
93         return this.getFieldAsObject(getToscaElement(toscaElementKey));
94     }
95
96     /**
97      * Return the classical/general fields of the component, & launch the properties deployment.
98      *
99      * @param toscaElement the compo
100      * @return a json object
101      */
102     public JsonObject getFieldAsObject(ToscaElement toscaElement) {
103
104         var globalFields = new JsonObject();
105         if (templates.get(OBJECT).hasFields(TITLE)) {
106             globalFields.addProperty(TITLE, toscaElement.getName());
107         }
108         if (templates.get(OBJECT).hasFields(TYPE)) {
109             globalFields.addProperty(TYPE, OBJECT);
110         }
111         if (templates.get(OBJECT).hasFields(DESCRIPTION) && (toscaElement.getDescription() != null)) {
112             globalFields.addProperty(DESCRIPTION, toscaElement.getDescription());
113         }
114         if (templates.get(OBJECT).hasFields(REQUIRED)) {
115             globalFields.add(REQUIRED, this.getRequirements(toscaElement.getName()));
116         }
117         if (templates.get(OBJECT).hasFields(PROPERTIES)) {
118             globalFields.add(PROPERTIES, this.deploy(toscaElement.getName()));
119         }
120         return globalFields;
121     }
122
123     /**
124      * Get the required properties of the Component, including the parents properties requirements.
125      *
126      * @param nameComponent name component
127      * @return a json array
128      */
129     public JsonArray getRequirements(String nameComponent) {
130         var requirements = new JsonArray();
131         ToscaElement toParse = components.get(nameComponent);
132         // Check for a father component, and launch the same process
133         if (!"tosca.datatypes.Root".equals(toParse.getDerivedFrom())
134                 && !"tosca.policies.Root".equals(toParse.getDerivedFrom())) {
135             requirements.addAll(getRequirements(toParse.getDerivedFrom()));
136         }
137         // Each property is checked, and add to the requirement array if it's required
138         Collection<ToscaElementProperty> properties = toParse.getProperties().values();
139         for (ToscaElementProperty toscaElementProperty : properties) {
140             if (toscaElementProperty.getItems().containsKey(REQUIRED)
141                     && toscaElementProperty.getItems().get(REQUIRED).equals(true)) {
142                 requirements.add(toscaElementProperty.getName());
143             }
144         }
145         return requirements;
146     }
147
148     /**
149      * The beginning of the recursive process. Get the parents (or not) to launch the same process, and otherwise
150      * deploy and parse the properties.
151      *
152      * @param nameComponent name component
153      * @return a json object
154      */
155     public JsonObject deploy(String nameComponent) {
156         var jsonSchema = new JsonObject();
157         ToscaElement toParse = components.get(nameComponent);
158         // Check for a father component, and launch the same process
159         if (!toParse.getDerivedFrom().equals("tosca.datatypes.Root")
160                 && !toParse.getDerivedFrom().equals("tosca.policies.Root")) {
161             jsonSchema = this.getParent(toParse.getDerivedFrom());
162         }
163         // For each component property, check if its a complex properties (a component) or not. In that case,
164         // launch the analyse of the property.
165         for (Entry<String, ToscaElementProperty> property : toParse.getProperties().entrySet()) {
166             if (getToscaElement((String) property.getValue().getItems().get(TYPE)) != null) {
167                 jsonSchema.add(property.getValue().getName(),
168                         this.getJsonSchemaOfToscaElement((String) property.getValue().getItems().get(TYPE)));
169             } else {
170                 jsonSchema.add(property.getValue().getName(), this.complexParse(property.getValue()));
171             }
172         }
173         return jsonSchema;
174     }
175
176     /**
177      * If a component has a parent, it is deploy in the same way.
178      *
179      * @param nameComponent name component
180      * @return a json object
181      */
182     public JsonObject getParent(String nameComponent) {
183         return deploy(nameComponent);
184     }
185
186     /**
187      * to be done.
188      *
189      * @param toscaElementProperty property
190      * @return a json object
191      */
192     @SuppressWarnings("unchecked")
193     public JsonObject complexParse(ToscaElementProperty toscaElementProperty) {
194         var propertiesInJson = new JsonObject();
195         JsonTemplate currentPropertyJsonTemplate;
196         String typeProperty = (String) toscaElementProperty.getItems().get(TYPE);
197         if (LIST.equalsIgnoreCase(typeProperty) || MAP.equalsIgnoreCase(typeProperty)) {
198             currentPropertyJsonTemplate = templates.get(OBJECT);
199         } else {
200             String propertyType = (String) toscaElementProperty.getItems().get(TYPE);
201             currentPropertyJsonTemplate = templates.get(propertyType.toLowerCase());
202         }
203         // Each "special" field is analysed, and has a specific treatment
204         for (String propertyField : toscaElementProperty.getItems().keySet()) {
205             switch (propertyField) {
206                 case TYPE:
207                     if (currentPropertyJsonTemplate.hasFields(propertyField)) {
208                         String fieldtype = (String) toscaElementProperty.getItems().get(propertyField);
209                         switch (fieldtype.toLowerCase()) {
210                             case LIST:
211                                 propertiesInJson.addProperty(TYPE, ARRAY);
212                                 break;
213                             case MAP:
214                                 propertiesInJson.addProperty(TYPE, OBJECT);
215                                 break;
216                             case "scalar-unit.time":
217                             case "scalar-unit.frequency":
218                             case "scalar-unit.size":
219                                 propertiesInJson.addProperty(TYPE, "string");
220                                 break;
221                             case "timestamp":
222                                 propertiesInJson.addProperty(TYPE, "string");
223                                 propertiesInJson.addProperty(FORMAT, "date-time");
224                                 break;
225                             case "float":
226                                 propertiesInJson.addProperty(TYPE, "number");
227                                 break;
228                             case "range":
229                                 propertiesInJson.addProperty(TYPE, "integer");
230                                 if (!checkConstraintPresence(toscaElementProperty, "greater_than")
231                                         && currentPropertyJsonTemplate.hasFields("exclusiveMinimum")) {
232                                     propertiesInJson.addProperty("exclusiveMinimum", false);
233                                 }
234                                 if (!checkConstraintPresence(toscaElementProperty, "less_than")
235                                         && currentPropertyJsonTemplate.hasFields("exclusiveMaximum")) {
236                                     propertiesInJson.addProperty("exclusiveMaximum", false);
237                                 }
238                                 break;
239                             default:
240                                 propertiesInJson.addProperty(TYPE, currentPropertyJsonTemplate.getName());
241                                 break;
242                         }
243                     }
244                     break;
245                 case METADATA:
246                     if (metadataParser != null) {
247                         metadataParser.processAllMetadataElement(toscaElementProperty, serviceModel).entrySet()
248                                 .forEach(jsonEntry -> propertiesInJson.add(jsonEntry.getKey(), jsonEntry.getValue()));
249                     }
250                     break;
251                 case CONSTRAINTS:
252                     toscaElementProperty.addConstraintsAsJson(propertiesInJson,
253                             (ArrayList<Object>) toscaElementProperty.getItems().get(CONSTRAINTS),
254                             currentPropertyJsonTemplate);
255                     break;
256                 case ENTRY_SCHEMA:
257                     // Here, a way to check if entry is a component (datatype) or a simple string
258                     if (getToscaElement(this.extractSpecificFieldFromMap(toscaElementProperty, ENTRY_SCHEMA)) != null) {
259                         String nameComponent = this.extractSpecificFieldFromMap(toscaElementProperty, ENTRY_SCHEMA);
260                         var child = new ToscaConverterToJsonSchema(components, templates, metadataParser, serviceModel);
261                         var propertiesContainer = new JsonObject();
262
263                         if (((String) toscaElementProperty.getItems().get(TYPE)).equals(MAP)) {
264                             JsonObject componentAsProperty = child.getJsonSchemaOfToscaElement(nameComponent);
265                             propertiesContainer.add(nameComponent, componentAsProperty);
266                             if (currentPropertyJsonTemplate.hasFields(PROPERTIES)) {
267                                 propertiesInJson.add(PROPERTIES, propertiesContainer);
268                             }
269                         } else {
270                             JsonObject componentAsItem = child.getJsonSchemaOfToscaElement(nameComponent);
271                             if (currentPropertyJsonTemplate.hasFields(PROPERTIES)) {
272                                 propertiesInJson.add("items", componentAsItem);
273                                 propertiesInJson.addProperty(FORMAT, "tabs-top");
274                             }
275                         }
276                     } else if (toscaElementProperty.getItems().get(TYPE).equals(LIST)) {
277                         // Native cases
278                         var itemContainer = new JsonObject();
279                         String valueInEntrySchema =
280                                 this.extractSpecificFieldFromMap(toscaElementProperty, ENTRY_SCHEMA);
281                         itemContainer.addProperty(TYPE, valueInEntrySchema);
282                         propertiesInJson.add("items", itemContainer);
283                         propertiesInJson.addProperty(FORMAT, "tabs-top");
284                     }
285
286                     // MAP Case, for now nothing
287
288                     break;
289                 default:
290                     // Each classical field : type, description, default..
291                     if (currentPropertyJsonTemplate.hasFields(propertyField) && !propertyField.equals(REQUIRED)) {
292                         toscaElementProperty.addFieldToJson(propertiesInJson, propertyField,
293                                 toscaElementProperty.getItems().get(propertyField));
294                     }
295                     break;
296             }
297         }
298         return propertiesInJson;
299     }
300
301     /**
302      * Look for a matching Component for the name parameter, in the components list.
303      *
304      * @param name the tosca element name to search for
305      * @return a tosca element
306      */
307     public ToscaElement getToscaElement(String name) {
308         ToscaElement correspondingToscaElement = null;
309         if (components == null) {
310             return null;
311         }
312         for (ToscaElement toscaElement : components.values()) {
313             if (toscaElement.getName().equals(name)) {
314                 correspondingToscaElement = toscaElement;
315             }
316         }
317         return correspondingToscaElement;
318     }
319
320     /**
321      * Simple method to extract quickly a type field from particular property item.
322      *
323      * @param toscaElementProperty the property
324      * @param fieldName the fieldname
325      * @return a string
326      */
327     @SuppressWarnings("unchecked")
328     public String extractSpecificFieldFromMap(ToscaElementProperty toscaElementProperty, String fieldName) {
329         LinkedHashMap<String, String> entrySchemaFields =
330                 (LinkedHashMap<String, String>) toscaElementProperty.getItems().get(fieldName);
331         return entrySchemaFields.get(TYPE);
332     }
333
334     /**
335      * Check if a constraint, for a specific property, is there.
336      *
337      * @param toscaElementProperty property
338      * @param nameConstraint name constraint
339      * @return a flag boolean
340      */
341     public boolean checkConstraintPresence(ToscaElementProperty toscaElementProperty, String nameConstraint) {
342         var presentConstraint = false;
343         if (toscaElementProperty.getItems().containsKey(CONSTRAINTS)) {
344             @SuppressWarnings("unchecked")
345             ArrayList<Object> constraints = (ArrayList<Object>) toscaElementProperty.getItems().get(CONSTRAINTS);
346             for (Object constraint : constraints) {
347                 if (constraint instanceof LinkedHashMap
348                         && ((LinkedHashMap<?, ?>) constraint).containsKey(nameConstraint)) {
349                     presentConstraint = true;
350                 }
351             }
352         }
353         return presentConstraint;
354     }
355 }