From 3a83e2a2ff88ef49535973df8dc77dc8015170da Mon Sep 17 00:00:00 2001 From: ash74268 Date: Fri, 31 Jan 2020 15:40:15 +0000 Subject: [PATCH] Changes include Metadata support, Upload tosca policy model and Loop Template CLAMP Metadata support to parse policy_model_type, acronym and clamp_possible_values from the Tosca Policy Model UI and Backend changes to support Loop Template Backend APIs for Dictionary referenced in the Tosca Policy Model. Upload Tosca Model UI changes to allow user to upload policy models. DB Schema changes for the Loop Element Model and updated schema for the Dictionary Added Jest test cases and snapshots checkstyle issues fix and Junits Issue-ID: CLAMP-580 Signed-off-by: ash74268 Change-Id: I57521bc1c3afaf4ca5a2acf4c59823df05fd4cd6 Signed-off-by: ash74268 --- extra/sql/bulkload/create-tables.sql | 31 +- .../clamp/clds/tosca/ToscaSchemaConstants.java | 5 + .../clamp/clds/tosca/ToscaYamlToJsonConvertor.java | 565 ++++++++---- .../onap/clamp/loop/template/LoopElementModel.java | 72 +- .../org/onap/clamp/loop/template/LoopTemplate.java | 116 ++- .../template/LoopTemplateLoopElementModelId.java | 14 +- .../clamp/loop/template/LoopTemplatesService.java | 111 +++ .../org/onap/clamp/loop/template/LoopType.java | 42 + .../clamp/loop/template/LoopTypeConvertor.java | 52 ++ .../org/onap/clamp/loop/template/PolicyModel.java | 32 +- .../clamp/loop/template/PolicyModelsService.java | 60 +- src/main/java/org/onap/clamp/tosca/Dictionary.java | 86 +- .../org/onap/clamp/tosca/DictionaryElement.java | 121 +-- .../clamp/tosca/DictionaryElementsRepository.java | 2 +- .../org/onap/clamp/tosca/DictionaryRepository.java | 4 +- .../org/onap/clamp/tosca/DictionaryService.java | 142 +++ .../org/onap/clamp/util/SemanticVersioning.java | 31 +- .../resources/clds/camel/rest/clamp-api-v2.xml | 634 +++++++++---- .../tosca/DictionaryRepositoriesTestItCase.java | 15 +- .../clds/tosca/ToscaYamlToJsonConvertorTest.java | 91 -- .../tosca/ToscaYamlToJsonConvertorTestItCase.java | 188 ++++ .../clamp/loop/LoopTemplatesServiceItCase.java | 145 +++ .../onap/clamp/tosca/DictionaryServiceItCase.java | 247 ++++++ .../onap/clamp/util/SemanticVersioningTest.java | 28 +- .../resources/clds/camel/rest/clamp-api-v2.xml | 984 +++++++++++++++++++++ .../tosca_metadata_clamp_possible_values.yaml | 184 ++++ ...metadata_clamp_possible_values_json_schema.json | 235 +++++ ui-react/src/LoopUI.js | 2 + ui-react/src/__snapshots__/LoopUI.test.js.snap | 4 + ui-react/src/__snapshots__/OnapClamp.test.js.snap | 4 + ui-react/src/api/TemplateMenuService.js | 52 +- .../dialogs/Tosca/UploadToscaPolicyModal.js | 138 +++ .../dialogs/Tosca/UploadToscaPolicyModal.test.js | 87 ++ .../dialogs/Tosca/ViewToscaPolicyModal.js | 37 +- .../dialogs/Tosca/ViewToscaPolicyModal.test.js | 87 +- .../UploadToscaPolicyModal.test.js.snap | 111 +++ .../ViewToscaPolicyModal.test.js.snap | 26 +- ui-react/src/components/menu/MenuBar.js | 3 +- .../menu/__snapshots__/MenuBar.test.js.snap | 51 ++ 39 files changed, 4133 insertions(+), 706 deletions(-) create mode 100644 src/main/java/org/onap/clamp/loop/template/LoopTemplatesService.java create mode 100644 src/main/java/org/onap/clamp/loop/template/LoopType.java create mode 100644 src/main/java/org/onap/clamp/loop/template/LoopTypeConvertor.java create mode 100644 src/main/java/org/onap/clamp/tosca/DictionaryService.java delete mode 100644 src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTest.java create mode 100644 src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTestItCase.java create mode 100644 src/test/java/org/onap/clamp/loop/LoopTemplatesServiceItCase.java create mode 100644 src/test/java/org/onap/clamp/tosca/DictionaryServiceItCase.java create mode 100644 src/test/resources/clds/camel/rest/clamp-api-v2.xml create mode 100644 src/test/resources/tosca/tosca_metadata_clamp_possible_values.yaml create mode 100644 src/test/resources/tosca/tosca_metadata_clamp_possible_values_json_schema.json create mode 100644 ui-react/src/components/dialogs/Tosca/UploadToscaPolicyModal.js create mode 100644 ui-react/src/components/dialogs/Tosca/UploadToscaPolicyModal.test.js create mode 100644 ui-react/src/components/dialogs/Tosca/__snapshots__/UploadToscaPolicyModal.test.js.snap diff --git a/extra/sql/bulkload/create-tables.sql b/extra/sql/bulkload/create-tables.sql index 4edb4691..50c8d42c 100644 --- a/extra/sql/bulkload/create-tables.sql +++ b/extra/sql/bulkload/create-tables.sql @@ -11,17 +11,22 @@ ) engine=InnoDB; create table dictionary_elements ( - name varchar(255) not null, + short_name varchar(255) not null, created_by varchar(255), created_timestamp datetime(6) not null, updated_by varchar(255), updated_timestamp datetime(6) not null, - description varchar(255), - short_name varchar(255) not null, - subdictionary_id varchar(255) not null, + description varchar(255) not null, + name varchar(255) not null, + subdictionary_name varchar(255), type varchar(255) not null, - dictionary_id varchar(255), - primary key (name) + primary key (short_name) + ) engine=InnoDB; + + create table dictionary_to_dictionaryelements ( + dictionary_name varchar(255) not null, + dictionary_element_short_name varchar(255) not null, + primary key (dictionary_name, dictionary_element_short_name) ) engine=InnoDB; create table hibernate_sequence ( @@ -39,6 +44,7 @@ blueprint_yaml MEDIUMTEXT, dcae_blueprint_id varchar(255), loop_element_type varchar(255) not null, + short_name varchar(255), primary key (name) ) engine=InnoDB; @@ -58,6 +64,7 @@ created_timestamp datetime(6) not null, updated_by varchar(255), updated_timestamp datetime(6) not null, + allowed_loop_type varchar(255), blueprint_yaml MEDIUMTEXT, dcae_blueprint_id varchar(255), maximum_instances_allowed integer, @@ -161,12 +168,14 @@ primary key (service_uuid) ) engine=InnoDB; - alter table dictionary_elements - add constraint UK_qxkrvsrhp26m60apfvxphpl3d unique (short_name); + alter table dictionary_to_dictionaryelements + add constraint FK68hjjinnm8nte2owstd0xwp23 + foreign key (dictionary_element_short_name) + references dictionary_elements (short_name); - alter table dictionary_elements - add constraint FKn87bpgpm9i56w7uko585rbkgn - foreign key (dictionary_id) + alter table dictionary_to_dictionaryelements + add constraint FKtqfxg46gsxwlm2gkl6ne3cxfe + foreign key (dictionary_name) references dictionary (name); alter table loop_logs diff --git a/src/main/java/org/onap/clamp/clds/tosca/ToscaSchemaConstants.java b/src/main/java/org/onap/clamp/clds/tosca/ToscaSchemaConstants.java index 595b1805..9601649c 100644 --- a/src/main/java/org/onap/clamp/clds/tosca/ToscaSchemaConstants.java +++ b/src/main/java/org/onap/clamp/clds/tosca/ToscaSchemaConstants.java @@ -42,6 +42,11 @@ public class ToscaSchemaConstants { public static final String PROPERTIES = "properties"; public static final String REQUIRED = "required"; public static final String ENTRY_SCHEMA = "entry_schema"; + + public static final String METADATA = "metadata"; + public static final String METADATA_POLICY_MODEL_TYPE = "policy_model_type"; + public static final String METADATA_ACRONYM = "acronym"; + public static final String METADATA_CLAMP_POSSIBLE_VALUES = "clamp_possible_values"; // Constraints public static final String CONSTRAINTS = "constraints"; diff --git a/src/main/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertor.java b/src/main/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertor.java index 232db48c..666ca670 100644 --- a/src/main/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertor.java +++ b/src/main/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertor.java @@ -23,15 +23,25 @@ package org.onap.clamp.clds.tosca; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - +import java.util.Map.Entry; +import java.util.Optional; +import java.util.stream.Collectors; import org.json.JSONArray; import org.json.JSONObject; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.tosca.DictionaryElement; +import org.onap.clamp.tosca.DictionaryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; /** @@ -39,8 +49,15 @@ import org.yaml.snakeyaml.Yaml; * Editor. * */ +@Component public class ToscaYamlToJsonConvertor { + @Autowired + private DictionaryService dictionaryService; + + @Autowired + private ClampProperties refProp; + private int simpleTypeOrder = 1000; private int complexTypeOrder = 10000; private int complexSimpleTypeOrder = 1; @@ -58,12 +75,57 @@ public class ToscaYamlToJsonConvertor { return complexTypeOrder + complexSimpleTypeOrder; } + /** + * Parses Tosca YAML string and Converts to JsonObject. + * + * @param yamlString YAML string + * @return JsonObject + */ + public JsonObject validateAndConvertToJson(String yamlString) { + + Yaml yaml = new Yaml(); + LinkedHashMap loadedYaml = yaml.load(yamlString); + if (loadedYaml == null) { + return null; + } + + JSONObject jsonObject = new JSONObject(loadedYaml); + return new Gson().fromJson(jsonObject.toString(), JsonObject.class); + } + + /** + * return the values by looking up the key in the Toscsa JSON object. + * + * @param obj Tosca Json Object + * @param key the parameter key to look up + * @return the value for the provided key + */ + public String getValueFromMetadata(JsonObject obj, String key) { + JsonElement jsonElement = obj.get(ToscaSchemaConstants.NODE_TYPES); + if (jsonElement.isJsonObject()) { + Iterator> itr = + jsonElement.getAsJsonObject().entrySet().iterator(); + while (itr.hasNext()) { + Entry entry = itr.next(); + if (entry.getValue() != null && entry.getValue().isJsonObject() + && entry.getValue().getAsJsonObject().has(ToscaSchemaConstants.METADATA)) { + JsonObject metadatas = entry.getValue().getAsJsonObject() + .get(ToscaSchemaConstants.METADATA).getAsJsonObject(); + if (metadatas.has(key)) { + return metadatas.get(key).getAsString(); + } + } + } + } + return null; + } + /** * Parses Tosca YAML string. * - * @param yamlString YAML string + * @param yamlString YAML string * @param modelTypeToUse The model type that must be used to obtain the Json - * Schema + * Schema * @return JSON string */ public String parseToscaYaml(String yamlString, String modelTypeToUse) { @@ -78,7 +140,8 @@ public class ToscaYamlToJsonConvertor { JSONObject jsonParentObject = new JSONObject(); JSONObject jsonTempObject = new JSONObject(); parseNodeAndDataType(loadedYaml, nodeTypes, dataNodes); - populateJsonEditorObject(loadedYaml, nodeTypes, dataNodes, jsonParentObject, jsonTempObject, modelTypeToUse); + populateJsonEditorObject(loadedYaml, nodeTypes, dataNodes, jsonParentObject, jsonTempObject, + modelTypeToUse); if (jsonTempObject.length() > 0) { jsonParentObject = jsonTempObject; } @@ -89,13 +152,17 @@ public class ToscaYamlToJsonConvertor { // Parse node_type and data_type @SuppressWarnings("unchecked") - private void parseNodeAndDataType(LinkedHashMap map, LinkedHashMap nodeTypes, - LinkedHashMap dataNodes) { + private void parseNodeAndDataType(LinkedHashMap map, + LinkedHashMap nodeTypes, LinkedHashMap dataNodes) { map.entrySet().stream().forEach(n -> { - if (n.getKey().contains(ToscaSchemaConstants.NODE_TYPES) && n.getValue() instanceof Map) { - parseNodeAndDataType((LinkedHashMap) n.getValue(), nodeTypes, dataNodes); - } else if (n.getKey().contains(ToscaSchemaConstants.DATA_TYPES) && n.getValue() instanceof Map) { - parseNodeAndDataType((LinkedHashMap) n.getValue(), nodeTypes, dataNodes); + if (n.getKey().contains(ToscaSchemaConstants.NODE_TYPES) + && n.getValue() instanceof Map) { + parseNodeAndDataType((LinkedHashMap) n.getValue(), nodeTypes, + dataNodes); + } else if (n.getKey().contains(ToscaSchemaConstants.DATA_TYPES) + && n.getValue() instanceof Map) { + parseNodeAndDataType((LinkedHashMap) n.getValue(), nodeTypes, + dataNodes); } else if (n.getKey().contains(ToscaSchemaConstants.POLICY_NODE)) { nodeTypes.put(n.getKey(), n.getValue()); } else if (n.getKey().contains(ToscaSchemaConstants.POLICY_DATA)) { @@ -105,83 +172,97 @@ public class ToscaYamlToJsonConvertor { } @SuppressWarnings("unchecked") - private void populateJsonEditorObject(LinkedHashMap map, LinkedHashMap nodeTypes, - LinkedHashMap dataNodes, JSONObject jsonParentObject, JSONObject jsonTempObject, - String modelTypeToUse) { + private void populateJsonEditorObject(LinkedHashMap map, + LinkedHashMap nodeTypes, LinkedHashMap dataNodes, + JSONObject jsonParentObject, JSONObject jsonTempObject, String modelTypeToUse) { Map jsonEntrySchema = new HashMap<>(); jsonParentObject.put(JsonEditorSchemaConstants.TYPE, JsonEditorSchemaConstants.TYPE_OBJECT); if (nodeTypes.get(modelTypeToUse) instanceof Map) { - ((LinkedHashMap) nodeTypes.get(modelTypeToUse)).entrySet().forEach(ntElement -> { - if (ntElement.getKey().equalsIgnoreCase(ToscaSchemaConstants.PROPERTIES)) { - JSONArray rootNodeArray = new JSONArray(); - if (ntElement.getValue() instanceof Map) { - ((LinkedHashMap) ntElement.getValue()).entrySet() + ((LinkedHashMap) nodeTypes.get(modelTypeToUse)).entrySet() + .forEach(ntElement -> { + if (ntElement.getKey().equalsIgnoreCase(ToscaSchemaConstants.PROPERTIES)) { + JSONArray rootNodeArray = new JSONArray(); + if (ntElement.getValue() instanceof Map) { + ((LinkedHashMap) ntElement.getValue()).entrySet() .forEach((ntPropertiesElement) -> { boolean isListNode = false; - parseDescription((LinkedHashMap) ntPropertiesElement.getValue(), - jsonParentObject); - LinkedHashMap parentPropertiesMap = (LinkedHashMap) ntPropertiesElement + parseDescription( + (LinkedHashMap) ntPropertiesElement + .getValue(), + jsonParentObject); + LinkedHashMap parentPropertiesMap = + (LinkedHashMap) ntPropertiesElement .getValue(); if (parentPropertiesMap.containsKey(ToscaSchemaConstants.TYPE) - && ((String) parentPropertiesMap.get(ToscaSchemaConstants.TYPE)) - .contains(ToscaSchemaConstants.TYPE_MAP) - && parentPropertiesMap.containsKey(ToscaSchemaConstants.ENTRY_SCHEMA)) { - parentPropertiesMap = (LinkedHashMap) parentPropertiesMap + && ((String) parentPropertiesMap + .get(ToscaSchemaConstants.TYPE)) + .contains(ToscaSchemaConstants.TYPE_MAP) + && parentPropertiesMap + .containsKey(ToscaSchemaConstants.ENTRY_SCHEMA)) { + parentPropertiesMap = + (LinkedHashMap) parentPropertiesMap .get(ToscaSchemaConstants.ENTRY_SCHEMA); isListNode = true; } if (parentPropertiesMap.containsKey(ToscaSchemaConstants.TYPE) - && ((String) parentPropertiesMap.get(ToscaSchemaConstants.TYPE)) - .contains(ToscaSchemaConstants.POLICY_DATA)) { - ((LinkedHashMap) dataNodes - .get(parentPropertiesMap.get(ToscaSchemaConstants.TYPE))).entrySet() - .stream().forEach(pmap -> { - if (pmap.getKey().equalsIgnoreCase( - ToscaSchemaConstants.PROPERTIES)) { - parseToscaProperties(ToscaSchemaConstants.POLICY_NODE, - (LinkedHashMap) pmap.getValue(), - jsonParentObject, rootNodeArray, - jsonEntrySchema, dataNodes, - incrementSimpleTypeOrder()); - } - }); + && ((String) parentPropertiesMap + .get(ToscaSchemaConstants.TYPE)) + .contains(ToscaSchemaConstants.POLICY_DATA)) { + ((LinkedHashMap) dataNodes.get( + parentPropertiesMap.get(ToscaSchemaConstants.TYPE))) + .entrySet().stream().forEach(pmap -> { + if (pmap.getKey().equalsIgnoreCase( + ToscaSchemaConstants.PROPERTIES)) { + parseToscaProperties( + ToscaSchemaConstants.POLICY_NODE, + (LinkedHashMap) pmap + .getValue(), + jsonParentObject, rootNodeArray, + jsonEntrySchema, dataNodes, + incrementSimpleTypeOrder()); + } + }); } if (isListNode) { jsonTempObject.put(JsonEditorSchemaConstants.TYPE, - JsonEditorSchemaConstants.TYPE_ARRAY); - parseDescription((LinkedHashMap) ntPropertiesElement.getValue(), - jsonTempObject); - jsonTempObject.put(JsonEditorSchemaConstants.ITEMS, jsonParentObject); + JsonEditorSchemaConstants.TYPE_ARRAY); + parseDescription( + (LinkedHashMap) ntPropertiesElement + .getValue(), + jsonTempObject); + jsonTempObject.put(JsonEditorSchemaConstants.ITEMS, + jsonParentObject); jsonTempObject.put(JsonEditorSchemaConstants.FORMAT, - JsonEditorSchemaConstants.CUSTOM_KEY_FORMAT_TABS_TOP); + JsonEditorSchemaConstants.CUSTOM_KEY_FORMAT_TABS_TOP); jsonTempObject.put(JsonEditorSchemaConstants.UNIQUE_ITEMS, - JsonEditorSchemaConstants.TRUE); + JsonEditorSchemaConstants.TRUE); } }); + } } - } - }); + }); } } @SuppressWarnings("unchecked") private void parseToscaProperties(String parentKey, LinkedHashMap propertiesMap, - JSONObject jsonDataNode, JSONArray array, Map jsonEntrySchema, - LinkedHashMap dataNodes, final int order) { + JSONObject jsonDataNode, JSONArray array, Map jsonEntrySchema, + LinkedHashMap dataNodes, final int order) { JSONObject jsonPropertyNode = new JSONObject(); propertiesMap.entrySet().stream().forEach(p -> { // Populate JSON Array for "required" key if (p.getValue() instanceof Map) { - LinkedHashMap nodeMap = (LinkedHashMap) p.getValue(); + LinkedHashMap nodeMap = + (LinkedHashMap) p.getValue(); if (nodeMap.containsKey(ToscaSchemaConstants.REQUIRED) - && ((boolean) nodeMap.get(ToscaSchemaConstants.REQUIRED))) { + && ((boolean) nodeMap.get(ToscaSchemaConstants.REQUIRED))) { array.put(p.getKey()); } // if(nodeMap.containsKey(ToscaSchemaConstants.CONSTRAINTS)) - parseToscaChildNodeMap(p.getKey(), nodeMap, jsonPropertyNode, jsonEntrySchema, dataNodes, array, - incrementSimpleTypeOrder()); + parseToscaChildNodeMap(p.getKey(), nodeMap, jsonPropertyNode, jsonEntrySchema, + dataNodes, array, incrementSimpleTypeOrder()); } }); jsonDataNode.put(JsonEditorSchemaConstants.REQUIRED, array); @@ -189,42 +270,48 @@ public class ToscaYamlToJsonConvertor { } @SuppressWarnings("unchecked") - private void parseToscaPropertiesForType(String parentKey, LinkedHashMap propertiesMap, - JSONObject jsonDataNode, JSONArray array, Map jsonEntrySchema, - LinkedHashMap dataNodes, boolean isType, int order) { + private void parseToscaPropertiesForType(String parentKey, + LinkedHashMap propertiesMap, JSONObject jsonDataNode, JSONArray array, + Map jsonEntrySchema, LinkedHashMap dataNodes, + boolean isType, int order) { JSONObject jsonPropertyNode = new JSONObject(); propertiesMap.entrySet().stream().forEach(p -> { // array.put(p.getKey()); boolean overWriteArray = false; if (p.getValue() instanceof Map) { - LinkedHashMap nodeMap = (LinkedHashMap) p.getValue(); + LinkedHashMap nodeMap = + (LinkedHashMap) p.getValue(); if (!(parentKey.contains(ToscaSchemaConstants.ENTRY_SCHEMA) - || parentKey.contains(ToscaSchemaConstants.POLICY_NODE)) - && nodeMap.containsKey(ToscaSchemaConstants.TYPE) - && (((String) nodeMap.get(ToscaSchemaConstants.TYPE)) - .contains(ToscaSchemaConstants.POLICY_DATA))) { + || parentKey.contains(ToscaSchemaConstants.POLICY_NODE)) + && nodeMap.containsKey(ToscaSchemaConstants.TYPE) + && (((String) nodeMap.get(ToscaSchemaConstants.TYPE)) + .contains(ToscaSchemaConstants.POLICY_DATA))) { overWriteArray = true; } if (nodeMap.containsKey(ToscaSchemaConstants.REQUIRED) - && ((boolean) nodeMap.get(ToscaSchemaConstants.REQUIRED))) { + && ((boolean) nodeMap.get(ToscaSchemaConstants.REQUIRED))) { array.put(p.getKey()); } - parseToscaChildNodeMap(p.getKey(), nodeMap, jsonPropertyNode, jsonEntrySchema, dataNodes, array, order); + parseToscaChildNodeMap(p.getKey(), nodeMap, jsonPropertyNode, jsonEntrySchema, + dataNodes, array, order); } }); jsonDataNode.put(JsonEditorSchemaConstants.REQUIRED, array); jsonDataNode.put(JsonEditorSchemaConstants.PROPERTIES, jsonPropertyNode); } - private void parseToscaChildNodeMap(String childObjectKey, LinkedHashMap childNodeMap, - JSONObject jsonPropertyNode, Map jsonEntrySchema, - LinkedHashMap dataNodes, JSONArray array, int order) { + private void parseToscaChildNodeMap(String childObjectKey, + LinkedHashMap childNodeMap, JSONObject jsonPropertyNode, + Map jsonEntrySchema, LinkedHashMap dataNodes, + JSONArray array, int order) { JSONObject childObject = new JSONObject(); // JSONArray childArray = new JSONArray(); parseDescription(childNodeMap, childObject); - parseTypes(childObjectKey, childNodeMap, childObject, jsonEntrySchema, dataNodes, array, order); + parseTypes(childObjectKey, childNodeMap, childObject, jsonEntrySchema, dataNodes, array, + order); parseConstraints(childNodeMap, childObject); + parseMetadataPossibleValues(childNodeMap, childObject); parseEntrySchema(childNodeMap, childObject, jsonPropertyNode, jsonEntrySchema, dataNodes); jsonPropertyNode.put(childObjectKey, childObject); @@ -232,15 +319,17 @@ public class ToscaYamlToJsonConvertor { } - private void parseEntrySchema(LinkedHashMap childNodeMap, JSONObject childObject, - JSONObject jsonPropertyNode, Map jsonEntrySchema, - LinkedHashMap dataNodes) { + private void parseEntrySchema(LinkedHashMap childNodeMap, + JSONObject childObject, JSONObject jsonPropertyNode, + Map jsonEntrySchema, LinkedHashMap dataNodes) { if (childNodeMap.get(ToscaSchemaConstants.ENTRY_SCHEMA) != null) { if (childNodeMap.get(ToscaSchemaConstants.ENTRY_SCHEMA) instanceof Map) { - LinkedHashMap entrySchemaMap = (LinkedHashMap) childNodeMap + LinkedHashMap entrySchemaMap = + (LinkedHashMap) childNodeMap .get(ToscaSchemaConstants.ENTRY_SCHEMA); entrySchemaMap.entrySet().stream().forEach(entry -> { - if (entry.getKey().equalsIgnoreCase(ToscaSchemaConstants.TYPE) && entry.getValue() != null) { + if (entry.getKey().equalsIgnoreCase(ToscaSchemaConstants.TYPE) + && entry.getValue() != null) { String entrySchemaType = (String) entry.getValue(); if (entrySchemaType.contains(ToscaSchemaConstants.POLICY_DATA)) { JSONArray array = new JSONArray(); @@ -248,44 +337,51 @@ public class ToscaYamlToJsonConvertor { // Already traversed JSONObject entrySchemaObject = jsonEntrySchema.get(entrySchemaType); attachEntrySchemaJsonObject(childObject, entrySchemaObject, - JsonEditorSchemaConstants.TYPE_OBJECT); + JsonEditorSchemaConstants.TYPE_OBJECT); } else if (dataNodes.containsKey(entrySchemaType)) { JSONObject entrySchemaObject = new JSONObject(); // Need to traverse - ((LinkedHashMap) dataNodes.get(entrySchemaType)).entrySet().stream() - .forEach(pmap -> { - if (pmap.getKey().equalsIgnoreCase(ToscaSchemaConstants.PROPERTIES)) { - parseToscaProperties(ToscaSchemaConstants.ENTRY_SCHEMA, - (LinkedHashMap) pmap.getValue(), - entrySchemaObject, array, jsonEntrySchema, dataNodes, - incrementComplexTypeOrder()); - jsonEntrySchema.put(entrySchemaType, entrySchemaObject); - dataNodes.remove(entrySchemaType); - attachEntrySchemaJsonObject(childObject, entrySchemaObject, - JsonEditorSchemaConstants.TYPE_OBJECT); - } + ((LinkedHashMap) dataNodes.get(entrySchemaType)) + .entrySet().stream().forEach(pmap -> { + if (pmap.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.PROPERTIES)) { + parseToscaProperties(ToscaSchemaConstants.ENTRY_SCHEMA, + (LinkedHashMap) pmap.getValue(), + entrySchemaObject, array, jsonEntrySchema, + dataNodes, incrementComplexTypeOrder()); + jsonEntrySchema.put(entrySchemaType, entrySchemaObject); + dataNodes.remove(entrySchemaType); + attachEntrySchemaJsonObject(childObject, + entrySchemaObject, + JsonEditorSchemaConstants.TYPE_OBJECT); + } - }); + }); } - } else if (entrySchemaType.equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING) - || entrySchemaType.equalsIgnoreCase(ToscaSchemaConstants.TYPE_INTEGER) - || entrySchemaType.equalsIgnoreCase(ToscaSchemaConstants.TYPE_FLOAT)) { + } else if (entrySchemaType + .equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING) + || entrySchemaType.equalsIgnoreCase(ToscaSchemaConstants.TYPE_INTEGER) + || entrySchemaType.equalsIgnoreCase(ToscaSchemaConstants.TYPE_FLOAT)) { JSONObject entrySchemaObject = new JSONObject(); parseConstraints(entrySchemaMap, entrySchemaObject); + parseMetadataPossibleValues(entrySchemaMap, entrySchemaObject); String jsontype = JsonEditorSchemaConstants.TYPE_STRING; if (entrySchemaType.equalsIgnoreCase(ToscaSchemaConstants.TYPE_INTEGER) - || entrySchemaType.equalsIgnoreCase(ToscaSchemaConstants.TYPE_FLOAT)) { + || entrySchemaType + .equalsIgnoreCase(ToscaSchemaConstants.TYPE_FLOAT)) { jsontype = JsonEditorSchemaConstants.TYPE_INTEGER; } if (childNodeMap.get(ToscaSchemaConstants.TYPE) != null) { // Only known value of type is String for now if (childNodeMap.get(ToscaSchemaConstants.TYPE) instanceof String) { - String typeValue = (String) childNodeMap.get(ToscaSchemaConstants.TYPE); - if (typeValue.equalsIgnoreCase(ToscaSchemaConstants.TYPE_LIST)) { + String typeValue = + (String) childNodeMap.get(ToscaSchemaConstants.TYPE); + if (typeValue + .equalsIgnoreCase(ToscaSchemaConstants.TYPE_LIST)) { // Custom key for JSON Editor and UI rendering childObject.put(JsonEditorSchemaConstants.CUSTOM_KEY_FORMAT, - JsonEditorSchemaConstants.FORMAT_SELECT); + JsonEditorSchemaConstants.FORMAT_SELECT); // childObject.put(JsonEditorSchemaConstants.UNIQUE_ITEMS, // JsonEditorSchemaConstants.TRUE); } @@ -299,7 +395,8 @@ public class ToscaYamlToJsonConvertor { } } - private void attachEntrySchemaJsonObject(JSONObject childObject, JSONObject entrySchemaObject, String dataType) { + private void attachEntrySchemaJsonObject(JSONObject childObject, JSONObject entrySchemaObject, + String dataType) { entrySchemaObject.put(JsonEditorSchemaConstants.TYPE, dataType); childObject.put(JsonEditorSchemaConstants.ITEMS, entrySchemaObject); @@ -320,33 +417,40 @@ public class ToscaYamlToJsonConvertor { * toscaKey.length()); } */ - private void parseDescription(LinkedHashMap childNodeMap, JSONObject childObject) { + private void parseDescription(LinkedHashMap childNodeMap, + JSONObject childObject) { if (childNodeMap.get(ToscaSchemaConstants.DESCRIPTION) != null) { - childObject.put(JsonEditorSchemaConstants.TITLE, childNodeMap.get(ToscaSchemaConstants.DESCRIPTION)); + childObject.put(JsonEditorSchemaConstants.TITLE, + childNodeMap.get(ToscaSchemaConstants.DESCRIPTION)); } } - private void parseTypes(String childObjectKey, LinkedHashMap childNodeMap, JSONObject childObject, - Map jsonEntrySchema, LinkedHashMap dataNodes, JSONArray array, - int order) { + private void parseTypes(String childObjectKey, LinkedHashMap childNodeMap, + JSONObject childObject, Map jsonEntrySchema, + LinkedHashMap dataNodes, JSONArray array, int order) { if (childNodeMap.get(ToscaSchemaConstants.TYPE) != null) { // Only known value of type is String for now if (childNodeMap.get(ToscaSchemaConstants.TYPE) instanceof String) { childObject.put(JsonEditorSchemaConstants.PROPERTY_ORDER, order); String typeValue = (String) childNodeMap.get(ToscaSchemaConstants.TYPE); if (typeValue.equalsIgnoreCase(ToscaSchemaConstants.TYPE_INTEGER)) { - childObject.put(JsonEditorSchemaConstants.TYPE, JsonEditorSchemaConstants.TYPE_INTEGER); + childObject.put(JsonEditorSchemaConstants.TYPE, + JsonEditorSchemaConstants.TYPE_INTEGER); } else if (typeValue.equalsIgnoreCase(ToscaSchemaConstants.TYPE_FLOAT)) { - childObject.put(JsonEditorSchemaConstants.TYPE, JsonEditorSchemaConstants.TYPE_INTEGER); + childObject.put(JsonEditorSchemaConstants.TYPE, + JsonEditorSchemaConstants.TYPE_INTEGER); } else if (typeValue.equalsIgnoreCase(ToscaSchemaConstants.TYPE_LIST)) { - childObject.put(JsonEditorSchemaConstants.TYPE, JsonEditorSchemaConstants.TYPE_ARRAY); + childObject.put(JsonEditorSchemaConstants.TYPE, + JsonEditorSchemaConstants.TYPE_ARRAY); // Custom key for JSON Editor and UI rendering childObject.put(JsonEditorSchemaConstants.CUSTOM_KEY_FORMAT, - JsonEditorSchemaConstants.CUSTOM_KEY_FORMAT_TABS_TOP); - childObject.put(JsonEditorSchemaConstants.UNIQUE_ITEMS, JsonEditorSchemaConstants.TRUE); + JsonEditorSchemaConstants.CUSTOM_KEY_FORMAT_TABS_TOP); + childObject.put(JsonEditorSchemaConstants.UNIQUE_ITEMS, + JsonEditorSchemaConstants.TRUE); } else if (typeValue.equalsIgnoreCase(ToscaSchemaConstants.TYPE_MAP)) { - childObject.put(JsonEditorSchemaConstants.TYPE, JsonEditorSchemaConstants.TYPE_OBJECT); + childObject.put(JsonEditorSchemaConstants.TYPE, + JsonEditorSchemaConstants.TYPE_OBJECT); } else if (typeValue.contains(ToscaSchemaConstants.POLICY_DATA)) { JSONArray childArray = new JSONArray(); @@ -358,101 +462,129 @@ public class ToscaYamlToJsonConvertor { JSONObject entrySchemaObject = new JSONObject(); // Need to traverse JSONArray jsonArray = new JSONArray(); - ((LinkedHashMap) dataNodes.get(typeValue)).entrySet().stream().forEach(pmap -> { - if (pmap.getKey().equalsIgnoreCase(ToscaSchemaConstants.PROPERTIES)) { - parseToscaPropertiesForType(childObjectKey, - (LinkedHashMap) pmap.getValue(), entrySchemaObject, childArray, - jsonEntrySchema, dataNodes, true, incrementComplexSimpleTypeOrder()); - jsonEntrySchema.put(typeValue, entrySchemaObject); - dataNodes.remove(typeValue); - attachTypeJsonObject(childObject, entrySchemaObject); - } - }); + ((LinkedHashMap) dataNodes.get(typeValue)).entrySet() + .stream().forEach(pmap -> { + if (pmap.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.PROPERTIES)) { + parseToscaPropertiesForType(childObjectKey, + (LinkedHashMap) pmap.getValue(), + entrySchemaObject, childArray, jsonEntrySchema, dataNodes, + true, incrementComplexSimpleTypeOrder()); + jsonEntrySchema.put(typeValue, entrySchemaObject); + dataNodes.remove(typeValue); + attachTypeJsonObject(childObject, entrySchemaObject); + } + }); } } else { - childObject.put(JsonEditorSchemaConstants.TYPE, JsonEditorSchemaConstants.TYPE_STRING); + childObject.put(JsonEditorSchemaConstants.TYPE, + JsonEditorSchemaConstants.TYPE_STRING); } } if (childNodeMap.get(ToscaSchemaConstants.DEFAULT) != null) { - childObject.put(JsonEditorSchemaConstants.DEFAULT, childNodeMap.get(ToscaSchemaConstants.DEFAULT)); + childObject.put(JsonEditorSchemaConstants.DEFAULT, + childNodeMap.get(ToscaSchemaConstants.DEFAULT)); } } } - private void parseConstraints(LinkedHashMap childNodeMap, JSONObject childObject) { + private void parseConstraints(LinkedHashMap childNodeMap, + JSONObject childObject) { if (childNodeMap.containsKey(ToscaSchemaConstants.CONSTRAINTS) - && childNodeMap.get(ToscaSchemaConstants.CONSTRAINTS) != null) { - List> constraintsList = (List>) childNodeMap + && childNodeMap.get(ToscaSchemaConstants.CONSTRAINTS) != null) { + List> constraintsList = + (List>) childNodeMap .get(ToscaSchemaConstants.CONSTRAINTS); constraintsList.stream().forEach(c -> { if (c instanceof Map) { c.entrySet().stream().forEach(constraint -> { if (constraint.getKey().equalsIgnoreCase(ToscaSchemaConstants.MIN_LENGTH) - || constraint.getKey().equalsIgnoreCase(ToscaSchemaConstants.GREATER_OR_EQUAL)) { - // For String min_lenghth is minimum length whereas for number, it will be + || constraint.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.GREATER_OR_EQUAL)) { + // For String min_lenghth is minimum length whereas for number, it will + // be // minimum or greater than to the defined value if (childNodeMap.containsKey(ToscaSchemaConstants.TYPE) - && (childNodeMap.get(ToscaSchemaConstants.TYPE) instanceof String) - && ((String) childNodeMap.get(ToscaSchemaConstants.TYPE)) - .equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING)) { - childObject.put(JsonEditorSchemaConstants.MIN_LENGTH, constraint.getValue()); + && (childNodeMap.get(ToscaSchemaConstants.TYPE) instanceof String) + && ((String) childNodeMap.get(ToscaSchemaConstants.TYPE)) + .equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING)) { + childObject.put(JsonEditorSchemaConstants.MIN_LENGTH, + constraint.getValue()); } else { - childObject.put(JsonEditorSchemaConstants.MINIMUM, constraint.getValue()); + childObject.put(JsonEditorSchemaConstants.MINIMUM, + constraint.getValue()); } - } else if (constraint.getKey().equalsIgnoreCase(ToscaSchemaConstants.MAX_LENGTH) - || constraint.getKey().equalsIgnoreCase(ToscaSchemaConstants.LESS_OR_EQUAL)) { - // For String max_lenghth is maximum length whereas for number, it will be + } else if (constraint.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.MAX_LENGTH) + || constraint.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.LESS_OR_EQUAL)) { + // For String max_lenghth is maximum length whereas for number, it will + // be // maximum or less than the defined value if (childNodeMap.containsKey(ToscaSchemaConstants.TYPE) - && (childNodeMap.get(ToscaSchemaConstants.TYPE) instanceof String) - && ((String) childNodeMap.get(ToscaSchemaConstants.TYPE)) - .equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING)) { - childObject.put(JsonEditorSchemaConstants.MAX_LENGTH, constraint.getValue()); + && (childNodeMap.get(ToscaSchemaConstants.TYPE) instanceof String) + && ((String) childNodeMap.get(ToscaSchemaConstants.TYPE)) + .equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING)) { + childObject.put(JsonEditorSchemaConstants.MAX_LENGTH, + constraint.getValue()); } else { - childObject.put(JsonEditorSchemaConstants.MAXIMUM, constraint.getValue()); + childObject.put(JsonEditorSchemaConstants.MAXIMUM, + constraint.getValue()); } - } else if (constraint.getKey().equalsIgnoreCase(ToscaSchemaConstants.LESS_THAN)) { - childObject.put(JsonEditorSchemaConstants.EXCLUSIVE_MAXIMUM, constraint.getValue()); - } else if (constraint.getKey().equalsIgnoreCase(ToscaSchemaConstants.GREATER_THAN)) { - childObject.put(JsonEditorSchemaConstants.EXCLUSIVE_MINIMUM, constraint.getValue()); - } else if (constraint.getKey().equalsIgnoreCase(ToscaSchemaConstants.IN_RANGE)) { + } else if (constraint.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.LESS_THAN)) { + childObject.put(JsonEditorSchemaConstants.EXCLUSIVE_MAXIMUM, + constraint.getValue()); + } else if (constraint.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.GREATER_THAN)) { + childObject.put(JsonEditorSchemaConstants.EXCLUSIVE_MINIMUM, + constraint.getValue()); + } else if (constraint.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.IN_RANGE)) { if (constraint.getValue() instanceof ArrayList) { if (childNodeMap.containsKey(ToscaSchemaConstants.TYPE) - && (childNodeMap.get(ToscaSchemaConstants.TYPE) instanceof String) - && ((String) childNodeMap.get(ToscaSchemaConstants.TYPE)) - .equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING)) { + && (childNodeMap + .get(ToscaSchemaConstants.TYPE) instanceof String) + && ((String) childNodeMap.get(ToscaSchemaConstants.TYPE)) + .equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING)) { childObject.put(JsonEditorSchemaConstants.MIN_LENGTH, - ((ArrayList) constraint.getValue()).get(0)); + ((ArrayList) constraint.getValue()).get(0)); childObject.put(JsonEditorSchemaConstants.MAX_LENGTH, - ((ArrayList) constraint.getValue()).get(1)); + ((ArrayList) constraint.getValue()).get(1)); } else { childObject.put(JsonEditorSchemaConstants.MINIMUM, - ((ArrayList) constraint.getValue()).get(0)); + ((ArrayList) constraint.getValue()).get(0)); childObject.put(JsonEditorSchemaConstants.MAXIMUM, - ((ArrayList) constraint.getValue()).get(1)); + ((ArrayList) constraint.getValue()).get(1)); } } - } else if (constraint.getKey().equalsIgnoreCase(ToscaSchemaConstants.VALID_VALUES)) { + } else if (constraint.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.VALID_VALUES)) { JSONArray validValuesArray = new JSONArray(); if (constraint.getValue() instanceof ArrayList) { - boolean processDictionary = ((ArrayList) constraint.getValue()).stream() - .anyMatch(value -> (value instanceof String - && ((String) value).contains(ToscaSchemaConstants.DICTIONARY))); + boolean processDictionary = + ((ArrayList) constraint.getValue()).stream().anyMatch( + value -> (value instanceof String && ((String) value) + .contains(ToscaSchemaConstants.DICTIONARY))); if (!processDictionary) { - ((ArrayList) constraint.getValue()).stream().forEach(value -> { - validValuesArray.put(value); - }); - childObject.put(JsonEditorSchemaConstants.ENUM, validValuesArray); + ((ArrayList) constraint.getValue()).stream() + .forEach(value -> { + validValuesArray.put(value); + }); + childObject.put(JsonEditorSchemaConstants.ENUM, + validValuesArray); } else { - ((ArrayList) constraint.getValue()).stream().forEach(value -> { - if ((value instanceof String - && ((String) value).contains(ToscaSchemaConstants.DICTIONARY))) { - processDictionaryElements(childObject, (String) value); - } + ((ArrayList) constraint.getValue()).stream() + .forEach(value -> { + if ((value instanceof String && ((String) value) + .contains(ToscaSchemaConstants.DICTIONARY))) { + processDictionaryElements(childObject, + (String) value); + } - }); + }); } } @@ -464,8 +596,117 @@ public class ToscaYamlToJsonConvertor { } } + private void parseMetadataPossibleValues(LinkedHashMap childNodeMap, + JSONObject childObject) { + if (childNodeMap.containsKey(ToscaSchemaConstants.METADATA) + && childNodeMap.get(ToscaSchemaConstants.METADATA) != null) { + LinkedHashMap metadataMap = + (LinkedHashMap) childNodeMap.get(ToscaSchemaConstants.METADATA); + if (metadataMap instanceof Map) { + metadataMap.entrySet().stream().forEach(constraint -> { + if (constraint.getKey() + .equalsIgnoreCase(ToscaSchemaConstants.METADATA_CLAMP_POSSIBLE_VALUES)) { + JSONArray validValuesArray = new JSONArray(); + + if (constraint.getValue() instanceof ArrayList) { + boolean processDictionary = ((ArrayList) constraint.getValue()) + .stream().anyMatch(value -> (value instanceof String + && ((String) value).contains(ToscaSchemaConstants.DICTIONARY))); + if (processDictionary) { + ((ArrayList) constraint.getValue()).stream().forEach(value -> { + if ((value instanceof String && ((String) value) + .contains(ToscaSchemaConstants.DICTIONARY))) { + processDictionaryElements(childObject, (String) value); + } + + }); + + } + } + + } + }); + } + } + } + private void processDictionaryElements(JSONObject childObject, String dictionaryReference) { + if (dictionaryReference.contains("#")) { + String[] dictionaryKeyArray = dictionaryReference + .substring(dictionaryReference.indexOf(ToscaSchemaConstants.DICTIONARY) + 11, + dictionaryReference.length()) + .split("#"); + // We support only one # as of now. + List cldsDictionaryElements = null; + List subDictionaryElements = null; + if (dictionaryKeyArray != null && dictionaryKeyArray.length == 2) { + cldsDictionaryElements = dictionaryService.getDictionary(dictionaryKeyArray[0]) + .getDictionaryElements().stream().collect(Collectors.toList()); + subDictionaryElements = dictionaryService.getDictionary(dictionaryKeyArray[1]) + .getDictionaryElements().stream().collect(Collectors.toList()); + + if (cldsDictionaryElements != null) { + List subCldsDictionaryNames = subDictionaryElements.stream() + .map(DictionaryElement::getShortName).collect(Collectors.toList()); + JSONArray jsonArray = new JSONArray(); + + Optional.ofNullable(cldsDictionaryElements).get().stream().forEach(c -> { + JSONObject jsonObject = new JSONObject(); + jsonObject.put(JsonEditorSchemaConstants.TYPE, getJsonType(c.getType())); + if (c.getType() != null + && c.getType().equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING)) { + jsonObject.put(JsonEditorSchemaConstants.MIN_LENGTH, 1); + } + jsonObject.put(JsonEditorSchemaConstants.ID, c.getName()); + jsonObject.put(JsonEditorSchemaConstants.LABEL, c.getShortName()); + jsonObject.put(JsonEditorSchemaConstants.OPERATORS, subCldsDictionaryNames); + jsonArray.put(jsonObject); + });; + JSONObject filterObject = new JSONObject(); + filterObject.put(JsonEditorSchemaConstants.FILTERS, jsonArray); + + childObject.put(JsonEditorSchemaConstants.TYPE, + JsonEditorSchemaConstants.TYPE_QBLDR); + // TO invoke validation on such parameters + childObject.put(JsonEditorSchemaConstants.MIN_LENGTH, 1); + childObject.put(JsonEditorSchemaConstants.QSSCHEMA, filterObject); + + } + } + } else { + String dictionaryKey = dictionaryReference.substring( + dictionaryReference.indexOf(ToscaSchemaConstants.DICTIONARY) + 11, + dictionaryReference.length()); + if (dictionaryKey != null) { + List cldsDictionaryElements = + dictionaryService.getDictionary(dictionaryKey).getDictionaryElements().stream() + .collect(Collectors.toList()); + if (cldsDictionaryElements != null) { + List cldsDictionaryNames = new ArrayList<>(); + List cldsDictionaryFullNames = new ArrayList<>(); + cldsDictionaryElements.stream().forEach(c -> { + // Json type will be translated before Policy creation + if (c.getType() != null && !c.getType().equalsIgnoreCase("json")) { + cldsDictionaryFullNames.add(c.getName()); + } + cldsDictionaryNames.add(c.getShortName()); + }); + + if (!cldsDictionaryFullNames.isEmpty()) { + childObject.put(JsonEditorSchemaConstants.ENUM, cldsDictionaryFullNames); + // Add Enum titles for generated translated values during JSON instance + // generation + JSONObject enumTitles = new JSONObject(); + enumTitles.put(JsonEditorSchemaConstants.ENUM_TITLES, cldsDictionaryNames); + childObject.put(JsonEditorSchemaConstants.OPTIONS, enumTitles); + } else { + childObject.put(JsonEditorSchemaConstants.ENUM, cldsDictionaryNames); + } + + } + } + } } private String getJsonType(String toscaType) { @@ -480,4 +721,4 @@ public class ToscaYamlToJsonConvertor { return jsonType; } -} \ No newline at end of file +} diff --git a/src/main/java/org/onap/clamp/loop/template/LoopElementModel.java b/src/main/java/org/onap/clamp/loop/template/LoopElementModel.java index 0a0831bb..e6ba9815 100644 --- a/src/main/java/org/onap/clamp/loop/template/LoopElementModel.java +++ b/src/main/java/org/onap/clamp/loop/template/LoopElementModel.java @@ -24,13 +24,11 @@ package org.onap.clamp.loop.template; import com.google.gson.annotations.Expose; - import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; - import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -41,7 +39,6 @@ import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; - import org.hibernate.annotations.SortNatural; import org.onap.clamp.loop.common.AuditEntity; @@ -79,16 +76,27 @@ public class LoopElementModel extends AuditEntity implements Serializable { @Column(nullable = false, name = "loop_element_type") private String loopElementType; + /** + * This variable is used to display the micro-service name in the SVG. + */ + @Expose + @Column(name = "short_name") + private String shortName; + /** * This variable is used to store the type mentioned in the micro-service * blueprint. */ @Expose - @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH }) - @JoinTable(name = "loopelementmodels_to_policymodels", - joinColumns = @JoinColumn(name = "loop_element_name", referencedColumnName = "name"), - inverseJoinColumns = { @JoinColumn(name = "policy_model_type", referencedColumnName = "policy_model_type"), - @JoinColumn(name = "policy_model_version", referencedColumnName = "version") }) + @ManyToMany( + fetch = FetchType.EAGER, + cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) + @JoinTable( + name = "loopelementmodels_to_policymodels", + joinColumns = @JoinColumn(name = "loop_element_name", referencedColumnName = "name"), + inverseJoinColumns = { + @JoinColumn(name = "policy_model_type", referencedColumnName = "policy_model_type"), + @JoinColumn(name = "policy_model_version", referencedColumnName = "version")}) @SortNatural private SortedSet policyModels = new TreeSet<>(); @@ -97,7 +105,7 @@ public class LoopElementModel extends AuditEntity implements Serializable { /** * policyModels getter. - * + * * @return the policyModel */ public SortedSet getPolicyModels() { @@ -106,7 +114,7 @@ public class LoopElementModel extends AuditEntity implements Serializable { /** * Method to add a new policyModel to the list. - * + * * @param policyModel The policy model */ public void addPolicyModel(PolicyModel policyModel) { @@ -116,7 +124,7 @@ public class LoopElementModel extends AuditEntity implements Serializable { /** * name getter. - * + * * @return the name */ public String getName() { @@ -125,7 +133,7 @@ public class LoopElementModel extends AuditEntity implements Serializable { /** * name setter. - * + * * @param name the name to set */ public void setName(String name) { @@ -134,7 +142,7 @@ public class LoopElementModel extends AuditEntity implements Serializable { /** * blueprint getter. - * + * * @return the blueprint */ public String getBlueprint() { @@ -143,7 +151,7 @@ public class LoopElementModel extends AuditEntity implements Serializable { /** * blueprint setter. - * + * * @param blueprint the blueprint to set */ public void setBlueprint(String blueprint) { @@ -151,10 +159,8 @@ public class LoopElementModel extends AuditEntity implements Serializable { } /** - * loopElementType getter. - * * dcaeBlueprintId getter. - * + * * @return the dcaeBlueprintId */ public String getDcaeBlueprintId() { @@ -163,7 +169,7 @@ public class LoopElementModel extends AuditEntity implements Serializable { /** * dcaeBlueprintId setter. - * + * * @param dcaeBlueprintId the dcaeBlueprintId to set */ public void setDcaeBlueprintId(String dcaeBlueprintId) { @@ -171,6 +177,8 @@ public class LoopElementModel extends AuditEntity implements Serializable { } /** + * loopElementType getter. + * * @return the loopElementType */ public String getLoopElementType() { @@ -179,16 +187,32 @@ public class LoopElementModel extends AuditEntity implements Serializable { /** * loopElementType setter. - * + * * @param loopElementType the loopElementType to set */ public void setLoopElementType(String loopElementType) { this.loopElementType = loopElementType; } + /** + * shortName getter. + * + * @return the shortName + */ + public String getShortName() { + return shortName; + } + + /** + * @param shortName the shortName to set. + */ + public void setShortName(String shortName) { + this.shortName = shortName; + } + /** * usedByLoopTemplates getter. - * + * * @return the usedByLoopTemplates */ public Set getUsedByLoopTemplates() { @@ -203,11 +227,11 @@ public class LoopElementModel extends AuditEntity implements Serializable { /** * Constructor. - * - * @param name The name id + * + * @param name The name id * @param loopElementType The type of loop element - * @param blueprint The blueprint defined for dcae that contains the - * policy type to use + * @param blueprint The blueprint defined for dcae that contains the + * policy type to use */ public LoopElementModel(String name, String loopElementType, String blueprint) { this.name = name; diff --git a/src/main/java/org/onap/clamp/loop/template/LoopTemplate.java b/src/main/java/org/onap/clamp/loop/template/LoopTemplate.java index 3e90c1e5..54096cb8 100644 --- a/src/main/java/org/onap/clamp/loop/template/LoopTemplate.java +++ b/src/main/java/org/onap/clamp/loop/template/LoopTemplate.java @@ -24,14 +24,13 @@ package org.onap.clamp.loop.template; import com.google.gson.annotations.Expose; - import java.io.Serializable; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; - import javax.persistence.CascadeType; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; @@ -39,7 +38,6 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; - import org.hibernate.annotations.SortNatural; import org.onap.clamp.loop.common.AuditEntity; import org.onap.clamp.loop.service.Service; @@ -74,12 +72,18 @@ public class LoopTemplate extends AuditEntity implements Serializable { private String svgRepresentation; @Expose - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "loopTemplate", orphanRemoval = true) + @OneToMany( + cascade = CascadeType.ALL, + fetch = FetchType.EAGER, + mappedBy = "loopTemplate", + orphanRemoval = true) @SortNatural private SortedSet loopElementModelsUsed = new TreeSet<>(); @Expose - @ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH }) + @ManyToOne( + fetch = FetchType.EAGER, + cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) @JoinColumn(name = "service_uuid") private Service modelService; @@ -91,9 +95,17 @@ public class LoopTemplate extends AuditEntity implements Serializable { @Column(name = "unique_blueprint", columnDefinition = "boolean default false") private boolean uniqueBlueprint; + /** + * Type of Loop allowed to be created. + */ + @Expose + @Column(name = "allowed_loop_type") + @Convert(converter = LoopTypeConvertor.class) + private LoopType allowedLoopType = LoopType.CLOSED; + /** * name getter. - * + * * @return the name */ public String getName() { @@ -102,7 +114,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * name setter. - * + * * @param name the name to set */ public void setName(String name) { @@ -111,7 +123,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * blueprint getter. - * + * * @return the blueprint */ public String getBlueprint() { @@ -120,7 +132,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * dcaeBlueprintId getter. - * + * * @return the dcaeBlueprintId */ public String getDcaeBlueprintId() { @@ -129,7 +141,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * dcaeBlueprintId setter. - * + * * @param dcaeBlueprintId the dcaeBlueprintId to set */ public void setDcaeBlueprintId(String dcaeBlueprintId) { @@ -138,7 +150,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * blueprint setter. - * + * * @param blueprint the blueprint to set */ public void setBlueprint(String blueprint) { @@ -152,7 +164,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * svgRepresentation getter. - * + * * @return the svgRepresentation */ public String getSvgRepresentation() { @@ -161,7 +173,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * svgRepresentation setter. - * + * * @param svgRepresentation the svgRepresentation to set */ public void setSvgRepresentation(String svgRepresentation) { @@ -170,7 +182,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * loopElementModelsUsed getter. - * + * * @return the loopElementModelsUsed */ public SortedSet getLoopElementModelsUsed() { @@ -179,7 +191,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * maximumInstancesAllowed getter. - * + * * @return the maximumInstancesAllowed */ public Integer getMaximumInstancesAllowed() { @@ -188,17 +200,35 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * maximumInstancesAllowed setter. - * + * * @param maximumInstancesAllowed the maximumInstancesAllowed to set */ public void setMaximumInstancesAllowed(Integer maximumInstancesAllowed) { this.maximumInstancesAllowed = maximumInstancesAllowed; } + /** + * allowedLoopType getter. + * + * @return the allowedLoopType Type of Loop allowed to be created + */ + public LoopType getAllowedLoopType() { + return allowedLoopType; + } + + /** + * allowedLoopType setter. + * + * @param allowedLoopType the allowedLoopType to set + */ + public void setAllowedLoopType(LoopType allowedLoopType) { + this.allowedLoopType = allowedLoopType; + } + /** * Add list of loopElements to the current template, each loopElementModel is * added at the end of the list so the flowOrder is computed automatically. - * + * * @param loopElementModels The loopElementModel set to add */ public void addLoopElementModels(Set loopElementModels) { @@ -210,12 +240,12 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * Add a loopElement to the current template, the loopElementModel is added at * the end of the list so the flowOrder is computed automatically. - * + * * @param loopElementModel The loopElementModel to add */ public void addLoopElementModel(LoopElementModel loopElementModel) { - LoopTemplateLoopElementModel jointEntry = new LoopTemplateLoopElementModel(this, loopElementModel, - this.loopElementModelsUsed.size()); + LoopTemplateLoopElementModel jointEntry = new LoopTemplateLoopElementModel(this, + loopElementModel, this.loopElementModelsUsed.size()); this.loopElementModelsUsed.add(jointEntry); loopElementModel.getUsedByLoopTemplates().add(jointEntry); } @@ -223,20 +253,20 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * Add a loopElement model to the current template, the flow order must be * specified manually. - * + * * @param loopElementModel The loopElementModel to add - * @param listPosition The position in the flow + * @param listPosition The position in the flow */ public void addLoopElementModel(LoopElementModel loopElementModel, Integer listPosition) { - LoopTemplateLoopElementModel jointEntry = new LoopTemplateLoopElementModel(this, loopElementModel, - listPosition); + LoopTemplateLoopElementModel jointEntry = + new LoopTemplateLoopElementModel(this, loopElementModel, listPosition); this.loopElementModelsUsed.add(jointEntry); loopElementModel.getUsedByLoopTemplates().add(jointEntry); } /** * modelService getter. - * + * * @return the modelService */ public Service getModelService() { @@ -245,7 +275,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * modelService setter. - * + * * @param modelService the modelService to set */ public void setModelService(Service modelService) { @@ -254,7 +284,7 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * uniqueBlueprint getter. - * + * * @return the uniqueBlueprint */ public boolean getUniqueBlueprint() { @@ -270,17 +300,17 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * Constructor. - * - * @param name The loop template name id - * @param blueprint The blueprint containing all microservices (legacy - * case) - * @param svgRepresentation The svg representation of that loop template + * + * @param name The loop template name id + * @param blueprint The blueprint containing all microservices (legacy + * case) + * @param svgRepresentation The svg representation of that loop template * @param maxInstancesAllowed The maximum number of instances that can be - * created from that template - * @param service The service associated to that loop template + * created from that template + * @param service The service associated to that loop template */ - public LoopTemplate(String name, String blueprint, String svgRepresentation, Integer maxInstancesAllowed, - Service service) { + public LoopTemplate(String name, String blueprint, String svgRepresentation, + Integer maxInstancesAllowed, Service service) { this.name = name; this.setBlueprint(blueprint); this.svgRepresentation = svgRepresentation; @@ -322,17 +352,17 @@ public class LoopTemplate extends AuditEntity implements Serializable { /** * Generate the loop template name. * - * @param serviceName The service name - * @param serviceVersion The service version - * @param resourceName The resource name + * @param serviceName The service name + * @param serviceVersion The service version + * @param resourceName The resource name * @param blueprintFileName The blueprint file name * @return The generated loop template name */ - public static String generateLoopTemplateName(String serviceName, String serviceVersion, String resourceName, - String blueprintFileName) { + public static String generateLoopTemplateName(String serviceName, String serviceVersion, + String resourceName, String blueprintFileName) { StringBuilder buffer = new StringBuilder("LOOP_TEMPLATE_").append(serviceName).append("_v") - .append(serviceVersion).append("_").append(resourceName).append("_") - .append(blueprintFileName.replaceAll(".yaml", "")); + .append(serviceVersion).append("_").append(resourceName).append("_") + .append(blueprintFileName.replaceAll(".yaml", "")); return buffer.toString().replace('.', '_').replaceAll(" ", ""); } } diff --git a/src/main/java/org/onap/clamp/loop/template/LoopTemplateLoopElementModelId.java b/src/main/java/org/onap/clamp/loop/template/LoopTemplateLoopElementModelId.java index 3e2f8ad4..cac5f088 100644 --- a/src/main/java/org/onap/clamp/loop/template/LoopTemplateLoopElementModelId.java +++ b/src/main/java/org/onap/clamp/loop/template/LoopTemplateLoopElementModelId.java @@ -24,9 +24,7 @@ package org.onap.clamp.loop.template; import com.google.gson.annotations.Expose; - import java.io.Serializable; - import javax.persistence.Column; import javax.persistence.Embeddable; @@ -55,8 +53,8 @@ public class LoopTemplateLoopElementModelId implements Serializable { /** * Constructor. - * - * @param loopTemplateName The loop template name id + * + * @param loopTemplateName The loop template name id * @param microServiceModelName THe micro Service name id */ public LoopTemplateLoopElementModelId(String loopTemplateName, String microServiceModelName) { @@ -66,7 +64,7 @@ public class LoopTemplateLoopElementModelId implements Serializable { /** * loopTemplateName getter. - * + * * @return the loopTemplateName */ public String getLoopTemplateName() { @@ -75,7 +73,7 @@ public class LoopTemplateLoopElementModelId implements Serializable { /** * loopTemplateName setter. - * + * * @param loopTemplateName the loopTemplateName to set */ public void setLoopTemplateName(String loopTemplateName) { @@ -84,7 +82,7 @@ public class LoopTemplateLoopElementModelId implements Serializable { /** * microServiceModelName getter. - * + * * @return the microServiceModelName */ public String getLoopElementModelName() { @@ -93,7 +91,7 @@ public class LoopTemplateLoopElementModelId implements Serializable { /** * loopElementModelName setter. - * + * * @param loopElementModelName the loopElementModelName to set */ public void setLoopElementModelName(String loopElementModelName) { diff --git a/src/main/java/org/onap/clamp/loop/template/LoopTemplatesService.java b/src/main/java/org/onap/clamp/loop/template/LoopTemplatesService.java new file mode 100644 index 00000000..279d602c --- /dev/null +++ b/src/main/java/org/onap/clamp/loop/template/LoopTemplatesService.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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.loop.template; + +import java.util.List; +import org.onap.clamp.clds.exception.sdc.controller.BlueprintParserException; +import org.onap.clamp.clds.sdc.controller.installer.BlueprintMicroService; +import org.onap.clamp.clds.sdc.controller.installer.BlueprintParser; +import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator; +import org.onap.clamp.clds.util.drawing.SvgFacade; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class LoopTemplatesService { + + private final LoopTemplatesRepository loopTemplatesRepository; + + @Autowired + ChainGenerator chainGenerator; + + @Autowired + private SvgFacade svgFacade; + + /** + * Constructor. + */ + @Autowired + public LoopTemplatesService(LoopTemplatesRepository loopTemplatesRepository) { + this.loopTemplatesRepository = loopTemplatesRepository; + + } + + public LoopTemplate saveOrUpdateLoopTemplate(LoopTemplate loopTemplate) { + return loopTemplatesRepository.save(loopTemplate); + } + + /** + * Saves or updates loop template Object. + * + * @param templateName the loop template name + * @param loopTemplate the loop template object + * @return the loop template + * @throws BlueprintParserException In case of issues with the blueprint + * parsing + */ + public LoopTemplate saveOrUpdateLoopTemplateByName(String templateName, + LoopTemplate loopTemplate) throws BlueprintParserException { + + if (getLoopTemplate(templateName) != null) { + loopTemplate.setName(getLoopTemplate(templateName).getName()); + } + return saveOrUpdateLoopTemplate(createTemplateFromBlueprint(templateName, loopTemplate)); + } + + public List getLoopTemplateNames() { + return loopTemplatesRepository.getAllLoopTemplateNames(); + } + + public List getAllLoopTemplates() { + return loopTemplatesRepository.findAll(); + } + + public LoopTemplate getLoopTemplate(String name) { + return loopTemplatesRepository.findById(name).orElse(null); + } + + public void deleteLoopTemplate(String name) { + loopTemplatesRepository.deleteById(name); + } + + private LoopTemplate createTemplateFromBlueprint(String templateName, LoopTemplate loopTemplate) + throws BlueprintParserException { + + String blueprintYaml = loopTemplate.getBlueprint(); + List microServicesChain = + chainGenerator.getChainOfMicroServices(BlueprintParser.getMicroServices(blueprintYaml)); + if (microServicesChain.isEmpty()) { + microServicesChain = BlueprintParser.fallbackToOneMicroService(); + } + loopTemplate.setSvgRepresentation(svgFacade.getSvgImage(microServicesChain)); + loopTemplate.setName(templateName); + + LoopTemplate existingTemplate = getLoopTemplate(templateName); + if (existingTemplate != null) { + loopTemplate.setName(existingTemplate.getName()); + } + return loopTemplate; + } +} diff --git a/src/main/java/org/onap/clamp/loop/template/LoopType.java b/src/main/java/org/onap/clamp/loop/template/LoopType.java new file mode 100644 index 00000000..ccbc62a8 --- /dev/null +++ b/src/main/java/org/onap/clamp/loop/template/LoopType.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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.loop.template; + +/** + * Enums for AllowedLoopType in LoopTemplate enity. + * + */ +public enum LoopType { + OPEN("OPEN"), CLOSED("CLOSED"), HYBRID("HYBRID"); + + private String value; + + private LoopType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/src/main/java/org/onap/clamp/loop/template/LoopTypeConvertor.java b/src/main/java/org/onap/clamp/loop/template/LoopTypeConvertor.java new file mode 100644 index 00000000..0b05613c --- /dev/null +++ b/src/main/java/org/onap/clamp/loop/template/LoopTypeConvertor.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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.loop.template; + +import java.util.stream.Stream; +import javax.persistence.AttributeConverter; + +/** + * Attribute Converter to allow using LoopType Enum values in DB and Java classes. + * + */ +public class LoopTypeConvertor implements AttributeConverter { + + @Override + public String convertToDatabaseColumn(LoopType loopType) { + if (loopType == null) { + return null; + } + return loopType.getValue(); + } + + @Override + public LoopType convertToEntityAttribute(String value) { + if (value == null) { + return null; + } + + return Stream.of(LoopType.values()).filter(c -> c.getValue().equals(value)).findFirst() + .orElseThrow(IllegalArgumentException::new); + } +} diff --git a/src/main/java/org/onap/clamp/loop/template/PolicyModel.java b/src/main/java/org/onap/clamp/loop/template/PolicyModel.java index 52f662bb..d06cb8cf 100644 --- a/src/main/java/org/onap/clamp/loop/template/PolicyModel.java +++ b/src/main/java/org/onap/clamp/loop/template/PolicyModel.java @@ -24,11 +24,9 @@ package org.onap.clamp.loop.template; import com.google.gson.annotations.Expose; - import java.io.Serializable; import java.util.HashSet; import java.util.Set; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; @@ -36,7 +34,6 @@ import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.ManyToMany; import javax.persistence.Table; - import org.onap.clamp.loop.common.AuditEntity; import org.onap.clamp.util.SemanticVersioning; @@ -83,7 +80,7 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * usedByElementModels getter. - * + * * @return the usedByElementModels */ public Set getUsedByElementModels() { @@ -92,7 +89,7 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * policyModelTosca getter. - * + * * @return the policyModelTosca */ public String getPolicyModelTosca() { @@ -101,7 +98,7 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * policyModelTosca setter. - * + * * @param policyModelTosca the policyModelTosca to set */ public void setPolicyModelTosca(String policyModelTosca) { @@ -110,7 +107,7 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * policyModelType getter. - * + * * @return the modelType */ public String getPolicyModelType() { @@ -119,7 +116,7 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * policyModelType setter. - * + * * @param modelType the modelType to set */ public void setPolicyModelType(String modelType) { @@ -128,7 +125,7 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * version getter. - * + * * @return the version */ public String getVersion() { @@ -137,7 +134,7 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * version setter. - * + * * @param version the version to set */ public void setVersion(String version) { @@ -147,7 +144,7 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * policyAcronym getter. - * + * * @return the policyAcronym value */ public String getPolicyAcronym() { @@ -156,7 +153,7 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * policyAcronym setter. - * + * * @param policyAcronym The policyAcronym to set */ public void setPolicyAcronym(String policyAcronym) { @@ -171,13 +168,14 @@ public class PolicyModel extends AuditEntity implements Serializable, Comparable /** * Constructor. - * - * @param policyType The policyType (referenced in the blueprint + * + * @param policyType The policyType (referenced in the blueprint * @param policyModelTosca The policy tosca model in yaml - * @param version the version like 1.0.0 - * @param policyAcronym Subtype for policy if it exists (could be used by UI) + * @param version the version like 1.0.0 + * @param policyAcronym Subtype for policy if it exists (could be used by UI) */ - public PolicyModel(String policyType, String policyModelTosca, String version, String policyAcronym) { + public PolicyModel(String policyType, String policyModelTosca, String version, + String policyAcronym) { this.policyModelType = policyType; this.policyModelTosca = policyModelTosca; this.version = version; diff --git a/src/main/java/org/onap/clamp/loop/template/PolicyModelsService.java b/src/main/java/org/onap/clamp/loop/template/PolicyModelsService.java index 8e22852a..0a09dd8d 100644 --- a/src/main/java/org/onap/clamp/loop/template/PolicyModelsService.java +++ b/src/main/java/org/onap/clamp/loop/template/PolicyModelsService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights + * Copyright (C) 2020 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,24 +23,62 @@ package org.onap.clamp.loop.template; +import com.google.gson.JsonObject; import java.util.List; - +import org.onap.clamp.clds.tosca.ToscaSchemaConstants; +import org.onap.clamp.clds.tosca.ToscaYamlToJsonConvertor; +import org.onap.clamp.util.SemanticVersioning; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PolicyModelsService { private final PolicyModelsRepository policyModelsRepository; + private ToscaYamlToJsonConvertor toscaYamlToJsonConvertor; @Autowired - public PolicyModelsService(PolicyModelsRepository policyModelrepo) { + public PolicyModelsService(PolicyModelsRepository policyModelrepo, + ToscaYamlToJsonConvertor convertor) { policyModelsRepository = policyModelrepo; + toscaYamlToJsonConvertor = convertor; } public PolicyModel saveOrUpdatePolicyModel(PolicyModel policyModel) { return policyModelsRepository.save(policyModel); } + /** + * Creates or updates the Tosca Policy Model. + * + * @param policyModelType + * The policyModeltype in Tosca yaml + * @param policyModel + * The Policymodel object + * @return The Policy Model + */ + public PolicyModel saveOrUpdateByPolicyModelType(String policyModelType, + String policyModelTosca) { + JsonObject jsonObject = toscaYamlToJsonConvertor.validateAndConvertToJson(policyModelTosca); + + String policyModelTypeName = toscaYamlToJsonConvertor.getValueFromMetadata(jsonObject, + ToscaSchemaConstants.METADATA_POLICY_MODEL_TYPE); + String acronym = toscaYamlToJsonConvertor.getValueFromMetadata(jsonObject, + ToscaSchemaConstants.METADATA_ACRONYM); + PolicyModel model = getPolicyModelByType( + policyModelTypeName != null ? policyModelTypeName : policyModelType); + + if (model == null) { + model = new PolicyModel(policyModelTypeName, policyModelTosca, + SemanticVersioning.incrementMajorVersion(null), acronym); + } else { + model.setVersion(SemanticVersioning + .incrementMajorVersion(model.getVersion() != null ? model.getVersion() : null)); + model.setPolicyModelType(policyModelTypeName); + model.setPolicyAcronym(acronym); + } + return saveOrUpdatePolicyModel(model); + } + public List getAllPolicyModelTypes() { return policyModelsRepository.getAllPolicyModelType(); } @@ -56,4 +94,20 @@ public class PolicyModelsService { public Iterable getAllPolicyModelsByType(String type) { return policyModelsRepository.findByPolicyModelType(type); } + + public PolicyModel getPolicyModelByType(String type) { + List list = policyModelsRepository.findByPolicyModelType(type); + return list.stream().sorted().findFirst().orElse(null); + } + + /** + * Retrieves the Tosca model Yaml string. + * + * @param type The PolicyModelType + * @return The Tosca model Yaml string + */ + public String getPolicyModelTosca(String type) { + PolicyModel policyModel = getPolicyModelByType(type); + return policyModel != null ? policyModel.getPolicyModelTosca() : null; + } } diff --git a/src/main/java/org/onap/clamp/tosca/Dictionary.java b/src/main/java/org/onap/clamp/tosca/Dictionary.java index 7b4e513a..44b5b6f6 100644 --- a/src/main/java/org/onap/clamp/tosca/Dictionary.java +++ b/src/main/java/org/onap/clamp/tosca/Dictionary.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights + * Copyright (C) 2020 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,19 +24,18 @@ package org.onap.clamp.tosca; import com.google.gson.annotations.Expose; - import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - +import java.util.HashSet; +import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; -import javax.persistence.OneToMany; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; import javax.persistence.Table; - import org.onap.clamp.loop.common.AuditEntity; /** @@ -59,19 +58,27 @@ public class Dictionary extends AuditEntity implements Serializable { @Expose @Column(name = "dictionary_second_level") - private int secondLevelDictionary; + private int secondLevelDictionary = 0; @Expose @Column(name = "dictionary_type") private String subDictionaryType; @Expose - @OneToMany(mappedBy = "dictionary", cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private List dictionaryElements = new ArrayList<>(); + @ManyToMany( + fetch = FetchType.EAGER, + cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) + @JoinTable( + name = "dictionary_to_dictionaryelements", + joinColumns = @JoinColumn(name = "dictionary_name", referencedColumnName = "name"), + inverseJoinColumns = {@JoinColumn( + name = "dictionary_element_short_name", + referencedColumnName = "short_name")}) + private Set dictionaryElements = new HashSet<>(); /** * name getter. - * + * * @return the name */ public String getName() { @@ -80,7 +87,7 @@ public class Dictionary extends AuditEntity implements Serializable { /** * name setter. - * + * * @param name the name to set */ public void setName(String name) { @@ -89,7 +96,7 @@ public class Dictionary extends AuditEntity implements Serializable { /** * secondLevelDictionary getter. - * + * * @return the secondLevelDictionary */ public int getSecondLevelDictionary() { @@ -98,7 +105,7 @@ public class Dictionary extends AuditEntity implements Serializable { /** * secondLevelDictionary setter. - * + * * @param secondLevelDictionary the secondLevelDictionary to set */ public void setSecondLevelDictionary(int secondLevelDictionary) { @@ -107,7 +114,7 @@ public class Dictionary extends AuditEntity implements Serializable { /** * subDictionaryType getter. - * + * * @return the subDictionaryType */ public String getSubDictionaryType() { @@ -116,7 +123,7 @@ public class Dictionary extends AuditEntity implements Serializable { /** * subDictionaryType setter. - * + * * @param subDictionaryType the subDictionaryType to set */ public void setSubDictionaryType(String subDictionaryType) { @@ -125,20 +132,51 @@ public class Dictionary extends AuditEntity implements Serializable { /** * dictionaryElements getter. - * - * @return the dictionaryElements + * + * @return the dictionaryElements List of dictionary element */ - public List getDictionaryElements() { + public Set getDictionaryElements() { return dictionaryElements; } /** - * dictionaryElements setter. - * - * @param dictionaryElements the dictionaryElements to set + * Method to add a new dictionaryElement to the list. + * + * @param dictionaryElement The dictionary element + */ + public void addDictionaryElements(DictionaryElement dictionaryElement) { + dictionaryElements.add(dictionaryElement); + dictionaryElement.getUsedByDictionaries().add(this); + } + + /** + * Method to delete a dictionaryElement from the list. + * + * @param dictionaryElement The dictionary element */ - public void setDictionaryElements(List dictionaryElements) { - this.dictionaryElements = dictionaryElements; + public void removeDictionaryElement(DictionaryElement dictionaryElement) { + dictionaryElements.remove(dictionaryElement); + dictionaryElement.getUsedByDictionaries().remove(this); + } + + /** + * Default Constructor. + */ + public Dictionary() { + + } + + /** + * Constructor. + * + * @param name The Dictionary name + * @param secondLevelDictionary defines if dictionary is a secondary level + * @param subDictionaryType defines the type of secondary level dictionary + */ + public Dictionary(String name, int secondLevelDictionary, String subDictionaryType) { + this.name = name; + this.secondLevelDictionary = secondLevelDictionary; + this.subDictionaryType = subDictionaryType; } @Override diff --git a/src/main/java/org/onap/clamp/tosca/DictionaryElement.java b/src/main/java/org/onap/clamp/tosca/DictionaryElement.java index e81885f3..43a3106f 100644 --- a/src/main/java/org/onap/clamp/tosca/DictionaryElement.java +++ b/src/main/java/org/onap/clamp/tosca/DictionaryElement.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights + * Copyright (C) 2020 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,17 +24,15 @@ package org.onap.clamp.tosca; import com.google.gson.annotations.Expose; - import java.io.Serializable; - -import javax.persistence.CascadeType; +import java.util.HashSet; +import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.FetchType; import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; +import javax.persistence.ManyToMany; import javax.persistence.Table; - import org.onap.clamp.loop.common.AuditEntity; /** @@ -51,32 +49,31 @@ public class DictionaryElement extends AuditEntity implements Serializable { @Id @Expose - @Column(nullable = false, name = "name", unique = true) - private String name; + @Column(nullable = false, name = "short_name") + private String shortName; @Expose - @Column(nullable = false, name = "short_name", unique = true) - private String shortName; + @Column(nullable = false, name = "name") + private String name; @Expose - @Column(name = "description") + @Column(nullable = false, name = "description") private String description; @Expose @Column(nullable = false, name = "type") private String type; - @Column(name = "subdictionary_id", nullable = false) @Expose + @Column(nullable = true, name = "subdictionary_name") private String subDictionary; - @ManyToOne(cascade = CascadeType.ALL) - @JoinColumn(name = "dictionary_id") - private Dictionary dictionary; + @ManyToMany(mappedBy = "dictionaryElements", fetch = FetchType.EAGER) + private Set usedByDictionaries = new HashSet<>(); /** * name getter. - * + * * @return the name */ public String getName() { @@ -85,7 +82,7 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * name setter. - * + * * @param name the name to set */ public void setName(String name) { @@ -94,7 +91,7 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * shortName getter. - * + * * @return the shortName */ public String getShortName() { @@ -103,7 +100,7 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * shortName setter. - * + * * @param shortName the shortName to set */ public void setShortName(String shortName) { @@ -112,7 +109,7 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * description getter. - * + * * @return the description */ public String getDescription() { @@ -121,7 +118,7 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * description setter. - * + * * @param description the description to set */ public void setDescription(String description) { @@ -130,7 +127,7 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * type getter. - * + * * @return the type */ public String getType() { @@ -139,7 +136,7 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * type setter. - * + * * @param type the type to set */ public void setType(String type) { @@ -148,7 +145,7 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * subDictionary getter. - * + * * @return the subDictionary */ public String getSubDictionary() { @@ -157,7 +154,7 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * subDictionary setter. - * + * * @param subDictionary the subDictionary to set */ public void setSubDictionary(String subDictionary) { @@ -165,21 +162,21 @@ public class DictionaryElement extends AuditEntity implements Serializable { } /** - * dictionary getter. - * - * @return the dictionary + * usedByDictionaries getter. + * + * @return the usedByDictionaries */ - public Dictionary getDictionary() { - return dictionary; + public Set getUsedByDictionaries() { + return usedByDictionaries; } /** - * dictionary setter. - * - * @param dictionary the dictionary to set + * usedByDictionaries setter. + * + * @param usedByDictionaries the usedByDictionaries to set */ - public void setDictionary(Dictionary dictionary) { - this.dictionary = dictionary; + public void setUsedByDictionaries(Set usedByDictionaries) { + this.usedByDictionaries = usedByDictionaries; } /** @@ -190,30 +187,46 @@ public class DictionaryElement extends AuditEntity implements Serializable { /** * Constructor. - * - * @param name The Dictionary element name - * @param shortName The short name - * @param description The description - * @param type The type of element + * + * @param name The Dictionary element name + * @param shortName The short name + * @param description The description + * @param type The type of element * @param subDictionary The sub type - * @param dictionary The parent dictionary */ - public DictionaryElement(String name, String shortName, String description, String type, String subDictionary, - Dictionary dictionary) { + public DictionaryElement(String name, String shortName, String description, String type, + String subDictionary) { this.name = name; this.shortName = shortName; this.description = description; this.type = type; this.subDictionary = subDictionary; - this.dictionary = dictionary; + } + + /** + * Constructor. + * + * @param name The Dictionary element name + * @param shortName The short name + * @param description The description + * @param type The type of element + * @param subDictionary The sub type + */ + public DictionaryElement(String name, String shortName, String description, String type, + String subDictionary, Set usedByDictionaries) { + this.name = name; + this.shortName = shortName; + this.description = description; + this.type = type; + this.subDictionary = subDictionary; + this.usedByDictionaries = usedByDictionaries; } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((dictionary == null) ? 0 : dictionary.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((shortName == null) ? 0 : shortName.hashCode()); return result; } @@ -229,21 +242,13 @@ public class DictionaryElement extends AuditEntity implements Serializable { return false; } DictionaryElement other = (DictionaryElement) obj; - if (dictionary == null) { - if (other.dictionary != null) { + if (shortName == null) { + if (other.shortName != null) { return false; } - } else if (!dictionary.equals(other.dictionary)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { + } else if (!shortName.equals(other.shortName)) { return false; } return true; } - } diff --git a/src/main/java/org/onap/clamp/tosca/DictionaryElementsRepository.java b/src/main/java/org/onap/clamp/tosca/DictionaryElementsRepository.java index 96cb2e35..43f6f1d4 100644 --- a/src/main/java/org/onap/clamp/tosca/DictionaryElementsRepository.java +++ b/src/main/java/org/onap/clamp/tosca/DictionaryElementsRepository.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights + * Copyright (C) 2020 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/src/main/java/org/onap/clamp/tosca/DictionaryRepository.java b/src/main/java/org/onap/clamp/tosca/DictionaryRepository.java index 2a087b6d..ae8430d9 100644 --- a/src/main/java/org/onap/clamp/tosca/DictionaryRepository.java +++ b/src/main/java/org/onap/clamp/tosca/DictionaryRepository.java @@ -24,7 +24,6 @@ package org.onap.clamp.tosca; import java.util.List; - import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @@ -35,4 +34,7 @@ public interface DictionaryRepository extends JpaRepository @Query("SELECT dict.name FROM Dictionary as dict") List getAllDictionaryNames(); + @Query("SELECT dict.name FROM Dictionary as dict where dict.secondLevelDictionary = 1") + List getAllSecondaryLevelDictionaryNames(); + } diff --git a/src/main/java/org/onap/clamp/tosca/DictionaryService.java b/src/main/java/org/onap/clamp/tosca/DictionaryService.java new file mode 100644 index 00000000..21ca1f7f --- /dev/null +++ b/src/main/java/org/onap/clamp/tosca/DictionaryService.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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.tosca; + +import com.google.common.collect.Sets; +import java.util.List; +import java.util.Set; +import javax.persistence.EntityNotFoundException; +import org.onap.clamp.clds.service.SecureServiceBase; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class DictionaryService extends SecureServiceBase { + + private final DictionaryRepository dictionaryRepository; + private final DictionaryElementsRepository dictionaryElementsRepository; + + /** + * Constructor. + */ + @Autowired + public DictionaryService(DictionaryRepository dictionaryRepository, + DictionaryElementsRepository dictionaryElementsRepository) { + this.dictionaryRepository = dictionaryRepository; + this.dictionaryElementsRepository = dictionaryElementsRepository; + + } + + public Dictionary saveOrUpdateDictionary(Dictionary dictionary) { + return dictionaryRepository.save(dictionary); + } + + /** + * Creates or Updates Dictionary Element. + * + * @param dictionaryName The Dictionary name + * @param dictionary The Dictionary object with dictionary elements + * @return updated Dictionary object with all dictionary elements + */ + public Dictionary saveOrUpdateDictionaryElement(String dictionaryName, Dictionary dictionary) { + Dictionary dict = getDictionary(dictionaryName); + + Set newDictionaryElements = dictionary.getDictionaryElements(); + + for (DictionaryElement dictionaryElement : newDictionaryElements) { + if (dict.getDictionaryElements().contains(dictionaryElement)) { + // Update the Dictionary Element + getAndUpdateDictionaryElement(dict, dictionaryElement); + } else { + // Create the Dictionary Element + dict.addDictionaryElements(getAndUpdateDictionaryElement(dict, dictionaryElement)); + dictionaryRepository.save(dict); + } + } + + // Fetch again to get Dictionary with most recent updates. + return dictionaryRepository.findById(dictionaryName).orElseThrow( + () -> new EntityNotFoundException("Couldn't find Dictionary named: " + dictionaryName)); + + } + + private DictionaryElement getAndUpdateDictionaryElement(Dictionary dictionary, + DictionaryElement element) { + return dictionaryElementsRepository + .save(dictionaryElementsRepository.findById(element.getShortName()) + .map(p -> updateDictionaryElement(p, element, dictionary)) + .orElse(new DictionaryElement(element.getName(), element.getShortName(), + element.getDescription(), element.getType(), element.getSubDictionary(), + Sets.newHashSet(dictionary)))); + } + + public void deleteDictionary(Dictionary dictionary) { + dictionaryRepository.delete(dictionary); + } + + public void deleteDictionary(String dictionaryName) { + dictionaryRepository.deleteById(dictionaryName); + } + + public List getAllDictionaries() { + return dictionaryRepository.findAll(); + } + + public List getAllSecondaryLevelDictionaryNames() { + return dictionaryRepository.getAllSecondaryLevelDictionaryNames(); + } + + public Dictionary getDictionary(String dictionaryName) { + return dictionaryRepository.findById(dictionaryName).orElseThrow( + () -> new EntityNotFoundException("Couldn't find Dictionary named: " + dictionaryName)); + } + + /** + * Deletes a dictionary element from Dictionary by shortName. + * + * @param dictionaryName The dictionary name + * @param dictionaryElementShortName the dictionary Element Short name + */ + public void deleteDictionaryElement(String dictionaryName, String dictionaryElementShortName) { + if (dictionaryRepository.existsById(dictionaryName)) { + DictionaryElement element = + dictionaryElementsRepository.findById(dictionaryElementShortName).orElse(null); + if (element != null) { + Dictionary dict = getDictionary(dictionaryName); + dict.removeDictionaryElement(element); + dictionaryRepository.save(dict); + } + } + } + + private DictionaryElement updateDictionaryElement(DictionaryElement oldDictionaryElement, + DictionaryElement newDictionaryElement, Dictionary dictionary) { + oldDictionaryElement.setName(newDictionaryElement.getName()); + oldDictionaryElement.setDescription(newDictionaryElement.getDescription()); + oldDictionaryElement.setType(newDictionaryElement.getType()); + oldDictionaryElement.setSubDictionary(newDictionaryElement.getSubDictionary()); + oldDictionaryElement.getUsedByDictionaries().add(dictionary); + return oldDictionaryElement; + } +} diff --git a/src/main/java/org/onap/clamp/util/SemanticVersioning.java b/src/main/java/org/onap/clamp/util/SemanticVersioning.java index bf1529c2..10228449 100644 --- a/src/main/java/org/onap/clamp/util/SemanticVersioning.java +++ b/src/main/java/org/onap/clamp/util/SemanticVersioning.java @@ -33,12 +33,13 @@ public class SemanticVersioning { public static final int BEFORE = -1; public static final int EQUAL = 0; public static final int AFTER = 1; + public static final String DEFAULT_VERSION = "1.0.0"; /** * The compare method that compare arg0 to arg1. - * - * @param arg0 A version in string for semantice versioning (a.b.c.d...) - * @param arg1 A version in string for semantice versioning (a.b.c.d...) + * + * @param arg0 A version in string for semantic versioning (a.b.c.d...) + * @param arg1 A version in string for semantic versioning (a.b.c.d...) * @return objects (arg0, arg1) given as parameters. It returns the value: 0: if * (arg0==arg1) -1: if (arg0 < arg1) 1: if (arg0 > arg1) */ @@ -58,11 +59,13 @@ public class SemanticVersioning { int smalestStringLength = Math.min(arg0Array.length, arg1Array.length); - for (int currentVersionIndex = 0; currentVersionIndex < smalestStringLength; ++currentVersionIndex) { - if (Integer.parseInt(arg0Array[currentVersionIndex]) < Integer.parseInt(arg1Array[currentVersionIndex])) { + for (int currentVersionIndex = + 0; currentVersionIndex < smalestStringLength; ++currentVersionIndex) { + if (Integer.parseInt(arg0Array[currentVersionIndex]) < Integer + .parseInt(arg1Array[currentVersionIndex])) { return BEFORE; } else if (Integer.parseInt(arg0Array[currentVersionIndex]) > Integer - .parseInt(arg1Array[currentVersionIndex])) { + .parseInt(arg1Array[currentVersionIndex])) { return AFTER; } // equals, so do not return anything, continue @@ -73,4 +76,18 @@ public class SemanticVersioning { return Integer.compare(arg0Array.length, arg1Array.length); } } -} \ No newline at end of file + + /** + * Method to increment a version from its current version. + * + * @param currentVersion The current Version + * @return the increment version string + */ + public static String incrementMajorVersion(String currentVersion) { + if (currentVersion == null || currentVersion.isEmpty()) { + return DEFAULT_VERSION; + } + String[] versionArray = currentVersion.split("\\."); + return String.valueOf(Integer.parseInt(versionArray[0]) + 1)+".0.0"; + } +} diff --git a/src/main/resources/clds/camel/rest/clamp-api-v2.xml b/src/main/resources/clds/camel/rest/clamp-api-v2.xml index a0a3eb10..f2db72cb 100644 --- a/src/main/resources/clds/camel/rest/clamp-api-v2.xml +++ b/src/main/resources/clds/camel/rest/clamp-api-v2.xml @@ -1,8 +1,6 @@ - @@ -26,14 +24,10 @@ - - + @@ -54,14 +48,10 @@ - + - + @@ -83,16 +73,11 @@ - + - + @@ -119,16 +104,11 @@ - + - + @@ -155,16 +135,13 @@ - - + @@ -192,17 +169,12 @@ - + - + - @@ -214,8 +186,7 @@ - @@ -228,8 +199,7 @@ - @@ -237,17 +207,12 @@ - + - + - @@ -256,8 +221,7 @@ - @@ -270,8 +234,7 @@ - @@ -279,17 +242,12 @@ - + - + - @@ -300,8 +258,7 @@ uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('DCAE UNDEPLOY request','INFO',${exchangeProperty[loopObject]})" /> - @@ -314,8 +271,7 @@ - @@ -323,17 +279,12 @@ - + - + - @@ -344,8 +295,7 @@ uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('STOP request','INFO',${exchangeProperty[loopObject]})" /> - @@ -358,8 +308,7 @@ - @@ -367,17 +316,12 @@ - + - + - @@ -389,8 +333,7 @@ uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('RESTART request','INFO',${exchangeProperty[loopObject]})" /> - @@ -403,8 +346,7 @@ - @@ -412,17 +354,12 @@ - + - + - @@ -435,8 +372,7 @@ false - ${exchangeProperty[loopObject].getMicroServicePolicies()} @@ -444,8 +380,7 @@ ${body} - false @@ -453,8 +388,7 @@ - ${exchangeProperty[loopObject].getOperationalPolicies()} @@ -462,8 +396,7 @@ ${body} - false @@ -472,8 +405,7 @@ - ${exchangeProperty[operationalPolicy].createGuardPolicyPayloads().entrySet()} @@ -481,8 +413,7 @@ ${body} - @@ -499,8 +430,7 @@ - @@ -513,8 +443,7 @@ - @@ -524,12 +453,9 @@ - + - @@ -546,14 +472,12 @@ ${body} - - ${exchangeProperty[loopObject].getOperationalPolicies()} @@ -561,12 +485,10 @@ ${body} - - ${exchangeProperty[operationalPolicy].createGuardPolicyPayloads().entrySet()} @@ -574,16 +496,14 @@ ${body} - - @@ -596,8 +516,7 @@ - @@ -605,17 +524,12 @@ - + - + - @@ -641,8 +555,7 @@ - @@ -655,5 +568,408 @@ + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + ${body} + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + ${body} + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + ${body} + + + + + java.lang.Exception + + true + + + 404 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + diff --git a/src/test/java/org/onap/clamp/clds/tosca/DictionaryRepositoriesTestItCase.java b/src/test/java/org/onap/clamp/clds/tosca/DictionaryRepositoriesTestItCase.java index 2274fcf6..5208f7ff 100644 --- a/src/test/java/org/onap/clamp/clds/tosca/DictionaryRepositoriesTestItCase.java +++ b/src/test/java/org/onap/clamp/clds/tosca/DictionaryRepositoriesTestItCase.java @@ -25,9 +25,7 @@ package org.onap.clamp.clds.tosca; import static org.assertj.core.api.Assertions.assertThat; -import java.util.LinkedList; import java.util.List; - import org.junit.Test; import org.junit.runner.RunWith; import org.onap.clamp.clds.Application; @@ -55,16 +53,12 @@ public class DictionaryRepositoriesTestItCase { dictionaryTest1.setSubDictionaryType("testType"); DictionaryElement element1 = new DictionaryElement(); - element1.setDictionary(dictionaryTest1); element1.setName("element1"); element1.setShortName("shortName1"); - element1.setSubDictionary("subDictionary1"); element1.setType("type1"); element1.setDescription("description1"); - LinkedList elementList1 = new LinkedList(); - elementList1.add(element1); - dictionaryTest1.setDictionaryElements(elementList1); + dictionaryTest1.addDictionaryElements(element1); Dictionary dictionaryTest2 = new Dictionary(); dictionaryTest2.setName("testDictionary2"); @@ -72,16 +66,13 @@ public class DictionaryRepositoriesTestItCase { dictionaryTest2.setSubDictionaryType("testType"); DictionaryElement element2 = new DictionaryElement(); - element2.setDictionary(dictionaryTest2); element2.setName("element2"); element2.setShortName("shortName2"); - element2.setSubDictionary("subDictionary2"); + element2.setSubDictionary("testDictionary1"); element2.setType("type2"); element2.setDescription("description2"); - LinkedList elementList2 = new LinkedList(); - elementList2.add(element2); - dictionaryTest2.setDictionaryElements(elementList2); + dictionaryTest2.addDictionaryElements(element2); dictionaryRepository.save(dictionaryTest1); List res1 = dictionaryRepository.getAllDictionaryNames(); diff --git a/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTest.java b/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTest.java deleted file mode 100644 index a9e279de..00000000 --- a/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights - * reserved. - * Modifications Copyright (C) 2019 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.clds.tosca; - -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.junit.Test; -import org.onap.clamp.clds.util.ResourceFileUtil; -import org.skyscreamer.jsonassert.JSONAssert; - -public class ToscaYamlToJsonConvertorTest { - - /** - * This Test validates TOSCA yaml to JSON Schema conversion based on JSON Editor - * Schema. - * - * @throws IOException In case of issue when opening the tosca yaml file and - * converted json file - */ - @Test - public final void testParseToscaYaml() throws IOException { - String toscaModelYaml = ResourceFileUtil.getResourceAsString("tosca/tosca_example.yaml"); - ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(); - - String parsedJsonSchema = convertor.parseToscaYaml(toscaModelYaml, - "onap.policies.monitoring.cdap.tca.hi.lo.app"); - assertNotNull(parsedJsonSchema); - JSONAssert.assertEquals(ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json.json"), - parsedJsonSchema, true); - } - - /** - * This Test validates TOSCA yaml with constraints to JSON Schema conversion - * based on JSON Editor Schema. - * - * @throws IOException In case of issue when opening the tosca yaml file and - * converted json file - */ - @Test - public final void testParseToscaYamlWithConstraints() throws IOException { - String toscaModelYaml = ResourceFileUtil.getResourceAsString("tosca/tosca-with-constraints.yaml"); - ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(); - - String parsedJsonSchema = convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.example.app"); - assertNotNull(parsedJsonSchema); - JSONAssert.assertEquals(ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json-with-constraints.json"), - parsedJsonSchema, true); - } - - /** - * This Test validates TOSCA yaml with different datatypes to JSON Schema - * conversion based on JSON Editor Schema. - * - * @throws IOException In case of issue when opening the tosca yaml file and - * converted json file - */ - @Test - public final void testParseToscaYamlWithTypes() throws IOException { - String toscaModelYaml = ResourceFileUtil.getResourceAsString("tosca/tosca-with-datatypes.yaml"); - ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(); - - String parsedJsonSchema = convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.example.app"); - assertNotNull(parsedJsonSchema); - JSONAssert.assertEquals(ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json-with-datatypes.json"), - parsedJsonSchema, true); - } -} diff --git a/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTestItCase.java b/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTestItCase.java new file mode 100644 index 00000000..f426c762 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTestItCase.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights + * reserved. + * Modifications Copyright (C) 2019 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.clds.tosca; + +import com.google.gson.JsonObject; +import java.io.IOException; +import javax.transaction.Transactional; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.clamp.clds.Application; +import org.onap.clamp.clds.util.ResourceFileUtil; +import org.onap.clamp.tosca.Dictionary; +import org.onap.clamp.tosca.DictionaryElement; +import org.onap.clamp.tosca.DictionaryService; +import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = Application.class) +public class ToscaYamlToJsonConvertorTestItCase { + + @Autowired + private DictionaryService dictionaryService; + + @Autowired + private ToscaYamlToJsonConvertor toscaYamlToJsonConvertor; + + /** + * This Test validates TOSCA yaml to JSON Schema conversion based on JSON Editor + * Schema. + * + * @throws IOException In case of issue when opening the tosca yaml file and + * converted json file + */ + @Test + public final void testParseToscaYaml() throws IOException { + String toscaModelYaml = ResourceFileUtil.getResourceAsString("tosca/tosca_example.yaml"); + ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(); + + String parsedJsonSchema = + convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.cdap.tca.hi.lo.app"); + assertNotNull(parsedJsonSchema); + JSONAssert.assertEquals( + ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json.json"), + parsedJsonSchema, true); + } + + /** + * This Test validates TOSCA yaml with constraints to JSON Schema conversion + * based on JSON Editor Schema. + * + * @throws IOException In case of issue when opening the tosca yaml file and + * converted json file + */ + @Test + public final void testParseToscaYamlWithConstraints() throws IOException { + String toscaModelYaml = + ResourceFileUtil.getResourceAsString("tosca/tosca-with-constraints.yaml"); + ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(); + + String parsedJsonSchema = + convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.example.app"); + assertNotNull(parsedJsonSchema); + JSONAssert.assertEquals( + ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json-with-constraints.json"), + parsedJsonSchema, true); + } + + /** + * This Test validates TOSCA yaml with different datatypes to JSON Schema + * conversion based on JSON Editor Schema. + * + * @throws IOException In case of issue when opening the tosca yaml file and + * converted json file + */ + @Test + public final void testParseToscaYamlWithTypes() throws IOException { + String toscaModelYaml = + ResourceFileUtil.getResourceAsString("tosca/tosca-with-datatypes.yaml"); + ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(); + + String parsedJsonSchema = + convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.example.app"); + assertNotNull(parsedJsonSchema); + JSONAssert.assertEquals( + ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json-with-datatypes.json"), + parsedJsonSchema, true); + } + + /** + * This Test validates Tosca yaml with metadata tag that contains policy_model_type and acronym + * parameters which defines the Tosca Policy name and its short name. + * + * @throws IOException In case of issue when opening the tosca yaml file and + * converted json file + */ + @Test + @Transactional + public final void testMetadataClampPossibleValues() throws IOException { + + // Set up dictionary elements + Dictionary dictionaryTest = new Dictionary(); + dictionaryTest.setName("Context"); + dictionaryTest.setSecondLevelDictionary(0); + + DictionaryElement element = new DictionaryElement(); + element.setName("PROD"); + element.setShortName("PROD"); + element.setType("string"); + element.setDescription("Production"); + dictionaryTest.addDictionaryElements(element); + + dictionaryService.saveOrUpdateDictionary(dictionaryTest); + + Dictionary dictionaryTest1 = new Dictionary(); + dictionaryTest1.setName("EventDictionary"); + dictionaryTest1.setSecondLevelDictionary(0); + + DictionaryElement element1 = new DictionaryElement(); + element1.setName("alarmCondition"); + element1.setShortName("alarmCondition"); + element1.setType("string"); + element1.setDescription("Alarm Condition"); + dictionaryTest1.addDictionaryElements(element1); + + dictionaryService.saveOrUpdateDictionary(dictionaryTest1); + + Dictionary dictionaryTest2 = new Dictionary(); + dictionaryTest2.setName("Operators"); + dictionaryTest2.setSecondLevelDictionary(0); + + DictionaryElement element2 = new DictionaryElement(); + element2.setName("equals"); + element2.setShortName("equals"); + element2.setType("string"); + element2.setDescription("equals"); + dictionaryTest2.addDictionaryElements(element2); + dictionaryService.saveOrUpdateDictionary(dictionaryTest2); + + String toscaModelYaml = + ResourceFileUtil.getResourceAsString("tosca/tosca_metadata_clamp_possible_values.yaml"); + + JsonObject jsonObject = toscaYamlToJsonConvertor.validateAndConvertToJson(toscaModelYaml); + assertNotNull(jsonObject); + String policyModelType = toscaYamlToJsonConvertor.getValueFromMetadata(jsonObject, + ToscaSchemaConstants.METADATA_POLICY_MODEL_TYPE); + String acronym = toscaYamlToJsonConvertor.getValueFromMetadata(jsonObject, + ToscaSchemaConstants.METADATA_ACRONYM); + String parsedJsonSchema = + toscaYamlToJsonConvertor.parseToscaYaml(toscaModelYaml, policyModelType); + + assertNotNull(parsedJsonSchema); + assertEquals("onap.policies.monitoring.cdap.tca.hi.lo.app", policyModelType); + assertEquals("tca", acronym); + JSONAssert.assertEquals( + ResourceFileUtil + .getResourceAsString("tosca/tosca_metadata_clamp_possible_values_json_schema.json"), + parsedJsonSchema, true); + } + +} diff --git a/src/test/java/org/onap/clamp/loop/LoopTemplatesServiceItCase.java b/src/test/java/org/onap/clamp/loop/LoopTemplatesServiceItCase.java new file mode 100644 index 00000000..3a36a5d8 --- /dev/null +++ b/src/test/java/org/onap/clamp/loop/LoopTemplatesServiceItCase.java @@ -0,0 +1,145 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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.loop; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.SortedSet; +import javax.transaction.Transactional; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.clamp.clds.Application; +import org.onap.clamp.loop.template.LoopElementModel; +import org.onap.clamp.loop.template.LoopTemplate; +import org.onap.clamp.loop.template.LoopTemplateLoopElementModel; +import org.onap.clamp.loop.template.LoopTemplatesService; +import org.onap.clamp.loop.template.LoopType; +import org.onap.clamp.loop.template.PolicyModel; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class LoopTemplatesServiceItCase { + + @Autowired + LoopTemplatesService loopTemplatesService; + + private static final String POLICY_MODEL_TYPE_1 = "org.onap.test"; + private static final String VERSION = "1.0.0"; + + private LoopElementModel getLoopElementModel(String yaml, String name, String loopElementType, + String createdBy, PolicyModel policyModel) { + LoopElementModel model = new LoopElementModel(name, loopElementType, yaml); + model.setBlueprint(""); + model.setDcaeBlueprintId(""); + model.addPolicyModel(policyModel); + return model; + } + + private PolicyModel getPolicyModel(String policyType, String policyModelTosca, String version, + String policyAcronym, String createdBy) { + return new PolicyModel(policyType, policyModelTosca, version, policyAcronym); + } + + private LoopTemplate getLoopTemplate(String name, String blueprint, String svgRepresentation, + String createdBy, Integer maxInstancesAllowed) { + LoopTemplate template = + new LoopTemplate(name, blueprint, svgRepresentation, maxInstancesAllowed, null); + template.addLoopElementModel(getLoopElementModel("yaml", "microService1", "MicroService", + createdBy, getPolicyModel(POLICY_MODEL_TYPE_1, "yaml", VERSION, "MS1", createdBy))); + template.setAllowedLoopType(LoopType.OPEN); + return template; + } + + @Test + @Transactional + public void shouldSaveOrUpdateLoopTemplate() { + LoopTemplate loopTemplate = getLoopTemplate("TemplateName", null, "svg", "xyz", -1); + LoopTemplate actualLoopTemplate = + loopTemplatesService.saveOrUpdateLoopTemplate(loopTemplate); + + assertNotNull(actualLoopTemplate); + assertThat(loopTemplate.getName()).isEqualTo("TemplateName"); + assertThat(loopTemplate.getAllowedLoopType()).isEqualTo(LoopType.OPEN); + } + + @Test + @Transactional + public void shouldReturnAllLoopemplates() { + LoopTemplate loopTemplate = getLoopTemplate("TemplateName", null, "svg", "xyz", -1); + loopTemplatesService.saveOrUpdateLoopTemplate(loopTemplate); + List loopTemplateList = loopTemplatesService.getAllLoopTemplates(); + + assertNotNull(loopTemplateList); + } + + @Test + @Transactional + public void shouldReturnLoopemplateNames() { + LoopTemplate loopTemplate = getLoopTemplate("TemplateName", null, "svg", "xyz", -1); + loopTemplatesService.saveOrUpdateLoopTemplate(loopTemplate); + List loopTemplateNames = loopTemplatesService.getLoopTemplateNames(); + + assertNotNull(loopTemplateNames); + assertEquals("TemplateName", loopTemplateNames.get(0)); + } + + @Test + @Transactional + public void shouldReturnLoopemplate() { + LoopTemplate loopTemplate = getLoopTemplate("TemplateName", null, "svg", "xyz", -1); + loopTemplatesService.saveOrUpdateLoopTemplate(loopTemplate); + LoopTemplate actualLoopTemplate = loopTemplatesService.getLoopTemplate("TemplateName"); + + assertNotNull(actualLoopTemplate); + assertThat(loopTemplate).isEqualTo(actualLoopTemplate); + assertThat(loopTemplate.getName()).isEqualTo(actualLoopTemplate.getName()); + assertThat(loopTemplate.getMaximumInstancesAllowed()) + .isEqualTo(actualLoopTemplate.getMaximumInstancesAllowed()); + SortedSet loopElementModelsUsed = + loopTemplate.getLoopElementModelsUsed(); + LoopTemplateLoopElementModel loopTemplateLoopElementModel = loopElementModelsUsed.first(); + assertThat(loopTemplateLoopElementModel.getLoopElementModel().getName()) + .isEqualTo("microService1"); + assertThat(loopTemplateLoopElementModel.getLoopTemplate().getName()) + .isEqualTo("TemplateName"); + } + + @Test + @Transactional + public void shouldDeleteLoopemplate() { + LoopTemplate loopTemplate = getLoopTemplate("TemplateName", null, "svg", "xyz", -1); + loopTemplatesService.saveOrUpdateLoopTemplate(loopTemplate); + loopTemplatesService.deleteLoopTemplate("TemplateName"); + LoopTemplate actualLoopTemplate = loopTemplatesService.getLoopTemplate("TemplateName"); + assertNull(actualLoopTemplate); + } + +} diff --git a/src/test/java/org/onap/clamp/tosca/DictionaryServiceItCase.java b/src/test/java/org/onap/clamp/tosca/DictionaryServiceItCase.java new file mode 100644 index 00000000..55d347ce --- /dev/null +++ b/src/test/java/org/onap/clamp/tosca/DictionaryServiceItCase.java @@ -0,0 +1,247 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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.tosca; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import javax.persistence.EntityNotFoundException; +import javax.transaction.Transactional; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.clamp.clds.Application; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class DictionaryServiceItCase { + + @Autowired + private DictionaryService dictionaryService; + + @Autowired + private DictionaryElementsRepository dictionaryElementsRepository; + + private DictionaryElement getDictionaryElement(String shortName, String name, + String description, String type, String subDictionaryName) { + + return new DictionaryElement(name, shortName, description, type, subDictionaryName); + + } + + private Dictionary getSimpleDictionaryExample() { + + Dictionary dictionary = new Dictionary("Dictionary1", 0, null); + + dictionary.addDictionaryElements(getDictionaryElement("DE1", "DictionaryElement1", + "DictionaryElement1", "string", null)); + + dictionary.addDictionaryElements(getDictionaryElement("DE2", "DictionaryElement2", + "DictionaryElement2", "number", null)); + + return dictionary; + } + + private Dictionary getSecondaryDictionaryExample() { + + Dictionary dictionary = new Dictionary("SecondaryDict", 1, "string"); + + dictionary.addDictionaryElements(getDictionaryElement("SDE1", "SecondaryDictElement1", + "SecondaryDictElement1", "string", null)); + + dictionary.addDictionaryElements(getDictionaryElement("SDE2", "SecondaryDictElement2", + "SecondaryDictElement2", "string", null)); + + return dictionary; + } + + /** + * Test to validate that Dictionary is created. + */ + @Test + @Transactional + public void shouldCreateDictionary() { + Dictionary dictionary = getSimpleDictionaryExample(); + Dictionary actualDictionary = dictionaryService.saveOrUpdateDictionary(dictionary); + assertNotNull(actualDictionary); + assertThat(actualDictionary).isEqualTo(dictionary); + assertThat(actualDictionary.getName()).isEqualTo(dictionary.getName()); + + assertThat(actualDictionary.getDictionaryElements()).contains( + dictionaryElementsRepository.findById("DE1").get(), + dictionaryElementsRepository.findById("DE2").get()); + } + + /** + * Test to validate a DictionaryElement is created for a Dictionary. + */ + @Test + @Transactional + public void shouldCreateorUpdateDictionaryElement() { + Dictionary dictionary = getSimpleDictionaryExample(); + Dictionary actualDictionary = dictionaryService.saveOrUpdateDictionary(dictionary); + DictionaryElement dictionaryElement = + getDictionaryElement("DictionaryElement3", "DE3", "DictionaryElement3", "date", null); + actualDictionary.addDictionaryElements(dictionaryElement); + Dictionary updatedDictionary = dictionaryService + .saveOrUpdateDictionaryElement(actualDictionary.getName(), actualDictionary); + assertNotNull(updatedDictionary); + assertTrue(updatedDictionary.getDictionaryElements().contains(dictionaryElement)); + assertThat(updatedDictionary.getName()).isEqualTo(actualDictionary.getName()); + // update the dictionary element. + dictionaryElement.setDescription("DictionaryElement3 New Description"); + Dictionary dictionary3 = new Dictionary("Dictionary1", 0, null); + dictionary3.addDictionaryElements(dictionaryElement); + Dictionary updatedDictionary2 = + dictionaryService.saveOrUpdateDictionaryElement(dictionary3.getName(), dictionary3); + + assertNotNull(updatedDictionary2); + assertTrue(updatedDictionary2.getDictionaryElements().contains(dictionaryElement)); + updatedDictionary2.getDictionaryElements().forEach(element -> { + if (element.equals(dictionaryElement)) { + assertTrue(element.getDescription().equals(dictionaryElement.getDescription())); + } + }); + + } + + /** + * Test to validate that All Dictionaries are retrieved. + */ + @Test + @Transactional + public void shouldReturnAllDictionaries() { + Dictionary dictionary = getSimpleDictionaryExample(); + Dictionary secondaryDictionary = getSecondaryDictionaryExample(); + dictionaryService.saveOrUpdateDictionary(dictionary); + dictionaryService.saveOrUpdateDictionary(secondaryDictionary); + + List list = dictionaryService.getAllDictionaries(); + assertNotNull(list); + assertThat(list).contains(dictionary, secondaryDictionary); + } + + /** + * Test to validate one Dictionary is returned. + */ + @Test + @Transactional + public void shouldReturnOneDictionary() { + Dictionary dictionary = getSimpleDictionaryExample(); + dictionaryService.saveOrUpdateDictionary(dictionary); + + Dictionary returnedDictionary = dictionaryService.getDictionary("Dictionary1"); + assertNotNull(returnedDictionary); + assertThat(returnedDictionary).isEqualTo(dictionary); + assertThat(returnedDictionary.getDictionaryElements()) + .isEqualTo(dictionary.getDictionaryElements()); + } + + /** + * Test to validate one Dictionary is returned. + */ + @Test + @Transactional + public void shouldReturnEntityNotFoundException() { + try { + dictionaryService.getDictionary("Test"); + } catch (Exception e) { + assertThat(e).isInstanceOf(EntityNotFoundException.class); + assertTrue(e.getMessage().equals("Couldn't find Dictionary named: Test")); + } + } + + /** + * Test to validate Dictionary is deleted. + */ + @Test + @Transactional + public void shouldDeleteDictionaryByObject() { + Dictionary dictionary = getSimpleDictionaryExample(); + Dictionary returnedDictionary = dictionaryService.saveOrUpdateDictionary(dictionary); + + dictionaryService.deleteDictionary(returnedDictionary); + try { + dictionaryService.getDictionary("Dictionary1"); + } catch (EntityNotFoundException e) { + assertTrue(e.getMessage().equals("Couldn't find Dictionary named: Dictionary1")); + } + } + + /** + * Test to validate Dictionary is deleted by Name. + */ + @Test + @Transactional + public void shouldDeleteDictionaryByName() { + Dictionary dictionary = getSimpleDictionaryExample(); + dictionaryService.saveOrUpdateDictionary(dictionary); + dictionaryService.deleteDictionary(dictionary.getName()); + try { + dictionaryService.getDictionary("Dictionary1"); + } catch (EntityNotFoundException e) { + assertTrue(e.getMessage().equals("Couldn't find Dictionary named: Dictionary1")); + } + } + + /** + * Test to validate DictionaryElements is deleted by Name. + */ + @Test + @Transactional + public void shouldDeleteDictionaryElementsByName() { + Dictionary dictionary = getSimpleDictionaryExample(); + dictionaryService.saveOrUpdateDictionary(dictionary); + DictionaryElement dictionaryElement = + dictionaryElementsRepository.findById("DE1").orElse(null); + assertNotNull(dictionaryElement); + dictionaryService.deleteDictionaryElement("Dictionary1", "DE1"); + dictionary = dictionaryService.getDictionary("Dictionary1"); + DictionaryElement deletedDictionaryElement = + dictionaryElementsRepository.findById("DE1").orElse(null); + assertThat(deletedDictionaryElement).isNotIn(dictionary.getDictionaryElements()); + } + + /** + * Test to validate all secondary level dictionary names are returned. + */ + @Test + @Transactional + public void shouldReturnAllSecondaryLevelDictionaryNames() { + Dictionary dictionary = getSecondaryDictionaryExample(); + dictionaryService.saveOrUpdateDictionary(dictionary); + + Dictionary dictionary2 = new Dictionary("SecondaryDict2", 1, "string"); + dictionaryService.saveOrUpdateDictionary(dictionary2); + List secondaryDictionaryNames = + dictionaryService.getAllSecondaryLevelDictionaryNames(); + + assertNotNull(secondaryDictionaryNames); + assertThat(secondaryDictionaryNames).contains(dictionary.getName(), dictionary2.getName()); + } +} diff --git a/src/test/java/org/onap/clamp/util/SemanticVersioningTest.java b/src/test/java/org/onap/clamp/util/SemanticVersioningTest.java index 1fb5922f..e018f095 100644 --- a/src/test/java/org/onap/clamp/util/SemanticVersioningTest.java +++ b/src/test/java/org/onap/clamp/util/SemanticVersioningTest.java @@ -6,27 +6,27 @@ * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with 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 + * + * 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.util; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class SemanticVersioningTest { @Test @@ -68,4 +68,12 @@ public class SemanticVersioningTest { assertThat(SemanticVersioning.compare(null, "1.0")).isEqualTo(-1); assertThat(SemanticVersioning.compare("1.0", null)).isEqualTo(1); } + + @Test + public void incrementVersionTest() { + assertThat(SemanticVersioning.incrementMajorVersion("1.0")).isEqualTo("2.0.0"); + assertThat(SemanticVersioning.incrementMajorVersion("1.0.0")).isEqualTo("2.0.0"); + assertThat(SemanticVersioning.incrementMajorVersion("1")).isEqualTo("2.0.0"); + assertThat(SemanticVersioning.incrementMajorVersion("1.2.3")).isEqualTo("2.0.0"); + } } diff --git a/src/test/resources/clds/camel/rest/clamp-api-v2.xml b/src/test/resources/clds/camel/rest/clamp-api-v2.xml new file mode 100644 index 00000000..b0a8d2fd --- /dev/null +++ b/src/test/resources/clds/camel/rest/clamp-api-v2.xml @@ -0,0 +1,984 @@ + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + ${body} + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + ${body} + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + ${body} + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + + + false + + + + + ${exchangeProperty[loopObject].getMicroServicePolicies()} + + + ${body} + + + + false + + + + + + + ${exchangeProperty[loopObject].getOperationalPolicies()} + + + ${body} + + + + false + + + + + + + + ${exchangeProperty[operationalPolicy].createGuardPolicyPayloads().entrySet()} + + + ${body} + + + + + false + + + + + + + + 3000 + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + + + + + ${exchangeProperty[loopObject].getMicroServicePolicies()} + + + ${body} + + + + + + + + ${exchangeProperty[loopObject].getOperationalPolicies()} + + + ${body} + + + + + + ${exchangeProperty[operationalPolicy].createGuardPolicyPayloads().entrySet()} + + + ${body} + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + ${exchangeProperty[loopObject]} + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + ${body} + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + ${body} + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + ${body} + + + + + java.lang.Exception + + true + + + 404 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + java.lang.Exception + + true + + + 500 + + + ERROR: ${exception.message} + + + + + + + + + + + + + + + + java.lang.Exception + + false + + + + + + + + diff --git a/src/test/resources/tosca/tosca_metadata_clamp_possible_values.yaml b/src/test/resources/tosca/tosca_metadata_clamp_possible_values.yaml new file mode 100644 index 00000000..4d3c3dff --- /dev/null +++ b/src/test/resources/tosca/tosca_metadata_clamp_possible_values.yaml @@ -0,0 +1,184 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + onap.policies.Monitoring: + derived_from: tosca.policies.Root + description: a base policy type for all policies that governs monitoring provisioning + onap.policies.monitoring.cdap.tca.hi.lo.app: + derived_from: onap.policies.Monitoring + version: 1.0.0 + properties: + tca_policy: + type: map + description: TCA Policy JSON + entry_schema: + type: onap.datatypes.monitoring.tca_policy + metadata: + policy_model_type: onap.policies.monitoring.cdap.tca.hi.lo.app + acronym: tca + +data_types: + onap.datatypes.monitoring.metricsPerEventName: + derived_from: tosca.datatypes.Root + properties: + controlLoopSchemaType: + type: string + required: true + description: Specifies Control Loop Schema Type for the event Name e.g. VNF, VM + constraints: + - valid_values: + - VM + - VNF + eventName: + type: string + required: true + description: Event name to which thresholds need to be applied + policyName: + type: string + required: true + description: TCA Policy Scope Name + policyScope: + type: string + required: true + description: TCA Policy Scope + policyVersion: + type: string + required: true + description: TCA Policy Scope Version + thresholds: + type: list + required: true + description: Thresholds associated with eventName + entry_schema: + type: onap.datatypes.monitoring.thresholds + context: + type: string + required: true + description: TCA Policy Dummy Context + metadata: + clamp_possible_values: ["Dictionary:Context"] + + signature: + type: onap.datatypes.monitoring.Dummy_Signature + description: Signature + required: true + + onap.datatypes.monitoring.Dummy_Signature: + derived_from: tosca.datatypes.Root + properties: + filter_clause: + type: string + description: Filter Clause + required: true + metadata: + clamp_possible_values: ["Dictionary:EventDictionary#Operators"] + + onap.datatypes.monitoring.tca_policy: + derived_from: tosca.datatypes.Root + properties: + domain: + type: string + required: true + description: Domain name to which TCA needs to be applied + default: measurementsForVfScaling + constraints: + - equal: measurementsForVfScaling + metricsPerEventName: + type: list + required: true + description: Contains eventName and threshold details that need to be applied to given eventName + entry_schema: + type: onap.datatypes.monitoring.metricsPerEventName + onap.datatypes.monitoring.thresholds: + derived_from: tosca.datatypes.Root + properties: + closedLoopControlName: + type: string + required: true + description: Closed Loop Control Name associated with the threshold + closedLoopEventStatus: + type: string + required: true + description: Closed Loop Event Status of the threshold + constraints: + - valid_values: + - ONSET + - ABATED + direction: + type: string + required: true + description: Direction of the threshold + constraints: + - valid_values: + - LESS + - LESS_OR_EQUAL + - GREATER + - GREATER_OR_EQUAL + - EQUAL + fieldPath: + type: string + required: true + description: Json field Path as per CEF message which needs to be analyzed for TCA + constraints: + - valid_values: + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsDelta + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsAccumulated + - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsAccumulated + - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuIdle + - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageInterrupt + - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageNice + - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSoftIrq + - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSteal + - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSystem + - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuWait + - $.event.measurementsForVfScalingFields.cpuUsageArray[*].percentUsage + - $.event.measurementsForVfScalingFields.meanRequestLatency + - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryBuffered + - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryCached + - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryConfigured + - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryFree + - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryUsed + - $.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value + severity: + type: string + required: true + description: Threshold Event Severity + constraints: + - valid_values: + - CRITICAL + - MAJOR + - MINOR + - WARNING + - NORMAL + thresholdValue: + type: integer + required: true + description: Threshold value for the field Path inside CEF message + version: + type: string + required: true + description: Version number associated with the threshold diff --git a/src/test/resources/tosca/tosca_metadata_clamp_possible_values_json_schema.json b/src/test/resources/tosca/tosca_metadata_clamp_possible_values_json_schema.json new file mode 100644 index 00000000..af8c1f96 --- /dev/null +++ b/src/test/resources/tosca/tosca_metadata_clamp_possible_values_json_schema.json @@ -0,0 +1,235 @@ +{ + "schema":{ + "uniqueItems":"true", + "format":"tabs-top", + "type":"array", + "title":"TCA Policy JSON", + "items":{ + "type":"object", + "title":"TCA Policy JSON", + "required":[ + "domain", + "metricsPerEventName" + ], + "properties":{ + "domain":{ + "propertyOrder":1001, + "default":"measurementsForVfScaling", + "title":"Domain name to which TCA needs to be applied", + "type":"string" + }, + "metricsPerEventName":{ + "propertyOrder":1002, + "uniqueItems":"true", + "format":"tabs-top", + "title":"Contains eventName and threshold details that need to be applied to given eventName", + "type":"array", + "items":{ + "type":"object", + "required":[ + "controlLoopSchemaType", + "eventName", + "policyName", + "policyScope", + "policyVersion", + "thresholds", + "context", + "signature" + ], + "properties":{ + "policyVersion":{ + "propertyOrder":1007, + "title":"TCA Policy Scope Version", + "type":"string" + }, + "thresholds":{ + "propertyOrder":1008, + "uniqueItems":"true", + "format":"tabs-top", + "title":"Thresholds associated with eventName", + "type":"array", + "items":{ + "type":"object", + "required":[ + "closedLoopControlName", + "closedLoopEventStatus", + "direction", + "fieldPath", + "severity", + "thresholdValue", + "version" + ], + "properties":{ + "severity":{ + "propertyOrder":1013, + "title":"Threshold Event Severity", + "type":"string", + "enum":[ + "CRITICAL", + "MAJOR", + "MINOR", + "WARNING", + "NORMAL" + ] + }, + "fieldPath":{ + "propertyOrder":1012, + "title":"Json field Path as per CEF message which needs to be analyzed for TCA", + "type":"string", + "enum":[ + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsAccumulated", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuIdle", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageInterrupt", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageNice", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSoftIrq", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSteal", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSystem", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuWait", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].percentUsage", + "$.event.measurementsForVfScalingFields.meanRequestLatency", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryBuffered", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryCached", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryConfigured", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryFree", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryUsed", + "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value" + ] + }, + "thresholdValue":{ + "propertyOrder":1014, + "title":"Threshold value for the field Path inside CEF message", + "type":"integer" + }, + "closedLoopEventStatus":{ + "propertyOrder":1010, + "title":"Closed Loop Event Status of the threshold", + "type":"string", + "enum":[ + "ONSET", + "ABATED" + ] + }, + "closedLoopControlName":{ + "propertyOrder":1009, + "title":"Closed Loop Control Name associated with the threshold", + "type":"string" + }, + "version":{ + "propertyOrder":1015, + "title":"Version number associated with the threshold", + "type":"string" + }, + "direction":{ + "propertyOrder":1011, + "title":"Direction of the threshold", + "type":"string", + "enum":[ + "LESS", + "LESS_OR_EQUAL", + "GREATER", + "GREATER_OR_EQUAL", + "EQUAL" + ] + } + } + } + }, + "policyName":{ + "propertyOrder":1005, + "title":"TCA Policy Scope Name", + "type":"string" + }, + "signature":{ + "propertyOrder":1017, + "title":"Signature", + "required":[ + "filter_clause" + ], + "properties":{ + "filter_clause":{ + "propertyOrder":30002, + "qschema":{ + "filters":[ + { + "operators":[ + "equals" + ], + "minLength":1, + "id":"alarmCondition", + "label":"alarmCondition", + "type":"string" + } + ] + }, + "minLength":1, + "title":"Filter Clause", + "type":"qbldr" + } + } + }, + "controlLoopSchemaType":{ + "propertyOrder":1003, + "title":"Specifies Control Loop Schema Type for the event Name e.g. VNF, VM", + "type":"string", + "enum":[ + "VM", + "VNF" + ] + }, + "policyScope":{ + "propertyOrder":1006, + "title":"TCA Policy Scope", + "type":"string" + }, + "context":{ + "propertyOrder":1016, + "options":{ + "enum_titles":[ + "PROD" + ] + }, + "title":"TCA Policy Dummy Context", + "type":"string", + "enum":[ + "PROD" + ] + }, + "eventName":{ + "propertyOrder":1004, + "title":"Event name to which thresholds need to be applied", + "type":"string" + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/ui-react/src/LoopUI.js b/ui-react/src/LoopUI.js index 9eea0be9..19b0814d 100644 --- a/ui-react/src/LoopUI.js +++ b/ui-react/src/LoopUI.js @@ -43,6 +43,7 @@ import ConfigurationPolicyModal from './components/dialogs/ConfigurationPolicy/C import LoopPropertiesModal from './components/dialogs/Loop/LoopPropertiesModal'; import UserInfoModal from './components/dialogs/UserInfoModal'; import LoopService from './api/LoopService'; +import UploadToscaPolicyModal from './components/dialogs/Tosca/UploadToscaPolicyModal'; import ViewToscaPolicyModal from './components/dialogs/Tosca/ViewToscaPolicyModal'; import ViewBlueprintMicroServiceTemplatesModal from './components/dialogs/Tosca/ViewBlueprintMicroServiceTemplatesModal'; import PerformAction from './components/dialogs/PerformActions'; @@ -248,6 +249,7 @@ export default class LoopUI extends React.Component { render() { return ( + ()} /> ()} /> ()} /> + + { + if (event.target.files && event.target.files[0]) { + const scope = this; + let reader = new FileReader(); + this.setState({policyModelType: '', policyModelTosca: '' }); + reader.onload = function(e) { + var lines = reader.result.split('\n'); + for (var line = 0; line < lines.length; line++) { + if(lines[line].trim().slice(0, 24) === 'onap.policies.monitoring') { + var microsvc = lines[line].trim().slice(0, -1); + scope.setState({ policyModelType: microsvc, policyModelTosca: reader.result}); + } + } + }; + console.log("Filename is", event.target.files[0]); + reader.readAsText(event.target.files[0]); + } + this.setState({selectedFile: event.target.files[0]}); + }; + + handleClose() { + this.setState({ show: false }); + this.props.history.push('/'); + } + + handleUploadToscaPolicyModel(e) { + e.preventDefault(); + console.log("Policy Model Type is", this.state.policyModelType); + if(this.state.policyModelType && this.state.policyModelTosca) { + TemplateMenuService.uploadToscaPolicyModal(this.state.policyModelType, this.state.policyModelTosca).then(resp => { + if(resp.status === 200) { + this.setState({apiResponseStatus: resp.status, apiResponseMessage: resp.message, upldBtnClicked: true}); + } else { + this.setState({apiResponseStatus: 500, apiResponseMessage: resp, upldBtnClicked: true}); + } + }); + } else { + this.setState({apiResponse: 500, apiResponseMessage: 'Parameters are missing', upldBtnClicked: true}); + } +} + + handlePolicyModelType = event => { + this.setState({ + policyModelType: event.target.value + }) + } + + render() { + return ( + + + Upload Tosca Modal + + + + + this.fileInput = fileInput}/> + + +

{this.state.selectedFile.name}

+
+ Micro Service Name: + + +
+
+ + {!this.state.apiResponseStatus?:""} + {!this.state.apiResponseStatus?:""} + {this.state.apiResponseStatus? +

{this.state.apiResponseMessage}

+ +
:""} +
+
+ ); + } +} diff --git a/ui-react/src/components/dialogs/Tosca/UploadToscaPolicyModal.test.js b/ui-react/src/components/dialogs/Tosca/UploadToscaPolicyModal.test.js new file mode 100644 index 00000000..dac8ac92 --- /dev/null +++ b/ui-react/src/components/dialogs/Tosca/UploadToscaPolicyModal.test.js @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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============================================ + * =================================================================== + * + */ +import React from 'react'; +import { shallow } from 'enzyme'; +import UploadToscaPolicyModal from './UploadToscaPolicyModal'; + + +describe('Test Upload Tosca Policy Model', () => { + + it('Test handleMicroServiceName', () => { + + const component = shallow(); + + const inputValue = 'TCA' + + const button = component.find('input').at(1); + + button.simulate('change', { target: { value: inputValue }}); + + expect(component.state('policyModelType')).toEqual(inputValue); + + expect(component).toMatchSnapshot(); + + }); + + it('Test handleUploadToscaPolicyModel for Tosca Model', () => { + + const component = shallow(); + + const fakeEvent = { preventDefault: () => console.log('preventDefault') }; + + component.setState({ + policyModelType: "TCA", + upldBtnClicked: false, + policyModelTosca: "TCAToscaModelYaml", + selectedFile: { name: "tca.yaml"} + }); + + const Button = component.find('Button').at(1); + + Button.simulate('click', fakeEvent); + + expect(component.state('policyModelTosca')).toEqual('TCAToscaModelYaml'); + + }); + + it('Test handleClose', () => { + + const historyMock = { push: jest.fn() }; + + const handleClose = jest.spyOn(UploadToscaPolicyModal.prototype,'handleClose'); + + const component = shallow() + + component.find('[variant="secondary"]').at(1).prop('onClick')(); + + expect(handleClose).toHaveBeenCalledTimes(1); + + expect(component.state('show')).toEqual(false); + + expect(historyMock.push.mock.calls[0]).toEqual([ '/']); + + handleClose.mockClear(); + + }); + +}); diff --git a/ui-react/src/components/dialogs/Tosca/ViewToscaPolicyModal.js b/ui-react/src/components/dialogs/Tosca/ViewToscaPolicyModal.js index 6a93d4d9..5b66a25c 100644 --- a/ui-react/src/components/dialogs/Tosca/ViewToscaPolicyModal.js +++ b/ui-react/src/components/dialogs/Tosca/ViewToscaPolicyModal.js @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights + * Copyright (C) 2020 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -58,29 +58,29 @@ export default class ViewToscalPolicyModal extends React.Component { show: true, content: 'Please select Tosca model to view the details', selectedRow: -1, - toscaNames: [], + toscaPolicyModelNames: [], toscaColumns: [ { title: "#", field: "index", render: rowData => rowData.tableData.id + 1, cellStyle: cellStyle, headerStyle: headerStyle }, - { title: "Micro Service Name", field: "toscaModelName", + { title: "Policy Model Type", field: "policyModelType", cellStyle: cellStyle, headerStyle: headerStyle }, - { title: "PolicyType", field: "policyType", + { title: "Policy Acronym", field: "policyAcronym", cellStyle: cellStyle, headerStyle: headerStyle }, - { title: "Version", field: "toscaModelRevisions[0].version", + { title: "Version", field: "version", cellStyle: cellStyle, headerStyle: headerStyle }, - { title: "Uploaded By", field: "userId", + { title: "Uploaded By", field: "updatedBy", cellStyle: cellStyle, headerStyle: headerStyle }, - { title: "Uploaded Date", field: "lastUpdatedDate", editable: 'never', + { title: "Uploaded Date", field: "updatedDate", editable: 'never', cellStyle: cellStyle, headerStyle: headerStyle } @@ -101,6 +101,7 @@ export default class ViewToscalPolicyModal extends React.Component { this.handleClose = this.handleClose.bind(this); this.getPolicyToscaModels = this.getToscaPolicyModels.bind(this); this.handleYamlContent = this.handleYamlContent.bind(this); + this.getToscaPolicyModelYaml = this.getToscaPolicyModelYaml.bind(this); } componentWillMount() { @@ -108,11 +109,25 @@ export default class ViewToscalPolicyModal extends React.Component { } getToscaPolicyModels() { - TemplateMenuService.getToscaPolicyModels().then(toscaNames => { - this.setState({ toscaNames: toscaNames }); + TemplateMenuService.getToscaPolicyModels().then(toscaPolicyModelNames => { + this.setState({ toscaPolicyModelNames: toscaPolicyModelNames }); }); } + getToscaPolicyModelYaml(policyModelType) { + if (typeof policyModelType !== "undefined") { + TemplateMenuService.getToscaPolicyModelYaml(policyModelType).then(toscaYaml => { + if (toscaYaml.length !== 0) { + this.setState({content: toscaYaml}) + } else { + this.setState({ content: 'Please select Tosca model to view the details' }) + } + }); + } else { + this.setState({ content: 'Please select Tosca model to view the details' }) + } + } + handleYamlContent(event) { this.setState({ content: event.target.value }); } @@ -130,10 +145,10 @@ export default class ViewToscalPolicyModal extends React.Component { {this.setState({content: rowData.toscaModelRevisions[0].toscaModelYaml, selectedRow: rowData.tableData.id})}} + onRowClick={(event, rowData) => {this.getToscaPolicyModelYaml(rowData.policyModelType);this.setState({selectedRow: rowData.tableData.id})}} options={{ headerStyle: rowHeaderStyle, rowStyle: rowData => ({ diff --git a/ui-react/src/components/dialogs/Tosca/ViewToscaPolicyModal.test.js b/ui-react/src/components/dialogs/Tosca/ViewToscaPolicyModal.test.js index 1445e886..952e8886 100644 --- a/ui-react/src/components/dialogs/Tosca/ViewToscaPolicyModal.test.js +++ b/ui-react/src/components/dialogs/Tosca/ViewToscaPolicyModal.test.js @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights + * Copyright (C) 2020 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -39,12 +39,12 @@ describe('Verify ViewToscaPolicyModal', () => { json: () => { return Promise.resolve({ "index": "1", - "toscaModelYaml":"MTCA", - "toscaModelName":"DCAE_MTCAConfig", - "version":"16", - "userId":"aj928f", - "policyType":"mtca", - "lastUpdatedDate":"05-07-2019 19:09:42" + "policyModelTosca":"TCA", + "policyModelType":"onap.policies.monitoring.cdap.tca.hi.lo.app", + "version":"1.0.0", + "policyAcronym": "TCA", + "updatedDate": "2020-01-31T20:49:48.658795600Z", + "updatedBy": "admin" }); } }); @@ -60,11 +60,12 @@ describe('Verify ViewToscaPolicyModal', () => { json: () => { return Promise.resolve({ "index": "1", - "toscaModelName":"DCAE_MTCAConfig", - "version":"16", - "userId":"aj928f", - "policyType":"mtca", - "lastUpdatedDate":"05-07-2019 19:09:42" + "policyModelTosca":"TCA", + "policyModelType":"onap.policies.monitoring.cdap.tca.hi.lo.app", + "version":"1.0.0", + "policyAcronym": "TCA", + "updatedDate": "2020-01-31T20:49:48.658795600Z", + "updatedBy": "admin" }); } }); @@ -95,12 +96,12 @@ describe('Verify ViewToscaPolicyModal', () => { json: () => { return Promise.resolve({ "index": "1", - "toscaModelYaml":"MTCA", - "toscaModelName":"DCAE_MTCAConfig", - "version":"16", - "userId":"aj928f", - "policyType":"mtca", - "lastUpdatedDate":"05-07-2019 19:09:42" + "policyModelTosca":"TCA", + "policyModelType":"onap.policies.monitoring.cdap.tca.hi.lo.app", + "version":"1.0.0", + "policyAcronym": "TCA", + "updatedDate": "2020-01-31T20:49:48.658795600Z", + "updatedBy": "admin" }); } }); @@ -108,12 +109,12 @@ describe('Verify ViewToscaPolicyModal', () => { const component = shallow(); component.setState({ toscaNames: { "index": "1", - "toscaModelYaml": "MTCA", - "toscaModelName": "DCAE_MTCAConfig", - "version" : "16", - "userId" : "aj928f", - "policyType" : "mtca", - "lastUpdatedDate" : "05-07-2019 19:09:42" + "policyModelTosca":"TCA", + "policyModelType":"onap.policies.monitoring.cdap.tca.hi.lo.app", + "version":"1.0.0", + "policyAcronym": "TCA", + "updatedDate": "2020-01-31T20:49:48.658795600Z", + "updatedBy": "admin" } }); expect(component).toMatchSnapshot(); @@ -127,12 +128,12 @@ describe('Verify ViewToscaPolicyModal', () => { json: () => { return Promise.resolve({ "index": "1", - "toscaModelYaml":"MTCA", - "toscaModelName":"DCAE_MTCAConfig", - "version":"16", - "userId":"aj928f", - "policyType":"mtca", - "lastUpdatedDate":"05-07-2019 19:09:42" + "policyModelTosca":"TCA", + "policyModelType":"onap.policies.monitoring.cdap.tca.hi.lo.app", + "version":"1.0.0", + "policyAcronym": "TCA", + "updatedDate": "2020-01-31T20:49:48.658795600Z", + "updatedBy": "admin" }); } }); @@ -149,17 +150,17 @@ describe('Verify ViewToscaPolicyModal', () => { json: () => { return Promise.resolve({ "index": "1", - "toscaModelYaml":"MTCA", - "toscaModelName":"DCAE_MTCAConfig", - "version":"16", - "userId":"aj928f", - "policyType":"mtca", - "lastUpdatedDate":"05-07-2019 19:09:42" + "policyModelTosca":"TCA", + "policyModelType":"onap.policies.monitoring.cdap.tca.hi.lo.app", + "version":"1.0.0", + "policyAcronym":"TCA", + "updatedDate": "2020-01-31T20:49:48.658795600Z", + "updatedBy": "admin" }); } }); }); - const yamlContent = 'MTCA Tosca model details'; + const yamlContent = 'TCA Tosca model details'; const component = shallow(); component.find('[value="Please select Tosca model to view the details"]').prop('onChange')({ target: { value: yamlContent }}); expect(component.state('content')).toEqual(yamlContent); @@ -173,12 +174,12 @@ describe('Verify ViewToscaPolicyModal', () => { json: () => { return Promise.resolve({ "index": "1", - "toscaModelYaml":"MTCA", - "toscaModelName":"DCAE_MTCAConfig", - "version":"16", - "userId":"aj928f", - "policyType":"mtca", - "lastUpdatedDate":"05-07-2019 19:09:42" + "policyModelTosca":"TCA", + "policyModelType":"onap.policies.monitoring.cdap.tca.hi.lo.app", + "version":"1.0.0", + "policyAcronym": "TCA", + "updatedDate": "2020-01-31T20:49:48.658795600Z", + "updatedBy": "admin" }); } }); diff --git a/ui-react/src/components/dialogs/Tosca/__snapshots__/UploadToscaPolicyModal.test.js.snap b/ui-react/src/components/dialogs/Tosca/__snapshots__/UploadToscaPolicyModal.test.js.snap new file mode 100644 index 00000000..1b5cd82a --- /dev/null +++ b/ui-react/src/components/dialogs/Tosca/__snapshots__/UploadToscaPolicyModal.test.js.snap @@ -0,0 +1,111 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Test Upload Tosca Policy Model Test handleMicroServiceName 1`] = ` + + + + Upload Tosca Modal + + + + + + + + +

+ + + Micro Service Name: + + + + + + + + + + +`; diff --git a/ui-react/src/components/dialogs/Tosca/__snapshots__/ViewToscaPolicyModal.test.js.snap b/ui-react/src/components/dialogs/Tosca/__snapshots__/ViewToscaPolicyModal.test.js.snap index e7294c08..fc5eef02 100644 --- a/ui-react/src/components/dialogs/Tosca/__snapshots__/ViewToscaPolicyModal.test.js.snap +++ b/ui-react/src/components/dialogs/Tosca/__snapshots__/ViewToscaPolicyModal.test.js.snap @@ -30,29 +30,29 @@ exports[`Verify ViewToscaPolicyModal Test the tosca model view render method 1`] "cellStyle": Object { "border": "1px solid black", }, - "field": "toscaModelName", + "field": "policyModelType", "headerStyle": Object { "backgroundColor": "#ddd", "border": "2px solid black", }, - "title": "Micro Service Name", + "title": "Policy Model Type", }, Object { "cellStyle": Object { "border": "1px solid black", }, - "field": "policyType", + "field": "policyAcronym", "headerStyle": Object { "backgroundColor": "#ddd", "border": "2px solid black", }, - "title": "PolicyType", + "title": "Policy Acronym", }, Object { "cellStyle": Object { "border": "1px solid black", }, - "field": "toscaModelRevisions[0].version", + "field": "version", "headerStyle": Object { "backgroundColor": "#ddd", "border": "2px solid black", @@ -63,7 +63,7 @@ exports[`Verify ViewToscaPolicyModal Test the tosca model view render method 1`] "cellStyle": Object { "border": "1px solid black", }, - "field": "userId", + "field": "updatedBy", "headerStyle": Object { "backgroundColor": "#ddd", "border": "2px solid black", @@ -75,7 +75,7 @@ exports[`Verify ViewToscaPolicyModal Test the tosca model view render method 1`] "border": "1px solid black", }, "editable": "never", - "field": "lastUpdatedDate", + "field": "updatedDate", "headerStyle": Object { "backgroundColor": "#ddd", "border": "2px solid black", @@ -84,17 +84,7 @@ exports[`Verify ViewToscaPolicyModal Test the tosca model view render method 1`] }, ] } - data={ - Object { - "index": "1", - "lastUpdatedDate": "05-07-2019 19:09:42", - "policyType": "mtca", - "toscaModelName": "DCAE_MTCAConfig", - "toscaModelYaml": "MTCA", - "userId": "aj928f", - "version": "16", - } - } + data={Array []} icons={ Object { "FirstPage": Object { diff --git a/ui-react/src/components/menu/MenuBar.js b/ui-react/src/components/menu/MenuBar.js index 41a10548..6fae008e 100644 --- a/ui-react/src/components/menu/MenuBar.js +++ b/ui-react/src/components/menu/MenuBar.js @@ -88,7 +88,8 @@ export default class MenuBar extends React.Component { - View Tosca Policy Models + Upload Tosca Policy Model + View Tosca Policy Models View Blueprint MicroService Templates diff --git a/ui-react/src/components/menu/__snapshots__/MenuBar.test.js.snap b/ui-react/src/components/menu/__snapshots__/MenuBar.test.js.snap index c17214aa..7ed386ff 100644 --- a/ui-react/src/components/menu/__snapshots__/MenuBar.test.js.snap +++ b/ui-react/src/components/menu/__snapshots__/MenuBar.test.js.snap @@ -38,6 +38,57 @@ exports[`Verify MenuBar Test the render method 1`] = ` [Function], "; } +", + ], + }, + "displayName": "Styled(Link)", + "foldedComponentIds": Array [], + "render": [Function], + "styledComponentId": "sc-bdVaJa", + "target": [Function], + "toString": [Function], + "warnTooManyClasses": [Function], + "withComponent": [Function], + } + } + disabled={false} + to="/uploadToscaPolicyModal" + > + Upload Tosca Policy Model + +