From 723de7f63f0951d0cfe7a23956cf9d00128809b1 Mon Sep 17 00:00:00 2001 From: sebdet Date: Thu, 12 Mar 2020 14:38:07 -0700 Subject: Fix the new tosca converter Fix the metadata section analysis and make the tosca parser more configurable (in applications.properties) Issue-ID: CLAMP-580 Signed-off-by: sebdet Change-Id: I9068bd9dc89861c640660a7f78fae2cb70bdc178 Signed-off-by: sebdet --- .../onap/clamp/clds/tosca/update/ArrayField.java | 72 -- .../onap/clamp/clds/tosca/update/Constraint.java | 221 ----- .../clamp/clds/tosca/update/MetadataParser.java | 46 - .../org/onap/clamp/clds/tosca/update/Property.java | 134 --- .../org/onap/clamp/clds/tosca/update/Template.java | 224 ----- .../clamp/clds/tosca/update/TemplateField.java | 148 ---- .../clds/tosca/update/ToscaConverterManager.java | 192 ---- .../clds/tosca/update/ToscaConverterToJson.java | 331 ------- .../ToscaConverterWithDictionarySupport.java | 93 ++ .../onap/clamp/clds/tosca/update/ToscaElement.java | 121 --- .../clamp/clds/tosca/update/ToscaItemsParser.java | 109 --- .../clds/tosca/update/elements/ArrayField.java | 72 ++ .../clds/tosca/update/elements/Constraint.java | 222 +++++ .../clds/tosca/update/elements/ToscaElement.java | 121 +++ .../update/elements/ToscaElementProperty.java | 135 +++ .../update/parser/ToscaConverterToJsonSchema.java | 340 +++++++ .../tosca/update/parser/ToscaElementParser.java | 103 +++ .../parser/metadata/ToscaMetadataParser.java | 31 + .../ToscaMetadataParserWithDictionarySupport.java | 178 ++++ .../clds/tosca/update/templates/JsonTemplate.java | 224 +++++ .../tosca/update/templates/JsonTemplateField.java | 149 ++++ .../update/templates/JsonTemplateManager.java | 184 ++++ .../clamp/clds/util/drawing/ClampGraphBuilder.java | 2 +- src/main/java/org/onap/clamp/loop/Loop.java | 38 +- .../java/org/onap/clamp/loop/LoopController.java | 3 +- src/main/java/org/onap/clamp/loop/LoopService.java | 23 +- .../clamp/loop/service/CsarServiceInstaller.java | 13 +- .../java/org/onap/clamp/loop/service/Service.java | 12 +- .../onap/clamp/loop/template/LoopElementModel.java | 27 +- .../clamp/loop/template/PolicyModelsService.java | 2 +- src/main/java/org/onap/clamp/policy/Policy.java | 23 - .../policy/microservice/MicroServicePolicy.java | 51 +- .../policy/operational/OperationalPolicy.java | 99 ++- .../OperationalPolicyRepresentationBuilder.java | 19 +- src/main/resources/META-INF/resources/swagger.html | 941 +++++++++++++++----- src/main/resources/application-noaaf.properties | 4 +- src/main/resources/application.properties | 4 +- .../clds/tosca-converter/default-tosca-types.yaml | 87 ++ .../resources/clds/tosca-converter/templates.json | 398 +++++++++ .../clds/tosca_update/default-tosca-types.yaml | 87 -- .../resources/clds/tosca_update/templates.json | 398 --------- .../clamp/clds/config/CldsUserJsonDecoderTest.java | 4 +- .../it/config/CldsReferencePropertiesItCase.java | 1 + .../tosca/ToscaYamlToJsonConvertorTestItCase.java | 44 +- .../clamp/clds/tosca/update/ArrayFieldTest.java | 16 +- .../clamp/clds/tosca/update/ConstraintTest.java | 48 +- .../clds/tosca/update/JsonTemplateManagerTest.java | 203 +++++ .../clamp/clds/tosca/update/JsonTemplateTest.java | 51 ++ .../onap/clamp/clds/tosca/update/PropertyTest.java | 71 -- .../onap/clamp/clds/tosca/update/TemplateTest.java | 46 - .../tosca/update/ToscaConverterManagerTest.java | 205 ----- .../ToscaConverterWithDictionarySupportItCase.java | 118 +++ .../tosca/update/ToscaElementPropertyTest.java | 79 ++ .../clamp/clds/tosca/update/ToscaElementTest.java | 12 +- .../clds/util/drawing/ClampGraphBuilderTest.java | 13 +- .../clds/util/drawing/SvgLoopGeneratorTest.java | 8 +- .../org/onap/clamp/loop/CsarInstallerItCase.java | 4 +- .../onap/clamp/loop/LoopControllerTestItCase.java | 14 +- .../org/onap/clamp/loop/PolicyComponentTest.java | 10 +- .../microservice/MicroServicePayloadTest.java | 2 +- .../microservice/OperationalPolicyPayloadTest.java | 8 +- .../onap/clamp/util/SemanticVersioningTest.java | 16 +- src/test/resources/application.properties | 4 +- .../resources/clds/camel/rest/clamp-api-v2.xml | 984 --------------------- .../1.0.0?connectionTimeToLive=5000/.file | 4 +- .../1.0.0?connectionTimeToLive=5000/.file | 4 +- .../tosca/new-converter/tca-with-metadata.json | 222 +++++ .../tosca/new-converter/tca-with-metadata.yaml | 184 ++++ 68 files changed, 4225 insertions(+), 3831 deletions(-) delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/ArrayField.java delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/Constraint.java delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/MetadataParser.java delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/Property.java delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/Template.java delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/TemplateField.java delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterManager.java delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterToJson.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterWithDictionarySupport.java delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/ToscaElement.java delete mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/ToscaItemsParser.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/elements/ArrayField.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/elements/Constraint.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/elements/ToscaElement.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/elements/ToscaElementProperty.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/parser/ToscaConverterToJsonSchema.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/parser/ToscaElementParser.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/parser/metadata/ToscaMetadataParser.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/parser/metadata/ToscaMetadataParserWithDictionarySupport.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplate.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplateField.java create mode 100644 src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplateManager.java create mode 100644 src/main/resources/clds/tosca-converter/default-tosca-types.yaml create mode 100644 src/main/resources/clds/tosca-converter/templates.json delete mode 100644 src/main/resources/clds/tosca_update/default-tosca-types.yaml delete mode 100644 src/main/resources/clds/tosca_update/templates.json create mode 100644 src/test/java/org/onap/clamp/clds/tosca/update/JsonTemplateManagerTest.java create mode 100644 src/test/java/org/onap/clamp/clds/tosca/update/JsonTemplateTest.java delete mode 100644 src/test/java/org/onap/clamp/clds/tosca/update/PropertyTest.java delete mode 100644 src/test/java/org/onap/clamp/clds/tosca/update/TemplateTest.java delete mode 100644 src/test/java/org/onap/clamp/clds/tosca/update/ToscaConverterManagerTest.java create mode 100644 src/test/java/org/onap/clamp/clds/tosca/update/ToscaConverterWithDictionarySupportItCase.java create mode 100644 src/test/java/org/onap/clamp/clds/tosca/update/ToscaElementPropertyTest.java delete mode 100644 src/test/resources/clds/camel/rest/clamp-api-v2.xml create mode 100644 src/test/resources/tosca/new-converter/tca-with-metadata.json create mode 100644 src/test/resources/tosca/new-converter/tca-with-metadata.yaml (limited to 'src') diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/ArrayField.java b/src/main/java/org/onap/clamp/clds/tosca/update/ArrayField.java deleted file mode 100644 index 61e40a1e..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/ArrayField.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import com.google.gson.JsonArray; -import java.util.ArrayList; - -public class ArrayField { - - private ArrayList complexFields; - - /** - * Constructor from arraryList. - * - * @param arrayProperties the array properties - */ - public ArrayField(ArrayList arrayProperties) { - this.complexFields = arrayProperties; - } - - /** - * Each LinkedHashMap is parsed to extract the Array and each of its value. They are casted for the JsonObject. - * - * @return JsonArray - */ - public JsonArray deploy() { - - JsonArray subPropertyValuesArray = new JsonArray(); - for (Object arrayElement : complexFields) { - //Cast for each Primitive Type - String typeValue = arrayElement.getClass().getSimpleName(); - switch (typeValue) { - case "String": - subPropertyValuesArray.add((String) arrayElement); - break; - case "Boolean": - subPropertyValuesArray.add((Boolean) arrayElement); - break; - case "Double": - subPropertyValuesArray.add((Number) arrayElement); - break; - case "Integer": - subPropertyValuesArray.add((Number) arrayElement); - break; - default: - break; - } - } - return subPropertyValuesArray; - } -} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/Constraint.java b/src/main/java/org/onap/clamp/clds/tosca/update/Constraint.java deleted file mode 100644 index 4f6b27a6..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/Constraint.java +++ /dev/null @@ -1,221 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.Map.Entry; - -public class Constraint { - - private LinkedHashMap constraints; - private Template template; - - public Constraint(LinkedHashMap constraints, Template template) { - this.template = template; - this.constraints = constraints; - } - - /** - * Deploy the linkedhashmap which contains the constraints, to extract them one to one. - * - * @param jsonSchema The json Schema - * @param typeProperty The ype property - * @return the json object - */ - public JsonObject deployConstraints(JsonObject jsonSchema, String typeProperty) { - for (Entry constraint : constraints.entrySet()) { - this.parseConstraint(jsonSchema, constraint.getKey(), constraint.getValue(), typeProperty); - } - return jsonSchema; - } - - /** - * Each case of Tosca constraints below parse specifically the field in the JsonObject. - * - * @param jsonSchema Json Schema - * @param nameConstraint Name constraint - * @param valueConstraint value constraint - * @param typeProperty Type Property - */ - @SuppressWarnings("unchecked") - public void parseConstraint(JsonObject jsonSchema, String nameConstraint, Object valueConstraint, - String typeProperty) { - switch (nameConstraint) { - case "equal": - checkTemplateField("const", jsonSchema, valueConstraint); - break; - case "greater_than": - checkTemplateField("exclusiveMinimum", jsonSchema, valueConstraint); - break; - case "greater_or_equal": - checkTemplateField("minimum", jsonSchema, valueConstraint); - break; - case "less_than": - checkTemplateField("exclusiveMaximum", jsonSchema, valueConstraint); - break; - case "less_or_equal": - checkTemplateField("maximum", jsonSchema, valueConstraint); - break; - case "in_range": - ArrayList limitValues = (ArrayList) valueConstraint; - checkTemplateField("minimum", jsonSchema, limitValues.get(0)); - checkTemplateField("maximum", jsonSchema, limitValues.get(1)); - break; - case "pattern": - jsonSchema.addProperty(nameConstraint, (String) valueConstraint); - break; - case "length": - this.getSpecificLength(jsonSchema, valueConstraint, typeProperty); - break; - case "min_length": - String[] prefixValues = nameConstraint.split("_"); - this.getLimitValue(jsonSchema, valueConstraint, typeProperty, prefixValues[0]); - break; - case "max_length": - String[] maxtab = nameConstraint.split("_"); - this.getLimitValue(jsonSchema, valueConstraint, typeProperty, maxtab[0]); - break; - default://valid_value - this.getValueArray(jsonSchema, valueConstraint, typeProperty); - break; - } - - } - - /** - * To be done. - * - * @param jsonSchema json schema - * @param fieldValue field value - * @param typeProperty For the complex components, get a specific number of items/properties - */ - public void getSpecificLength(JsonObject jsonSchema, Object fieldValue, String typeProperty) { - switch (typeProperty.toLowerCase()) { - case "string": - checkTemplateField("minLength", jsonSchema, fieldValue); - checkTemplateField("maxLength", jsonSchema, fieldValue); - break; - case "array": - if (fieldValue.equals(1) && template.hasFields("uniqueItems")) { - jsonSchema.addProperty("uniqueItems", true); - } else { - checkTemplateField("minItems", jsonSchema, fieldValue); - checkTemplateField("maxItems", jsonSchema, fieldValue); - } - break; - default:// Map && List - checkTemplateField("minProperties", jsonSchema, fieldValue); - checkTemplateField("maxProperties", jsonSchema, fieldValue); - break; - } - - } - - /** - * To be done. - * - * @param jsonSchema json schema - * @param fieldValue field value - * @param typeProperty type property - * @param side Get the limits fieldValue for the properties : depend of the type of the component - */ - public void getLimitValue(JsonObject jsonSchema, Object fieldValue, String typeProperty, String side) { - switch (typeProperty) { - case "string": - if (side.equals("min")) { - checkTemplateField("minLength", jsonSchema, fieldValue); - } else { - checkTemplateField("maxLength", jsonSchema, fieldValue); - } - break; - default:// Array - if (side.equals("min")) { - checkTemplateField("minItems", jsonSchema, fieldValue); - } else { - checkTemplateField("maxItems", jsonSchema, fieldValue); - } - break; - } - - } - - /** - * To be done. - * - * @param jsonSchema Json schema - * @param fieldValue field value - * @param typeProperty Get as Enum the valid values for the property - */ - public void getValueArray(JsonObject jsonSchema, Object fieldValue, String typeProperty) { - if (template.hasFields("enum")) { - JsonArray enumeration = new JsonArray(); - if (typeProperty.equals("string") || typeProperty.equals("String")) { - ArrayList arrayValues = (ArrayList) fieldValue; - for (String arrayItem : arrayValues) { - enumeration.add(arrayItem); - } - jsonSchema.add("enum", enumeration); - } else { - ArrayList arrayValues = (ArrayList) fieldValue; - for (Number arrayItem : arrayValues) { - enumeration.add(arrayItem); - } - jsonSchema.add("enum", enumeration); - } - } - } - - /** - * To be done. - * - * @param field Field - * @param jsonSchema Json schema - * @param fieldValue Simple way to avoid code duplication - */ - public void checkTemplateField(String field, JsonObject jsonSchema, Object fieldValue) { - if (template.hasFields(field)) { - String typeField = fieldValue.getClass().getSimpleName(); - switch (typeField) { - case "String": - jsonSchema.addProperty(field, (String) fieldValue); - break; - case "Integer": - jsonSchema.addProperty(field, (Integer) fieldValue); - break; - case "Number": - jsonSchema.addProperty(field, (Number) fieldValue); - break; - case "Boolean": - jsonSchema.addProperty(field, (Boolean) fieldValue); - break; - default: - break; - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/MetadataParser.java b/src/main/java/org/onap/clamp/clds/tosca/update/MetadataParser.java deleted file mode 100644 index fb70231f..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/MetadataParser.java +++ /dev/null @@ -1,46 +0,0 @@ - -/*- - * ============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.clds.tosca.update; - -import com.google.gson.JsonObject; -import org.onap.clamp.tosca.DictionaryService; - -public class MetadataParser { - - /** - * This method is used to start the processing of the metadata field. - * - * @param property The property metadata as Json Object - * @param dictionaryService the Dictionary service, if null nothing will be done - * @return The jsonObject structure that must be added to the json schema - */ - public static JsonObject processAllMetadataElement(Property property, DictionaryService dictionaryService) { - if (dictionaryService != null) { - return null; - } else { - return null; - } - } -} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/Property.java b/src/main/java/org/onap/clamp/clds/tosca/update/Property.java deleted file mode 100644 index 0b6e3816..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/Property.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import java.util.ArrayList; -import java.util.LinkedHashMap; - -public class Property { - - /** - * name parameter is used as "key", in the LinkedHashMap of Components. - */ - private String name; - private LinkedHashMap items; - - /** - * Constructor. - * - * @param name the name - * @param items the items - */ - public Property(String name, LinkedHashMap items) { - super(); - this.name = name; - this.items = items; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public LinkedHashMap getItems() { - return items; - } - - public void setItems(LinkedHashMap items) { - this.items = items; - } - - /** - * For each primitive value, requires to get each field Value and cast it and add it in a Json. - * - * @param fieldsContent field - * @param fieldName field - * @param value value - */ - public void addFieldToJson(JsonObject fieldsContent, String fieldName, Object value) { - if (value != null) { - String typeValue = value.getClass().getSimpleName(); - switch (typeValue) { - case "String": - fieldsContent.addProperty(fieldName, (String) value); - break; - case "Boolean": - fieldsContent.addProperty(fieldName, (Boolean) value); - break; - case "Double": - fieldsContent.addProperty(fieldName, (Number) value); - break; - case "Integer": - fieldsContent.addProperty(fieldName, (Integer) value); - break; - default: - fieldsContent.add(fieldName, parseArray((ArrayList) value)); - break; - } - } - } - - /** - * If a field value is an Array, create an Instance of ArrayField to insert if in the JsonObject. - * - * @param arrayProperties array pro - * @return a json array - */ - public JsonArray parseArray(ArrayList arrayProperties) { - JsonArray arrayContent = new JsonArray(); - ArrayList arrayComponent = new ArrayList<>(); - for (Object itemArray : arrayProperties) { - arrayComponent.add(itemArray); - } - ArrayField af = new ArrayField(arrayComponent); - arrayContent = af.deploy(); - return arrayContent; - } - - /** - * Create an instance of Constraint, to extract the values and add it to the Json (according to the type - * * of the current property). - * - * @param json a json - * @param constraints constraints - * @param template template - */ - @SuppressWarnings("unchecked") - public void addConstraintsAsJson(JsonObject json, ArrayList constraints, Template template) { - for (Object constraint : constraints) { - if (constraint instanceof LinkedHashMap) { - LinkedHashMap valueConstraint = (LinkedHashMap) constraint; - Constraint constraintParser = new Constraint(valueConstraint, template); - constraintParser.deployConstraints(json, (String) getItems().get("type")); - } - } - - } - -} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/Template.java b/src/main/java/org/onap/clamp/clds/tosca/update/Template.java deleted file mode 100644 index 6a531aee..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/Template.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import com.google.gson.JsonObject; -import java.util.ArrayList; -import java.util.List; - -public class Template { - - /** - * name parameter is used as "key", in the LinkedHashMap of Templates. - */ - private String name; - private List templateFields; - - public Template(String name) { - this.name = name; - this.templateFields = new ArrayList<>(); - } - - public Template(String name, List templateFields) { - this.name = name; - this.templateFields = templateFields; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getTemplateFields() { - return templateFields; - } - - public void setTemplateFields(List templateFields) { - this.templateFields = templateFields; - } - - /** - * Search in fields if fieldName exists. - * - * @param fieldName The field name - * @return Ture if it exists, false otherwise - */ - public boolean hasFields(String fieldName) { - for (TemplateField templateField : this.getTemplateFields()) { - if (templateField.getTitle().equals(fieldName)) { - return true; - } - } - return false; - } - - /** - * Get a specific Field. - * - * @param fieldName The field name - * @return THe Field found - */ - public TemplateField getSpecificField(String fieldName) { - for (TemplateField templateField : this.getTemplateFields()) { - if (templateField.getTitle().equals(fieldName)) { - return templateField; - } - } - return null; - } - - public void addField(TemplateField templateField) { - templateFields.add(templateField); - } - - public void removeField(TemplateField templateField) { - templateFields.remove(templateField); - } - - /** - * Enable or disable the visibility. - * - * @param nameField THe field name - * @param state True or false - */ - public void setVisibility(String nameField, boolean state) { - for (TemplateField templateField : this.templateFields) { - if (templateField.getTitle().equals(nameField)) { - templateField.setVisible(state); - } - } - } - - /** - * This method defines if a field is static or not. - * - * @param nameField The name of the field - * @param state true or false - */ - public void setStatic(String nameField, boolean state) { - for (TemplateField templateField : this.templateFields) { - if (templateField.getTitle().equals(nameField)) { - templateField.setStaticValue(state); - } - } - } - - /** - * This method updates the value of a specfic field. - * - * @param nameField The name of the field - * @param newValue The new value as Object - */ - public void updateValueField(String nameField, Object newValue) { - for (TemplateField templateField : this.templateFields) { - if (templateField.getTitle().equals(nameField)) { - templateField.setValue(newValue); - } - } - } - - /** - * Compare two templates : size and their contents. - * - * @param template the template - * @return a boolean - */ - public boolean checkFields(Template template) { - boolean duplicateFields = false; - if (template.getTemplateFields().size() == this.getTemplateFields().size()) { - int countMatchingFields = 0; - //loop each component of first - for (TemplateField templateFieldToCheck : template.getTemplateFields()) { - for (TemplateField templateField : this.getTemplateFields()) { - if (templateFieldToCheck.compareWithField(templateField)) { - countMatchingFields++; - } - } - } - - if (template.getTemplateFields().size() == countMatchingFields) { - duplicateFields = true; - } - } - return duplicateFields; - } - - /** - * This method gets the specific field status. - * - * @param field The field name - * @return true or false - */ - public boolean fieldStaticStatus(String field) { - if (this.hasFields(field) && this.getSpecificField(field).getStaticValue().equals(true) - && this.getSpecificField(field).getValue() != null) { - return true; - } - return false; - } - - public boolean isVisible(String field) { - return this.getSpecificField(field).getVisible(); - } - - /** - * Set the value of a property of the Field in the json. - * - * @param jsonSchema The Json schema - * @param fieldName The Field name - * @param value The value - */ - public void setValue(JsonObject jsonSchema, String fieldName, String value) { - if (isVisible(fieldName)) { - if (fieldStaticStatus(fieldName)) { - String defaultValue = (String) this.getSpecificField(fieldName).getValue(); - jsonSchema.addProperty(fieldName, defaultValue); - } - else { - jsonSchema.addProperty(fieldName, value); - } - } - } - - /** - * Inject a static value in the json. - * - * @param jsonSchema The json schema object - * @param fieldName The field name - */ - public void injectStaticValue(JsonObject jsonSchema, String fieldName) { - if (isVisible(fieldName)) { - TemplateField toInject = this.getSpecificField(fieldName); - jsonSchema.addProperty(fieldName, (String) toInject.getValue()); - } - } - - @Override - public String toString() { - return " templateFields : " + templateFields; - } -} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/TemplateField.java b/src/main/java/org/onap/clamp/clds/tosca/update/TemplateField.java deleted file mode 100644 index 34446436..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/TemplateField.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -public class TemplateField { - private String title; - private Object value; - private Boolean visible; - private Boolean staticValue; - - public TemplateField(String title) { - this.title = title; - } - - /** - * Constructor. - * - * @param title The title - * @param value The value - * @param visible visible or not - * @param staticValue The static value - */ - public TemplateField(String title, Object value, Boolean visible, Boolean staticValue) { - this.title = title; - this.value = value; - this.visible = visible; - this.staticValue = staticValue; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Object getValue() { - return value; - } - - public void setValue(Object value) { - this.value = value; - } - - public Boolean getVisible() { - return visible; - } - - public void setVisible(Boolean visible) { - this.visible = visible; - } - - public Boolean getStaticValue() { - return staticValue; - } - - public void setStaticValue(Boolean staticValue) { - this.staticValue = staticValue; - } - - public String toString() { - return title + " " + value + " " + visible + " " + staticValue; - } - - /** - * This method compares two fields. - * - * @param otherField Compare the current object with the one specified - * @return true if they are totally equals, false otherwise - */ - public boolean compareWithField(Object otherField) { - if (this == otherField) { - return true; - } - if (otherField == null || getClass() != otherField.getClass()) { - return false; - } - - TemplateField templateField = (TemplateField) otherField; - - if (title != null ? !title.equals(templateField.title) : templateField.title != null) { - return false; - } - if (value != null ? !value.equals(templateField.value) : templateField.value != null) { - return false; - } - if (visible != null ? !visible.equals(templateField.visible) : templateField.visible != null) { - return false; - } - return staticValue != null ? staticValue.equals(templateField.staticValue) : templateField.staticValue == null; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object == null || getClass() != object.getClass()) { - return false; - } - - TemplateField templateField = (TemplateField) object; - - return title != null ? title.equals(templateField.title) : templateField.title == null; - } - - @Override - public int hashCode() { - return title != null ? title.hashCode() : 0; - } - - /** - * This method test the entire equality. - * - * @param templateField1 object one - * @param templateField2 object two - * @return true if they are totally equals (all attributes, false otherwise - */ - public static boolean fieldsEquals(TemplateField templateField1, TemplateField templateField2) { - return (templateField2.getTitle().equals(templateField1.getTitle()) - && templateField2.getValue().equals(templateField1.getValue()) - && templateField2.getVisible().equals(templateField1.getVisible()) - && templateField2.getStaticValue().equals(templateField1.getStaticValue())); - } - -} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterManager.java b/src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterManager.java deleted file mode 100644 index b3224b04..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterManager.java +++ /dev/null @@ -1,192 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import java.io.IOException; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import org.onap.clamp.clds.util.JsonUtils; - -public class ToscaConverterManager { - - private LinkedHashMap templates; - private LinkedHashMap components; - private ToscaConverterToJson toscaConverterToJson; - private ToscaItemsParser toscaItemsParser; - - /** - * Constructor. - * - * @param toscaYamlContent Policy Tosca Yaml content as string - * @param nativeToscaDatatypes The tosca yaml with tosca native datatypes - * @param templateProperties template properties as string - * @throws IOException in case of failure - */ - public ToscaConverterManager(String toscaYamlContent, String nativeToscaDatatypes, String templateProperties) - throws IOException { - if (toscaYamlContent != null && !toscaYamlContent.isEmpty()) { - this.toscaItemsParser = new ToscaItemsParser(toscaYamlContent, nativeToscaDatatypes); - this.components = toscaItemsParser.getAllItemsFound(); - this.templates = initializeTemplates(templateProperties); - } - else { - components = null; - } - } - - //GETTERS & SETTERS - public LinkedHashMap getComponents() { - return components; - } - - public void setComponents(LinkedHashMap components) { - this.components = components; - } - - public ToscaConverterToJson getParseToJson() { - return toscaConverterToJson; - } - - public void setParseToJson(ToscaConverterToJson toscaConverterToJson) { - this.toscaConverterToJson = toscaConverterToJson; - } - - public LinkedHashMap getTemplates() { - return templates; - } - - public void setTemplates(LinkedHashMap templates) { - this.templates = templates; - } - - public ToscaItemsParser getToscaItemsParser() { - return toscaItemsParser; - } - - /** - * Add a template. - * - * @param name name - * @param templateFields fields - */ - public void addTemplate(String name, List templateFields) { - Template template = new Template(name, templateFields); - //If it is true, the operation does not have any interest : - // replace OR put two different object with the same body - if (!templates.containsKey(template.getName()) || !this.hasTemplate(template)) { - this.templates.put(template.getName(), template); - } - } - - /** - * By name, find and remove a given template. - * - * @param nameTemplate name template - */ - public void removeTemplate(String nameTemplate) { - this.templates.remove(nameTemplate); - } - - /** - * Update Template : adding with true flag, removing with false. - * - * @param nameTemplate name template - * @param templateField field name - * @param operation operation - */ - public void updateTemplate(String nameTemplate, TemplateField templateField, Boolean operation) { - // Operation = true && field is not present => add Field - if (operation && !this.templates.get(nameTemplate).getTemplateFields().contains(templateField)) { - this.templates.get(nameTemplate).addField(templateField); - } - // Operation = false && field is present => remove Field - else if (!operation && this.templates.get(nameTemplate).getTemplateFields().contains(templateField)) { - this.templates.get(nameTemplate).removeField(templateField); - } - } - - /** - * Check if the JSONTemplates have the same bodies. - * - * @param template template - * @return a boolean - */ - public boolean hasTemplate(Template template) { - boolean duplicateTemplate = false; - Collection templatesName = templates.keySet(); - if (templatesName.contains(template.getName())) { - Template existingTemplate = templates.get(template.getName()); - duplicateTemplate = existingTemplate.checkFields(template); - } - return duplicateTemplate; - } - - /** - * For a given Component, get a corresponding JsonObject, through parseToJSON. - * - * @param componentName name - * @return an json object - */ - public JsonObject startConversionToJson(String componentName) throws UnknownComponentException { - this.toscaConverterToJson = new ToscaConverterToJson(components, templates); - if (toscaConverterToJson.matchComponent(componentName) == null) { - throw new UnknownComponentException(componentName); - } - return toscaConverterToJson.getJsonProcess(componentName, "object"); - } - - /** - * Create and complete several Templates from file.properties. - * - * @param jsonTemplates The template properties as String - * @return a map - */ - @SuppressWarnings("unused") - private LinkedHashMap initializeTemplates(String jsonTemplates) { - - LinkedHashMap generatedTemplates = new LinkedHashMap<>(); - JsonObject templates = JsonUtils.GSON.fromJson(jsonTemplates, JsonObject.class); - - for (Map.Entry templateAsJson : templates.entrySet()) { - Template template = new Template(templateAsJson.getKey()); - JsonObject templateBody = (JsonObject) templateAsJson.getValue(); - for (Map.Entry field : templateBody.entrySet()) { - String fieldName = field.getKey(); - JsonObject bodyFieldAsJson = (JsonObject) field.getValue(); - Object fieldValue = bodyFieldAsJson.get("defaultValue").getAsString(); - Boolean fieldVisible = bodyFieldAsJson.get("visible").getAsBoolean(); - Boolean fieldStatic = bodyFieldAsJson.get("static").getAsBoolean(); - TemplateField bodyTemplateField = new TemplateField(fieldName, fieldValue, fieldVisible, fieldStatic); - template.getTemplateFields().add(bodyTemplateField); - } - generatedTemplates.put(template.getName(), template); - } - return generatedTemplates; - } - -} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterToJson.java b/src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterToJson.java deleted file mode 100644 index 297d568b..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterToJson.java +++ /dev/null @@ -1,331 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.Map.Entry; -import org.onap.clamp.tosca.DictionaryService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class ToscaConverterToJson { - private LinkedHashMap components; - private LinkedHashMap templates; - - // if this one is set, the dictionary mechanism is enabled - @Autowired - private DictionaryService dictionaryService; - - public ToscaConverterToJson(LinkedHashMap components, LinkedHashMap templates) { - this.components = components; - this.templates = templates; - } - - /** - * For a given component, launch process to parse it in Json. - * - * @param nameComponent name components - * @return return - */ - public JsonObject getJsonProcess(String nameComponent, String typeComponent) { - JsonObject glob = new JsonObject(); - - if (typeComponent.equals("object")) { - glob = this.getFieldAsObject(matchComponent(nameComponent)); - } - else { - /*glob = this.getFieldAsArray(matchComponent(nameComponent));*/ - } - - return glob; - } - - /** - * Return the classical/general fields of the component, & launch the properties deployment. - * - * @param toscaElement the compo - * @return a json object - */ - public JsonObject getFieldAsObject(ToscaElement toscaElement) { - - JsonObject globalFields = new JsonObject(); - if (templates.get("object").hasFields("title")) { - globalFields.addProperty("title", toscaElement.getName()); - } - if (templates.get("object").hasFields("type")) { - globalFields.addProperty("type", "object"); - } - if (templates.get("object").hasFields("description")) { - if (toscaElement.getDescription() != null) { - globalFields.addProperty("description", toscaElement.getDescription()); - } - } - if (templates.get("object").hasFields("required")) { - globalFields.add("required", this.getRequirements(toscaElement.getName())); - } - if (templates.get("object").hasFields("properties")) { - globalFields.add("properties", this.deploy(toscaElement.getName())); - } - return globalFields; - } - - /** - * Get the required properties of the Component, including the parents properties requirements. - * - * @param nameComponent name component - * @return a json array - */ - public JsonArray getRequirements(String nameComponent) { - JsonArray requirements = new JsonArray(); - ToscaElement toParse = components.get(nameComponent); - //Check for a father component, and launch the same process - if (!toParse.getDerivedFrom().equals("tosca.datatypes.Root") - && !toParse.getDerivedFrom().equals("tosca.policies.Root")) { - requirements.addAll(getRequirements(toParse.getDerivedFrom())); - } - //Each property is checked, and add to the requirement array if it's required - Collection properties = toParse.getProperties().values(); - for (Property property : properties) { - if (property.getItems().containsKey("required") - && property.getItems().get("required").equals(true)) { - requirements.add(property.getName()); - } - } - return requirements; - } - - /** - * The beginning of the recursive process. Get the parents (or not) to launch the same process, and otherwise - * deploy and parse the properties. - * - * @param nameComponent name component - * @return a json object - */ - public JsonObject deploy(String nameComponent) { - JsonObject jsonSchema = new JsonObject(); - ToscaElement toParse = components.get(nameComponent); - //Check for a father component, and launch the same process - if (!toParse.getDerivedFrom().equals("tosca.datatypes.Root") - && !toParse.getDerivedFrom().equals("tosca.policies.Root")) { - jsonSchema = this.getParent(toParse.getDerivedFrom()); - } - //For each component property, check if its a complex properties (a component) or not. In that case, - //launch the analyse of the property. - for (Entry property : toParse.getProperties().entrySet()) { - if (matchComponent((String) property.getValue().getItems().get("type")) != null) { - jsonSchema.add(property.getValue().getName(), - this.getJsonProcess((String) property.getValue().getItems().get("type"), "object")); - } - else { - jsonSchema.add(property.getValue().getName(), this.complexParse(property.getValue())); - } - } - return jsonSchema; - } - - /** - * If a component has a parent, it is deploy in the same way. - * - * @param nameComponent name component - * @return a json object - */ - public JsonObject getParent(String nameComponent) { - return deploy(nameComponent); - } - - /** - * to be done. - * - * @param property property - * @return a json object - */ - @SuppressWarnings("unchecked") - public JsonObject complexParse(Property property) { - JsonObject propertiesInJson = new JsonObject(); - Template currentPropertyTemplate; - String typeProperty = (String) property.getItems().get("type"); - if (typeProperty.toLowerCase().equals("list") || typeProperty.toLowerCase().equals("map")) { - currentPropertyTemplate = templates.get("object"); - } - else { - String propertyType = (String) property.getItems().get("type"); - currentPropertyTemplate = templates.get(propertyType.toLowerCase()); - } - //Each "special" field is analysed, and has a specific treatment - for (String propertyField : property.getItems().keySet()) { - switch (propertyField) { - case "type": - if (currentPropertyTemplate.hasFields(propertyField)) { - String fieldtype = (String) property.getItems().get(propertyField); - switch (fieldtype.toLowerCase()) { - case "list": - propertiesInJson.addProperty("type", "array"); - break; - case "map": - propertiesInJson.addProperty("type", "object"); - break; - case "scalar-unit.time": - case "scalar-unit.frequency": - case "scalar-unit.size": - propertiesInJson.addProperty("type", "string"); - break; - case "timestamp": - propertiesInJson.addProperty("type", "string"); - propertiesInJson.addProperty("format", "date-time"); - break; - case "float": - propertiesInJson.addProperty("type", "number"); - break; - case "range": - propertiesInJson.addProperty("type", "integer"); - if (!checkConstraintPresence(property, "greater_than") - && currentPropertyTemplate.hasFields("exclusiveMinimum")) { - propertiesInJson.addProperty("exclusiveMinimum", false); - } - if (!checkConstraintPresence(property, "less_than") - && currentPropertyTemplate.hasFields("exclusiveMaximum")) { - propertiesInJson.addProperty("exclusiveMaximum", false); - } - break; - default: - propertiesInJson.addProperty("type", currentPropertyTemplate.getName()); - break; - } - } - break; - case "metadata": - propertiesInJson.add("enum", MetadataParser.processAllMetadataElement(property, - dictionaryService)); - break; - case "constraints": - property.addConstraintsAsJson(propertiesInJson, - (ArrayList) property.getItems().get("constraints"), - currentPropertyTemplate); - break; - case "entry_schema": - //Here, a way to check if entry is a component (datatype) or a simple string - if (matchComponent(this.extractSpecificFieldFromMap(property, "entry_schema")) != null) { - String nameComponent = this.extractSpecificFieldFromMap(property, "entry_schema"); - ToscaConverterToJson child = new ToscaConverterToJson(components, templates); - JsonObject propertiesContainer = new JsonObject(); - - switch ((String) property.getItems().get("type")) { - case "map": // Get it as an object - JsonObject componentAsProperty = child.getJsonProcess(nameComponent, "object"); - propertiesContainer.add(nameComponent, componentAsProperty); - if (currentPropertyTemplate.hasFields("properties")) { - propertiesInJson.add("properties", propertiesContainer); - } - break; - default://list : get it as an Array - JsonObject componentAsItem = child.getJsonProcess(nameComponent, "object"); - if (currentPropertyTemplate.hasFields("properties")) { - propertiesInJson.add("items", componentAsItem); - } - break; - } - - } - // Native cases - else if (property.getItems().get("type").equals("list")) { - JsonObject itemContainer = new JsonObject(); - String valueInEntrySchema = this.extractSpecificFieldFromMap(property, "entry_schema"); - itemContainer.addProperty("type", valueInEntrySchema); - propertiesInJson.add("items", itemContainer); - } - // MAP Case, for now nothing - - break; - default: - //Each classical field : type, description, default.. - if (currentPropertyTemplate.hasFields(propertyField) && !propertyField.equals("required")) { - property.addFieldToJson(propertiesInJson, propertyField, - property.getItems().get(propertyField)); - } - break; - } - } - return propertiesInJson; - } - - /** - * Look for a matching Component for the name paramater, in the components list. - * - * @param name the name - * @return a component - */ - public ToscaElement matchComponent(String name) { - ToscaElement correspondingToscaElement = null; - if (components == null) { - return null; - } - for (ToscaElement toscaElement : components.values()) { - if (toscaElement.getName().equals(name)) { - correspondingToscaElement = toscaElement; - } - } - return correspondingToscaElement; - } - - /** - * Simple method to extract quickly a type field from particular property item. - * - * @param property the property - * @param fieldName the fieldname - * @return a string - */ - @SuppressWarnings("unchecked") - public String extractSpecificFieldFromMap(Property property, String fieldName) { - LinkedHashMap entrySchemaFields = - (LinkedHashMap) property.getItems().get(fieldName); - return entrySchemaFields.get("type"); - } - - /** - * Check if a constraint, for a specific property, is there. - * - * @param property property - * @param nameConstraint name constraint - * @return a flag boolean - */ - public boolean checkConstraintPresence(Property property, String nameConstraint) { - boolean presentConstraint = false; - if (property.getItems().containsKey("constraints")) { - ArrayList constraints = (ArrayList) property.getItems().get("constraints"); - for (Object constraint : constraints) { - if (constraint instanceof LinkedHashMap) { - if (((LinkedHashMap) constraint).containsKey(nameConstraint)) { - presentConstraint = true; - } - } - } - } - return presentConstraint; - } -} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterWithDictionarySupport.java b/src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterWithDictionarySupport.java new file mode 100644 index 00000000..c1bf1ad8 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/ToscaConverterWithDictionarySupport.java @@ -0,0 +1,93 @@ +/*- + * ============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.clds.tosca.update; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.gson.JsonObject; +import java.io.IOException; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.tosca.update.parser.metadata.ToscaMetadataParser; +import org.onap.clamp.clds.tosca.update.parser.metadata.ToscaMetadataParserWithDictionarySupport; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplateManager; +import org.onap.clamp.clds.util.JsonUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ToscaConverterWithDictionarySupport { + + private static final EELFLogger logger = + EELFManager.getInstance().getLogger(ToscaConverterWithDictionarySupport.class); + + private ClampProperties clampProperties; + private ToscaMetadataParser metadataParser; + + /** + * Constructor with Spring support. + * + * @param clampProperties Clamp Spring properties + * @param metadataParser Metadata parser + */ + @Autowired + public ToscaConverterWithDictionarySupport(ClampProperties clampProperties, + ToscaMetadataParserWithDictionarySupport metadataParser) { + this.clampProperties = clampProperties; + this.metadataParser = metadataParser; + } + + /** + * This method converts a tosca file to a json schema. + * It uses some parameters specified in the application.properties. + * + * @param toscaFile The tosca file as String + * @param policyTypeToDecode The policy type to decode + * @return A json object being a json schema + */ + public JsonObject convertToscaToJsonSchemaObject(String toscaFile, String policyTypeToDecode) { + try { + return new JsonTemplateManager(toscaFile, + clampProperties.getFileContent("tosca.converter.default.datatypes"), + clampProperties.getFileContent("tosca.converter.json.schema.templates")) + .getJsonSchemaForPolicyType(policyTypeToDecode, Boolean.parseBoolean(clampProperties.getStringValue( + "tosca.converter.dictionary.support.enabled")) ? metadataParser : null); + } catch (IOException | UnknownComponentException e) { + logger.error("Unable to convert the tosca properly, exception caught during the decoding", + e); + return new JsonObject(); + } + } + + /** + * This method converts a tosca file to a json schema. + * It uses some parameters specified in the application.properties. + * + * @param toscaFile The tosca file as String + * @param policyTypeToDecode The policy type to decode + * @return A String containing the json schema + */ + public String convertToscaToJsonSchemaString(String toscaFile, String policyTypeToDecode) { + return JsonUtils.GSON.toJson(this.convertToscaToJsonSchemaObject(toscaFile, policyTypeToDecode)); + } +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/ToscaElement.java b/src/main/java/org/onap/clamp/clds/tosca/update/ToscaElement.java deleted file mode 100644 index d702cda5..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/ToscaElement.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import java.util.ArrayList; -import java.util.LinkedHashMap; - -public class ToscaElement { - - /** - * name parameter is used as "key", in the LinkedHashMap of Components. - */ - private String name; - private String derivedFrom; - private String version; - private String typeVersion; - private String description; - private LinkedHashMap properties; - - public ToscaElement() { - } - - /** - * Constructor. - * - * @param name name - * @param derivedFrom derivedFrom - * @param description description - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - public ToscaElement(String name, String derivedFrom, String description) { - super(); - this.name = name; - this.derivedFrom = derivedFrom; - this.description = description; - this.properties = new LinkedHashMap(); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDerivedFrom() { - return derivedFrom; - } - - public void setDerivedFrom(String derivedFrom) { - this.derivedFrom = derivedFrom; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getTypeVersion() { - return typeVersion; - } - - public void setTypeVersion(String typeVersion) { - this.typeVersion = typeVersion; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public LinkedHashMap getProperties() { - return properties; - } - - public void setProperties(LinkedHashMap properties) { - this.properties = properties; - } - - public void addProperties(Property property) { - this.properties.put(property.getName(), property); - } - - public ArrayList propertiesNames() { - return new ArrayList<>(properties.keySet()); - } - - @Override - public String toString() { - return name + ": " + description + ", version: " + version + ", nb de properties: " + properties.size() - + System.getProperty("line.separator") + propertiesNames(); - } -} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/ToscaItemsParser.java b/src/main/java/org/onap/clamp/clds/tosca/update/ToscaItemsParser.java deleted file mode 100644 index 443a4b0c..00000000 --- a/src/main/java/org/onap/clamp/clds/tosca/update/ToscaItemsParser.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Map.Entry; -import org.yaml.snakeyaml.Yaml; - -public class ToscaItemsParser { - private LinkedHashMap allItemsFound; - - /** - * Constructor. - * - * @param toscaYaml The tosca to parse - * @param toscaNativeDataTypeYaml THe name of the policy type to search - */ - public ToscaItemsParser(String toscaYaml, String toscaNativeDataTypeYaml) { - this.allItemsFound = searchAllToscaElements(toscaYaml, toscaNativeDataTypeYaml); - } - - public LinkedHashMap getAllItemsFound() { - return allItemsFound; - } - - private static LinkedHashMap searchAllDataTypesAndPolicyTypes(String toscaYaml) { - LinkedHashMap> file = - (LinkedHashMap>) new Yaml().load(toscaYaml); - // Get DataTypes - LinkedHashMap allItemsFound = file.get("data_types"); - allItemsFound = (allItemsFound == null) ? (new LinkedHashMap<>()) : allItemsFound; - // Put the policies and datatypes in the same collection - allItemsFound.putAll(file.get("policy_types")); - return allItemsFound; - } - - private static LinkedHashMap searchAllNativeToscaDataTypes(String toscaNativeYaml) { - return ((LinkedHashMap>) new Yaml().load(toscaNativeYaml)) - .get("data_types"); - } - - /** - * Yaml Parse gets raw policies and datatypes, in different sections : necessary to extract - * all entities and put them at the same level. - * - * @return a map - */ - private static LinkedHashMap searchAllToscaElements(String toscaYaml, - String nativeToscaYaml) { - LinkedHashMap allItemsFound = searchAllDataTypesAndPolicyTypes(toscaYaml); - allItemsFound.putAll(searchAllNativeToscaDataTypes(nativeToscaYaml)); - return parseAllItemsFound(allItemsFound); - } - - /** - * With all the component, get as Map, Components and Components properties are created. - * - * @param allMaps maps - */ - private static LinkedHashMap parseAllItemsFound(LinkedHashMap allMaps) { - LinkedHashMap allItemsFound = new LinkedHashMap(); - //Component creations, from the file maps - for (Entry itemToParse : allMaps.entrySet()) { - LinkedHashMap componentBody = (LinkedHashMap) itemToParse.getValue(); - ToscaElement toscaElement = - new ToscaElement(itemToParse.getKey(), (String) componentBody.get("derived_from"), - (String) componentBody.get("description")); - //If policy, version and type_version : - if (componentBody.get("type_version") != null) { - toscaElement.setVersion((String) componentBody.get("type_version")); - toscaElement.setTypeVersion((String) componentBody.get("type_version")); - } - //Properties creation, from the map - if (componentBody.get("properties") != null) { - LinkedHashMap properties = - (LinkedHashMap) componentBody.get("properties"); - for (Entry itemToProperty : properties.entrySet()) { - Property property = new Property(itemToProperty.getKey(), - (LinkedHashMap) itemToProperty.getValue()); - toscaElement.addProperties(property); - } - } - allItemsFound.put(toscaElement.getName(), toscaElement); - } - return allItemsFound; - } -} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/elements/ArrayField.java b/src/main/java/org/onap/clamp/clds/tosca/update/elements/ArrayField.java new file mode 100644 index 00000000..83f792f3 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/elements/ArrayField.java @@ -0,0 +1,72 @@ +/*- + * ============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.clds.tosca.update.elements; + +import com.google.gson.JsonArray; +import java.util.ArrayList; + +public class ArrayField { + + private ArrayList complexFields; + + /** + * Constructor from arraryList. + * + * @param arrayProperties the array properties + */ + public ArrayField(ArrayList arrayProperties) { + this.complexFields = arrayProperties; + } + + /** + * Each LinkedHashMap is parsed to extract the Array and each of its value. They are casted for the JsonObject. + * + * @return JsonArray + */ + public JsonArray deploy() { + + JsonArray subPropertyValuesArray = new JsonArray(); + for (Object arrayElement : complexFields) { + //Cast for each Primitive Type + String typeValue = arrayElement.getClass().getSimpleName(); + switch (typeValue) { + case "String": + subPropertyValuesArray.add((String) arrayElement); + break; + case "Boolean": + subPropertyValuesArray.add((Boolean) arrayElement); + break; + case "Double": + subPropertyValuesArray.add((Number) arrayElement); + break; + case "Integer": + subPropertyValuesArray.add((Number) arrayElement); + break; + default: + break; + } + } + return subPropertyValuesArray; + } +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/elements/Constraint.java b/src/main/java/org/onap/clamp/clds/tosca/update/elements/Constraint.java new file mode 100644 index 00000000..d6bd355e --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/elements/Constraint.java @@ -0,0 +1,222 @@ +/*- + * ============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.clds.tosca.update.elements; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map.Entry; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplate; + +public class Constraint { + + private LinkedHashMap constraints; + private JsonTemplate jsonTemplate; + + public Constraint(LinkedHashMap constraints, JsonTemplate jsonTemplate) { + this.jsonTemplate = jsonTemplate; + this.constraints = constraints; + } + + /** + * Deploy the linkedhashmap which contains the constraints, to extract them one to one. + * + * @param jsonSchema The json Schema + * @param typeProperty The ype property + * @return the json object + */ + public JsonObject deployConstraints(JsonObject jsonSchema, String typeProperty) { + for (Entry constraint : constraints.entrySet()) { + this.parseConstraint(jsonSchema, constraint.getKey(), constraint.getValue(), typeProperty); + } + return jsonSchema; + } + + /** + * Each case of Tosca constraints below parse specifically the field in the JsonObject. + * + * @param jsonSchema Json Schema + * @param nameConstraint Name constraint + * @param valueConstraint value constraint + * @param typeProperty Type Property + */ + @SuppressWarnings("unchecked") + public void parseConstraint(JsonObject jsonSchema, String nameConstraint, Object valueConstraint, + String typeProperty) { + switch (nameConstraint) { + case "equal": + checkTemplateField("const", jsonSchema, valueConstraint); + break; + case "greater_than": + checkTemplateField("exclusiveMinimum", jsonSchema, valueConstraint); + break; + case "greater_or_equal": + checkTemplateField("minimum", jsonSchema, valueConstraint); + break; + case "less_than": + checkTemplateField("exclusiveMaximum", jsonSchema, valueConstraint); + break; + case "less_or_equal": + checkTemplateField("maximum", jsonSchema, valueConstraint); + break; + case "in_range": + ArrayList limitValues = (ArrayList) valueConstraint; + checkTemplateField("minimum", jsonSchema, limitValues.get(0)); + checkTemplateField("maximum", jsonSchema, limitValues.get(1)); + break; + case "pattern": + jsonSchema.addProperty(nameConstraint, (String) valueConstraint); + break; + case "length": + this.getSpecificLength(jsonSchema, valueConstraint, typeProperty); + break; + case "min_length": + String[] prefixValues = nameConstraint.split("_"); + this.getLimitValue(jsonSchema, valueConstraint, typeProperty, prefixValues[0]); + break; + case "max_length": + String[] maxtab = nameConstraint.split("_"); + this.getLimitValue(jsonSchema, valueConstraint, typeProperty, maxtab[0]); + break; + default://valid_value + this.getValueArray(jsonSchema, valueConstraint, typeProperty); + break; + } + + } + + /** + * To be done. + * + * @param jsonSchema json schema + * @param fieldValue field value + * @param typeProperty For the complex components, get a specific number of items/properties + */ + public void getSpecificLength(JsonObject jsonSchema, Object fieldValue, String typeProperty) { + switch (typeProperty.toLowerCase()) { + case "string": + checkTemplateField("minLength", jsonSchema, fieldValue); + checkTemplateField("maxLength", jsonSchema, fieldValue); + break; + case "array": + if (fieldValue.equals(1) && jsonTemplate.hasFields("uniqueItems")) { + jsonSchema.addProperty("uniqueItems", true); + } else { + checkTemplateField("minItems", jsonSchema, fieldValue); + checkTemplateField("maxItems", jsonSchema, fieldValue); + } + break; + default:// Map && List + checkTemplateField("minProperties", jsonSchema, fieldValue); + checkTemplateField("maxProperties", jsonSchema, fieldValue); + break; + } + + } + + /** + * To be done. + * + * @param jsonSchema json schema + * @param fieldValue field value + * @param typeProperty type property + * @param side Get the limits fieldValue for the properties : depend of the type of the component + */ + public void getLimitValue(JsonObject jsonSchema, Object fieldValue, String typeProperty, String side) { + switch (typeProperty) { + case "string": + if (side.equals("min")) { + checkTemplateField("minLength", jsonSchema, fieldValue); + } else { + checkTemplateField("maxLength", jsonSchema, fieldValue); + } + break; + default:// Array + if (side.equals("min")) { + checkTemplateField("minItems", jsonSchema, fieldValue); + } else { + checkTemplateField("maxItems", jsonSchema, fieldValue); + } + break; + } + + } + + /** + * To be done. + * + * @param jsonSchema Json schema + * @param fieldValue field value + * @param typeProperty Get as Enum the valid values for the property + */ + public void getValueArray(JsonObject jsonSchema, Object fieldValue, String typeProperty) { + if (jsonTemplate.hasFields("enum")) { + JsonArray enumeration = new JsonArray(); + if (typeProperty.equals("string") || typeProperty.equals("String")) { + ArrayList arrayValues = (ArrayList) fieldValue; + for (String arrayItem : arrayValues) { + enumeration.add(arrayItem); + } + jsonSchema.add("enum", enumeration); + } else { + ArrayList arrayValues = (ArrayList) fieldValue; + for (Number arrayItem : arrayValues) { + enumeration.add(arrayItem); + } + jsonSchema.add("enum", enumeration); + } + } + } + + /** + * To be done. + * + * @param field Field + * @param jsonSchema Json schema + * @param fieldValue Simple way to avoid code duplication + */ + public void checkTemplateField(String field, JsonObject jsonSchema, Object fieldValue) { + if (jsonTemplate.hasFields(field)) { + String typeField = fieldValue.getClass().getSimpleName(); + switch (typeField) { + case "String": + jsonSchema.addProperty(field, (String) fieldValue); + break; + case "Integer": + jsonSchema.addProperty(field, (Integer) fieldValue); + break; + case "Number": + jsonSchema.addProperty(field, (Number) fieldValue); + break; + case "Boolean": + jsonSchema.addProperty(field, (Boolean) fieldValue); + break; + default: + break; + } + } + } + +} \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/elements/ToscaElement.java b/src/main/java/org/onap/clamp/clds/tosca/update/elements/ToscaElement.java new file mode 100644 index 00000000..9035a580 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/elements/ToscaElement.java @@ -0,0 +1,121 @@ +/*- + * ============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.clds.tosca.update.elements; + +import java.util.ArrayList; +import java.util.LinkedHashMap; + +public class ToscaElement { + + /** + * name parameter is used as "key", in the LinkedHashMap of Components. + */ + private String name; + private String derivedFrom; + private String version; + private String typeVersion; + private String description; + private LinkedHashMap properties; + + public ToscaElement() { + } + + /** + * Constructor. + * + * @param name name + * @param derivedFrom derivedFrom + * @param description description + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public ToscaElement(String name, String derivedFrom, String description) { + super(); + this.name = name; + this.derivedFrom = derivedFrom; + this.description = description; + this.properties = new LinkedHashMap(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDerivedFrom() { + return derivedFrom; + } + + public void setDerivedFrom(String derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getTypeVersion() { + return typeVersion; + } + + public void setTypeVersion(String typeVersion) { + this.typeVersion = typeVersion; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public LinkedHashMap getProperties() { + return properties; + } + + public void setProperties(LinkedHashMap properties) { + this.properties = properties; + } + + public void addProperties(ToscaElementProperty toscaElementProperty) { + this.properties.put(toscaElementProperty.getName(), toscaElementProperty); + } + + public ArrayList propertiesNames() { + return new ArrayList<>(properties.keySet()); + } + + @Override + public String toString() { + return name + ": " + description + ", version: " + version + ", nb de properties: " + properties.size() + + System.getProperty("line.separator") + propertiesNames(); + } +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/elements/ToscaElementProperty.java b/src/main/java/org/onap/clamp/clds/tosca/update/elements/ToscaElementProperty.java new file mode 100644 index 00000000..c5ab5a18 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/elements/ToscaElementProperty.java @@ -0,0 +1,135 @@ +/*- + * ============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.clds.tosca.update.elements; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplate; + +public class ToscaElementProperty { + + /** + * name parameter is used as "key", in the LinkedHashMap of Components. + */ + private String name; + private LinkedHashMap items; + + /** + * Constructor. + * + * @param name the name + * @param items the items + */ + public ToscaElementProperty(String name, LinkedHashMap items) { + super(); + this.name = name; + this.items = items; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public LinkedHashMap getItems() { + return items; + } + + public void setItems(LinkedHashMap items) { + this.items = items; + } + + /** + * For each primitive value, requires to get each field Value and cast it and add it in a Json. + * + * @param fieldsContent field + * @param fieldName field + * @param value value + */ + public void addFieldToJson(JsonObject fieldsContent, String fieldName, Object value) { + if (value != null) { + String typeValue = value.getClass().getSimpleName(); + switch (typeValue) { + case "String": + fieldsContent.addProperty(fieldName, (String) value); + break; + case "Boolean": + fieldsContent.addProperty(fieldName, (Boolean) value); + break; + case "Double": + fieldsContent.addProperty(fieldName, (Number) value); + break; + case "Integer": + fieldsContent.addProperty(fieldName, (Integer) value); + break; + default: + fieldsContent.add(fieldName, parseArray((ArrayList) value)); + break; + } + } + } + + /** + * If a field value is an Array, create an Instance of ArrayField to insert if in the JsonObject. + * + * @param arrayProperties array pro + * @return a json array + */ + public JsonArray parseArray(ArrayList arrayProperties) { + JsonArray arrayContent = new JsonArray(); + ArrayList arrayComponent = new ArrayList<>(); + for (Object itemArray : arrayProperties) { + arrayComponent.add(itemArray); + } + ArrayField af = new ArrayField(arrayComponent); + arrayContent = af.deploy(); + return arrayContent; + } + + /** + * Create an instance of Constraint, to extract the values and add it to the Json (according to the type + * * of the current property). + * + * @param json a json + * @param constraints constraints + * @param jsonTemplate template + */ + @SuppressWarnings("unchecked") + public void addConstraintsAsJson(JsonObject json, ArrayList constraints, JsonTemplate jsonTemplate) { + for (Object constraint : constraints) { + if (constraint instanceof LinkedHashMap) { + LinkedHashMap valueConstraint = (LinkedHashMap) constraint; + Constraint constraintParser = new Constraint(valueConstraint, jsonTemplate); + constraintParser.deployConstraints(json, (String) getItems().get("type")); + } + } + + } + +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/parser/ToscaConverterToJsonSchema.java b/src/main/java/org/onap/clamp/clds/tosca/update/parser/ToscaConverterToJsonSchema.java new file mode 100644 index 00000000..cfc0e42a --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/parser/ToscaConverterToJsonSchema.java @@ -0,0 +1,340 @@ +/*- + * ============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.clds.tosca.update.parser; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map.Entry; +import org.onap.clamp.clds.tosca.update.elements.ToscaElement; +import org.onap.clamp.clds.tosca.update.elements.ToscaElementProperty; +import org.onap.clamp.clds.tosca.update.parser.metadata.ToscaMetadataParser; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplate; + +public class ToscaConverterToJsonSchema { + private LinkedHashMap components; + private LinkedHashMap templates; + + private ToscaMetadataParser metadataParser; + + /** + * Constructor. + * + * @param toscaElementsMap All the tosca elements found (policy type + data types + native tosca datatypes) + * @param jsonSchemaTemplates All Json schema templates to use + * @param metadataParser The metadata parser to use for metadata section + */ + public ToscaConverterToJsonSchema(LinkedHashMap toscaElementsMap, + LinkedHashMap jsonSchemaTemplates, + ToscaMetadataParser metadataParser) { + this.components = toscaElementsMap; + this.templates = jsonSchemaTemplates; + this.metadataParser = metadataParser; + } + + /** + * For a given component, launch process to parse it in Json. + * + * @param toscaElementKey name components + * @return return + */ + public JsonObject getJsonSchemaOfToscaElement(String toscaElementKey) { + return this.getFieldAsObject(getToscaElement(toscaElementKey)); + } + + /** + * Return the classical/general fields of the component, & launch the properties deployment. + * + * @param toscaElement the compo + * @return a json object + */ + public JsonObject getFieldAsObject(ToscaElement toscaElement) { + + JsonObject globalFields = new JsonObject(); + if (templates.get("object").hasFields("title")) { + globalFields.addProperty("title", toscaElement.getName()); + } + if (templates.get("object").hasFields("type")) { + globalFields.addProperty("type", "object"); + } + if (templates.get("object").hasFields("description")) { + if (toscaElement.getDescription() != null) { + globalFields.addProperty("description", toscaElement.getDescription()); + } + } + if (templates.get("object").hasFields("required")) { + globalFields.add("required", this.getRequirements(toscaElement.getName())); + } + if (templates.get("object").hasFields("properties")) { + globalFields.add("properties", this.deploy(toscaElement.getName())); + } + return globalFields; + } + + /** + * Get the required properties of the Component, including the parents properties requirements. + * + * @param nameComponent name component + * @return a json array + */ + public JsonArray getRequirements(String nameComponent) { + JsonArray requirements = new JsonArray(); + ToscaElement toParse = components.get(nameComponent); + //Check for a father component, and launch the same process + if (!toParse.getDerivedFrom().equals("tosca.datatypes.Root") + && !toParse.getDerivedFrom().equals("tosca.policies.Root")) { + requirements.addAll(getRequirements(toParse.getDerivedFrom())); + } + //Each property is checked, and add to the requirement array if it's required + Collection properties = toParse.getProperties().values(); + for (ToscaElementProperty toscaElementProperty : properties) { + if (toscaElementProperty.getItems().containsKey("required") + && toscaElementProperty.getItems().get("required").equals(true)) { + requirements.add(toscaElementProperty.getName()); + } + } + return requirements; + } + + /** + * The beginning of the recursive process. Get the parents (or not) to launch the same process, and otherwise + * deploy and parse the properties. + * + * @param nameComponent name component + * @return a json object + */ + public JsonObject deploy(String nameComponent) { + JsonObject jsonSchema = new JsonObject(); + ToscaElement toParse = components.get(nameComponent); + //Check for a father component, and launch the same process + if (!toParse.getDerivedFrom().equals("tosca.datatypes.Root") + && !toParse.getDerivedFrom().equals("tosca.policies.Root")) { + jsonSchema = this.getParent(toParse.getDerivedFrom()); + } + //For each component property, check if its a complex properties (a component) or not. In that case, + //launch the analyse of the property. + for (Entry property : toParse.getProperties().entrySet()) { + if (getToscaElement((String) property.getValue().getItems().get("type")) != null) { + jsonSchema.add(property.getValue().getName(), + this.getJsonSchemaOfToscaElement((String) property.getValue().getItems().get("type"))); + } + else { + jsonSchema.add(property.getValue().getName(), this.complexParse(property.getValue())); + } + } + return jsonSchema; + } + + /** + * If a component has a parent, it is deploy in the same way. + * + * @param nameComponent name component + * @return a json object + */ + public JsonObject getParent(String nameComponent) { + return deploy(nameComponent); + } + + /** + * to be done. + * + * @param toscaElementProperty property + * @return a json object + */ + @SuppressWarnings("unchecked") + public JsonObject complexParse(ToscaElementProperty toscaElementProperty) { + JsonObject propertiesInJson = new JsonObject(); + JsonTemplate currentPropertyJsonTemplate; + String typeProperty = (String) toscaElementProperty.getItems().get("type"); + if (typeProperty.toLowerCase().equals("list") || typeProperty.toLowerCase().equals("map")) { + currentPropertyJsonTemplate = templates.get("object"); + } + else { + String propertyType = (String) toscaElementProperty.getItems().get("type"); + currentPropertyJsonTemplate = templates.get(propertyType.toLowerCase()); + } + //Each "special" field is analysed, and has a specific treatment + for (String propertyField : toscaElementProperty.getItems().keySet()) { + switch (propertyField) { + case "type": + if (currentPropertyJsonTemplate.hasFields(propertyField)) { + String fieldtype = (String) toscaElementProperty.getItems().get(propertyField); + switch (fieldtype.toLowerCase()) { + case "list": + propertiesInJson.addProperty("type", "array"); + break; + case "map": + propertiesInJson.addProperty("type", "object"); + break; + case "scalar-unit.time": + case "scalar-unit.frequency": + case "scalar-unit.size": + propertiesInJson.addProperty("type", "string"); + break; + case "timestamp": + propertiesInJson.addProperty("type", "string"); + propertiesInJson.addProperty("format", "date-time"); + break; + case "float": + propertiesInJson.addProperty("type", "number"); + break; + case "range": + propertiesInJson.addProperty("type", "integer"); + if (!checkConstraintPresence(toscaElementProperty, "greater_than") + && currentPropertyJsonTemplate.hasFields("exclusiveMinimum")) { + propertiesInJson.addProperty("exclusiveMinimum", false); + } + if (!checkConstraintPresence(toscaElementProperty, "less_than") + && currentPropertyJsonTemplate.hasFields("exclusiveMaximum")) { + propertiesInJson.addProperty("exclusiveMaximum", false); + } + break; + default: + propertiesInJson.addProperty("type", currentPropertyJsonTemplate.getName()); + break; + } + } + break; + case "metadata": + if (metadataParser != null) { + metadataParser.processAllMetadataElement(toscaElementProperty).entrySet() + .forEach((jsonEntry) -> { + propertiesInJson.add(jsonEntry.getKey(), + jsonEntry.getValue()); + + }); + } + break; + case "constraints": + toscaElementProperty.addConstraintsAsJson(propertiesInJson, + (ArrayList) toscaElementProperty.getItems().get("constraints"), + currentPropertyJsonTemplate); + break; + case "entry_schema": + //Here, a way to check if entry is a component (datatype) or a simple string + if (getToscaElement(this.extractSpecificFieldFromMap(toscaElementProperty, "entry_schema")) + != null) { + String nameComponent = this.extractSpecificFieldFromMap(toscaElementProperty, "entry_schema"); + ToscaConverterToJsonSchema + child = new ToscaConverterToJsonSchema(components, templates, + metadataParser); + JsonObject propertiesContainer = new JsonObject(); + + switch ((String) toscaElementProperty.getItems().get("type")) { + case "map": // Get it as an object + JsonObject componentAsProperty = child.getJsonSchemaOfToscaElement(nameComponent); + propertiesContainer.add(nameComponent, componentAsProperty); + if (currentPropertyJsonTemplate.hasFields("properties")) { + propertiesInJson.add("properties", propertiesContainer); + } + break; + default://list : get it as an Array + JsonObject componentAsItem = child.getJsonSchemaOfToscaElement(nameComponent); + if (currentPropertyJsonTemplate.hasFields("properties")) { + propertiesInJson.add("items", componentAsItem); + } + break; + } + + } + // Native cases + else if (toscaElementProperty.getItems().get("type").equals("list")) { + JsonObject itemContainer = new JsonObject(); + String valueInEntrySchema = + this.extractSpecificFieldFromMap(toscaElementProperty, "entry_schema"); + itemContainer.addProperty("type", valueInEntrySchema); + propertiesInJson.add("items", itemContainer); + } + // MAP Case, for now nothing + + break; + default: + //Each classical field : type, description, default.. + if (currentPropertyJsonTemplate.hasFields(propertyField) && !propertyField.equals("required")) { + toscaElementProperty.addFieldToJson(propertiesInJson, propertyField, + toscaElementProperty.getItems().get(propertyField)); + } + break; + } + } + return propertiesInJson; + } + + /** + * Look for a matching Component for the name parameter, in the components list. + * + * @param name the tosca element name to search for + * @return a tosca element + */ + public ToscaElement getToscaElement(String name) { + ToscaElement correspondingToscaElement = null; + if (components == null) { + return null; + } + for (ToscaElement toscaElement : components.values()) { + if (toscaElement.getName().equals(name)) { + correspondingToscaElement = toscaElement; + } + } + return correspondingToscaElement; + } + + /** + * Simple method to extract quickly a type field from particular property item. + * + * @param toscaElementProperty the property + * @param fieldName the fieldname + * @return a string + */ + @SuppressWarnings("unchecked") + public String extractSpecificFieldFromMap(ToscaElementProperty toscaElementProperty, String fieldName) { + LinkedHashMap entrySchemaFields = + (LinkedHashMap) toscaElementProperty.getItems().get(fieldName); + return entrySchemaFields.get("type"); + } + + /** + * Check if a constraint, for a specific property, is there. + * + * @param toscaElementProperty property + * @param nameConstraint name constraint + * @return a flag boolean + */ + public boolean checkConstraintPresence(ToscaElementProperty toscaElementProperty, String nameConstraint) { + boolean presentConstraint = false; + if (toscaElementProperty.getItems().containsKey("constraints")) { + ArrayList constraints = (ArrayList) toscaElementProperty.getItems().get("constraints"); + for (Object constraint : constraints) { + if (constraint instanceof LinkedHashMap) { + if (((LinkedHashMap) constraint).containsKey(nameConstraint)) { + presentConstraint = true; + } + } + } + } + return presentConstraint; + } +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/parser/ToscaElementParser.java b/src/main/java/org/onap/clamp/clds/tosca/update/parser/ToscaElementParser.java new file mode 100644 index 00000000..090fcfcf --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/parser/ToscaElementParser.java @@ -0,0 +1,103 @@ +/*- + * ============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.clds.tosca.update.parser; + +import java.util.LinkedHashMap; +import java.util.Map.Entry; +import org.onap.clamp.clds.tosca.update.elements.ToscaElement; +import org.onap.clamp.clds.tosca.update.elements.ToscaElementProperty; +import org.yaml.snakeyaml.Yaml; + +public class ToscaElementParser { + /** + * Constructor. + */ + private ToscaElementParser() { + } + + private static LinkedHashMap searchAllDataTypesAndPolicyTypes(String toscaYaml) { + LinkedHashMap> file = + (LinkedHashMap>) new Yaml().load(toscaYaml); + LinkedHashMap allDataTypesFound = file.get("data_types"); + LinkedHashMap allPolicyTypesFound = file.get("policy_types"); + LinkedHashMap allItemsFound = new LinkedHashMap<>(); + // Put the policies and datatypes in the same collection + allItemsFound = (allDataTypesFound == null) ? (new LinkedHashMap<>()) : allDataTypesFound; + allItemsFound.putAll(allPolicyTypesFound == null ? new LinkedHashMap<>() : allPolicyTypesFound); + return allItemsFound; + } + + private static LinkedHashMap searchAllNativeToscaDataTypes(String toscaNativeYaml) { + return ((LinkedHashMap>) new Yaml().load(toscaNativeYaml)) + .get("data_types"); + } + + /** + * Yaml Parse gets raw policies and datatypes, in different sections : necessary to extract + * all entities and put them at the same level. + * + * @param toscaYaml the tosca model content + * @param nativeToscaYaml the tosca native datatype content + * @return a map of Tosca Element containing all tosca elements found (policy types and datatypes) + */ + public static LinkedHashMap searchAllToscaElements(String toscaYaml, + String nativeToscaYaml) { + LinkedHashMap allItemsFound = searchAllDataTypesAndPolicyTypes(toscaYaml); + allItemsFound.putAll(searchAllNativeToscaDataTypes(nativeToscaYaml)); + return parseAllItemsFound(allItemsFound); + } + + /** + * With all the component, get as Map, Components and Components properties are created. + * + * @param allMaps maps + */ + private static LinkedHashMap parseAllItemsFound(LinkedHashMap allMaps) { + LinkedHashMap allItemsFound = new LinkedHashMap(); + //Component creations, from the file maps + for (Entry itemToParse : allMaps.entrySet()) { + LinkedHashMap componentBody = (LinkedHashMap) itemToParse.getValue(); + ToscaElement toscaElement = + new ToscaElement(itemToParse.getKey(), (String) componentBody.get("derived_from"), + (String) componentBody.get("description")); + //If policy, version and type_version : + if (componentBody.get("type_version") != null) { + toscaElement.setVersion((String) componentBody.get("type_version")); + toscaElement.setTypeVersion((String) componentBody.get("type_version")); + } + //Properties creation, from the map + if (componentBody.get("properties") != null) { + LinkedHashMap properties = + (LinkedHashMap) componentBody.get("properties"); + for (Entry itemToProperty : properties.entrySet()) { + ToscaElementProperty toscaElementProperty = new ToscaElementProperty(itemToProperty.getKey(), + (LinkedHashMap) itemToProperty.getValue()); + toscaElement.addProperties(toscaElementProperty); + } + } + allItemsFound.put(toscaElement.getName(), toscaElement); + } + return allItemsFound; + } +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/parser/metadata/ToscaMetadataParser.java b/src/main/java/org/onap/clamp/clds/tosca/update/parser/metadata/ToscaMetadataParser.java new file mode 100644 index 00000000..a51818e2 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/parser/metadata/ToscaMetadataParser.java @@ -0,0 +1,31 @@ +/*- + * ============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.clds.tosca.update.parser.metadata; + +import com.google.gson.JsonObject; +import org.onap.clamp.clds.tosca.update.elements.ToscaElementProperty; + +public interface ToscaMetadataParser { + JsonObject processAllMetadataElement(ToscaElementProperty toscaElementProperty); +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/parser/metadata/ToscaMetadataParserWithDictionarySupport.java b/src/main/java/org/onap/clamp/clds/tosca/update/parser/metadata/ToscaMetadataParserWithDictionarySupport.java new file mode 100644 index 00000000..349ccee9 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/parser/metadata/ToscaMetadataParserWithDictionarySupport.java @@ -0,0 +1,178 @@ +/*- + * ============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.clds.tosca.update.parser.metadata; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Optional; +import org.json.JSONArray; +import org.onap.clamp.clds.tosca.JsonEditorSchemaConstants; +import org.onap.clamp.clds.tosca.ToscaSchemaConstants; +import org.onap.clamp.clds.tosca.update.elements.ToscaElementProperty; +import org.onap.clamp.tosca.DictionaryElement; +import org.onap.clamp.tosca.DictionaryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ToscaMetadataParserWithDictionarySupport implements ToscaMetadataParser { + + @Autowired + private DictionaryService dictionaryService; + + /** + * This method is used to start the processing of the metadata field. + * + * @param toscaElementProperty The property metadata as Json Object + * @return The jsonObject structure that must be added to the json schema + */ + public JsonObject processAllMetadataElement(ToscaElementProperty toscaElementProperty) { + if (dictionaryService != null) { + return parseMetadataPossibleValues(toscaElementProperty.getItems(), dictionaryService); + } + else { + return null; + } + } + + private static JsonObject parseMetadataPossibleValues(LinkedHashMap childNodeMap, + DictionaryService dictionaryService) { + JsonObject childObject = new JsonObject(); + if (childNodeMap.containsKey(ToscaSchemaConstants.METADATA) + && childNodeMap.get(ToscaSchemaConstants.METADATA) != null) { + LinkedHashMap metadataMap = + (LinkedHashMap) childNodeMap.get(ToscaSchemaConstants.METADATA); + if (metadataMap != null) { + 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((String) value, childObject, dictionaryService); + } + + }); + } + } + } + }); + } + } + return childObject; + } + + private static void processDictionaryElements(String dictionaryReference, JsonObject childObject, + DictionaryService dictionaryService) { + String[] dictionaryKeyArray = + dictionaryReference.substring(dictionaryReference.indexOf(ToscaSchemaConstants.DICTIONARY) + 11, + dictionaryReference.length()).split("#"); + if (dictionaryKeyArray.length > 1) { + // We support only one # as of now. + List dictionaryElements = null; + if (dictionaryKeyArray.length == 2) { + dictionaryElements = new ArrayList<>(dictionaryService.getDictionary(dictionaryKeyArray[0]) + .getDictionaryElements()); + JsonArray subDictionaryNames = new JsonArray(); + new ArrayList(dictionaryService.getDictionary(dictionaryKeyArray[1]) + .getDictionaryElements()).forEach(elem -> subDictionaryNames.add(elem.getShortName())); + + JsonArray jsonArray = new JsonArray(); + + Optional.of(dictionaryElements).get().stream().forEach(c -> { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty(JsonEditorSchemaConstants.TYPE, getJsonType(c.getType())); + if (c.getType() != null + && c.getType().equalsIgnoreCase(ToscaSchemaConstants.TYPE_STRING)) { + jsonObject.addProperty(JsonEditorSchemaConstants.MIN_LENGTH, 1); + + } + jsonObject.addProperty(JsonEditorSchemaConstants.ID, c.getName()); + jsonObject.addProperty(JsonEditorSchemaConstants.LABEL, c.getShortName()); + jsonObject.add(JsonEditorSchemaConstants.OPERATORS, subDictionaryNames); + jsonArray.add(jsonObject); + }); + + JsonObject filterObject = new JsonObject(); + filterObject.add(JsonEditorSchemaConstants.FILTERS, jsonArray); + + childObject.addProperty(JsonEditorSchemaConstants.TYPE, + JsonEditorSchemaConstants.TYPE_QBLDR); + // TO invoke validation on such parameters + childObject.addProperty(JsonEditorSchemaConstants.MIN_LENGTH, 1); + childObject.add(JsonEditorSchemaConstants.QSSCHEMA, filterObject); + + } + } + else { + List dictionaryElements = + new ArrayList<>(dictionaryService.getDictionary(dictionaryKeyArray[0]).getDictionaryElements()); + JsonArray dictionaryNames = new JsonArray(); + JsonArray dictionaryFullNames = new JsonArray(); + dictionaryElements.stream().forEach(c -> { + // Json type will be translated before Policy creation + if (c.getType() != null && !c.getType().equalsIgnoreCase("json")) { + dictionaryFullNames.add(c.getName()); + } + dictionaryNames.add(c.getShortName()); + }); + + if (dictionaryFullNames.size() > 0) { + childObject.add(JsonEditorSchemaConstants.ENUM, dictionaryFullNames); + // Add Enum titles for generated translated values during JSON instance + // generation + JsonObject enumTitles = new JsonObject(); + enumTitles.add(JsonEditorSchemaConstants.ENUM_TITLES, dictionaryNames); + childObject.add(JsonEditorSchemaConstants.OPTIONS, enumTitles); + } + else { + childObject.add(JsonEditorSchemaConstants.ENUM, dictionaryNames); + } + } + } + + private static String getJsonType(String toscaType) { + String jsonType = null; + if (toscaType.equalsIgnoreCase(ToscaSchemaConstants.TYPE_INTEGER)) { + jsonType = JsonEditorSchemaConstants.TYPE_INTEGER; + } + else if (toscaType.equalsIgnoreCase(ToscaSchemaConstants.TYPE_LIST)) { + jsonType = JsonEditorSchemaConstants.TYPE_ARRAY; + } + else { + jsonType = JsonEditorSchemaConstants.TYPE_STRING; + } + return jsonType; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplate.java b/src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplate.java new file mode 100644 index 00000000..f64ba68c --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplate.java @@ -0,0 +1,224 @@ +/*- + * ============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.clds.tosca.update.templates; + +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.List; + +public class JsonTemplate { + + /** + * name parameter is used as "key", in the LinkedHashMap of Templates. + */ + private String name; + private List jsonTemplateFields; + + public JsonTemplate(String name) { + this.name = name; + this.jsonTemplateFields = new ArrayList<>(); + } + + public JsonTemplate(String name, List jsonTemplateFields) { + this.name = name; + this.jsonTemplateFields = jsonTemplateFields; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getJsonTemplateFields() { + return jsonTemplateFields; + } + + public void setJsonTemplateFields(List jsonTemplateFields) { + this.jsonTemplateFields = jsonTemplateFields; + } + + /** + * Search in fields if fieldName exists. + * + * @param fieldName The field name + * @return Ture if it exists, false otherwise + */ + public boolean hasFields(String fieldName) { + for (JsonTemplateField jsonTemplateField : this.getJsonTemplateFields()) { + if (jsonTemplateField.getTitle().equals(fieldName)) { + return true; + } + } + return false; + } + + /** + * Get a specific Field. + * + * @param fieldName The field name + * @return THe Field found + */ + public JsonTemplateField getSpecificField(String fieldName) { + for (JsonTemplateField jsonTemplateField : this.getJsonTemplateFields()) { + if (jsonTemplateField.getTitle().equals(fieldName)) { + return jsonTemplateField; + } + } + return null; + } + + public void addField(JsonTemplateField jsonTemplateField) { + jsonTemplateFields.add(jsonTemplateField); + } + + public void removeField(JsonTemplateField jsonTemplateField) { + jsonTemplateFields.remove(jsonTemplateField); + } + + /** + * Enable or disable the visibility. + * + * @param nameField THe field name + * @param state True or false + */ + public void setVisibility(String nameField, boolean state) { + for (JsonTemplateField jsonTemplateField : this.jsonTemplateFields) { + if (jsonTemplateField.getTitle().equals(nameField)) { + jsonTemplateField.setVisible(state); + } + } + } + + /** + * This method defines if a field is static or not. + * + * @param nameField The name of the field + * @param state true or false + */ + public void setStatic(String nameField, boolean state) { + for (JsonTemplateField jsonTemplateField : this.jsonTemplateFields) { + if (jsonTemplateField.getTitle().equals(nameField)) { + jsonTemplateField.setStaticValue(state); + } + } + } + + /** + * This method updates the value of a specfic field. + * + * @param nameField The name of the field + * @param newValue The new value as Object + */ + public void updateValueField(String nameField, Object newValue) { + for (JsonTemplateField jsonTemplateField : this.jsonTemplateFields) { + if (jsonTemplateField.getTitle().equals(nameField)) { + jsonTemplateField.setValue(newValue); + } + } + } + + /** + * Compare two templates : size and their contents. + * + * @param jsonTemplate the template + * @return a boolean + */ + public boolean checkFields(JsonTemplate jsonTemplate) { + boolean duplicateFields = false; + if (jsonTemplate.getJsonTemplateFields().size() == this.getJsonTemplateFields().size()) { + int countMatchingFields = 0; + //loop each component of first + for (JsonTemplateField jsonTemplateFieldToCheck : jsonTemplate.getJsonTemplateFields()) { + for (JsonTemplateField jsonTemplateField : this.getJsonTemplateFields()) { + if (jsonTemplateFieldToCheck.compareWithField(jsonTemplateField)) { + countMatchingFields++; + } + } + } + + if (jsonTemplate.getJsonTemplateFields().size() == countMatchingFields) { + duplicateFields = true; + } + } + return duplicateFields; + } + + /** + * This method gets the specific field status. + * + * @param field The field name + * @return true or false + */ + public boolean fieldStaticStatus(String field) { + if (this.hasFields(field) && this.getSpecificField(field).getStaticValue().equals(true) + && this.getSpecificField(field).getValue() != null) { + return true; + } + return false; + } + + public boolean isVisible(String field) { + return this.getSpecificField(field).getVisible(); + } + + /** + * Set the value of a property of the Field in the json. + * + * @param jsonSchema The Json schema + * @param fieldName The Field name + * @param value The value + */ + public void setValue(JsonObject jsonSchema, String fieldName, String value) { + if (isVisible(fieldName)) { + if (fieldStaticStatus(fieldName)) { + String defaultValue = (String) this.getSpecificField(fieldName).getValue(); + jsonSchema.addProperty(fieldName, defaultValue); + } + else { + jsonSchema.addProperty(fieldName, value); + } + } + } + + /** + * Inject a static value in the json. + * + * @param jsonSchema The json schema object + * @param fieldName The field name + */ + public void injectStaticValue(JsonObject jsonSchema, String fieldName) { + if (isVisible(fieldName)) { + JsonTemplateField toInject = this.getSpecificField(fieldName); + jsonSchema.addProperty(fieldName, (String) toInject.getValue()); + } + } + + @Override + public String toString() { + return " templateFields : " + jsonTemplateFields; + } +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplateField.java b/src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplateField.java new file mode 100644 index 00000000..a1e15307 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplateField.java @@ -0,0 +1,149 @@ +/*- + * ============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.clds.tosca.update.templates; + +public class JsonTemplateField { + private String title; + private Object value; + private Boolean visible; + private Boolean staticValue; + + public JsonTemplateField(String title) { + this.title = title; + } + + /** + * Constructor. + * + * @param title The title + * @param value The value + * @param visible visible or not + * @param staticValue The static value + */ + public JsonTemplateField(String title, Object value, Boolean visible, Boolean staticValue) { + this.title = title; + this.value = value; + this.visible = visible; + this.staticValue = staticValue; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + public Boolean getVisible() { + return visible; + } + + public void setVisible(Boolean visible) { + this.visible = visible; + } + + public Boolean getStaticValue() { + return staticValue; + } + + public void setStaticValue(Boolean staticValue) { + this.staticValue = staticValue; + } + + public String toString() { + return title + " " + value + " " + visible + " " + staticValue; + } + + /** + * This method compares two fields. + * + * @param otherField Compare the current object with the one specified + * @return true if they are totally equals, false otherwise + */ + public boolean compareWithField(Object otherField) { + if (this == otherField) { + return true; + } + if (otherField == null || getClass() != otherField.getClass()) { + return false; + } + + JsonTemplateField jsonTemplateField = (JsonTemplateField) otherField; + + if (title != null ? !title.equals(jsonTemplateField.title) : jsonTemplateField.title != null) { + return false; + } + if (value != null ? !value.equals(jsonTemplateField.value) : jsonTemplateField.value != null) { + return false; + } + if (visible != null ? !visible.equals(jsonTemplateField.visible) : jsonTemplateField.visible != null) { + return false; + } + return staticValue != null ? staticValue.equals(jsonTemplateField.staticValue) : + jsonTemplateField.staticValue == null; + } + + @Override + public boolean equals(Object object) { + if (this == object) { + return true; + } + if (object == null || getClass() != object.getClass()) { + return false; + } + + JsonTemplateField jsonTemplateField = (JsonTemplateField) object; + + return title != null ? title.equals(jsonTemplateField.title) : jsonTemplateField.title == null; + } + + @Override + public int hashCode() { + return title != null ? title.hashCode() : 0; + } + + /** + * This method test the entire equality. + * + * @param jsonTemplateField1 object one + * @param jsonTemplateField2 object two + * @return true if they are totally equals (all attributes, false otherwise + */ + public static boolean fieldsEquals(JsonTemplateField jsonTemplateField1, JsonTemplateField jsonTemplateField2) { + return (jsonTemplateField2.getTitle().equals(jsonTemplateField1.getTitle()) + && jsonTemplateField2.getValue().equals(jsonTemplateField1.getValue()) + && jsonTemplateField2.getVisible().equals(jsonTemplateField1.getVisible()) + && jsonTemplateField2.getStaticValue().equals(jsonTemplateField1.getStaticValue())); + } + +} diff --git a/src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplateManager.java b/src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplateManager.java new file mode 100644 index 00000000..5e4b6600 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/tosca/update/templates/JsonTemplateManager.java @@ -0,0 +1,184 @@ +/*- + * ============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.clds.tosca.update.templates; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.onap.clamp.clds.tosca.update.UnknownComponentException; +import org.onap.clamp.clds.tosca.update.elements.ToscaElement; +import org.onap.clamp.clds.tosca.update.parser.ToscaConverterToJsonSchema; +import org.onap.clamp.clds.tosca.update.parser.ToscaElementParser; +import org.onap.clamp.clds.tosca.update.parser.metadata.ToscaMetadataParser; +import org.onap.clamp.clds.util.JsonUtils; + +public class JsonTemplateManager { + private LinkedHashMap jsonSchemaTemplates; + private LinkedHashMap toscaElements; + + /** + * Constructor. + * + * @param toscaYamlContent Policy Tosca Yaml content as string + * @param nativeToscaDatatypes The tosca yaml with tosca native datatypes + * @param jsonSchemaTemplates template properties as string + */ + public JsonTemplateManager(String toscaYamlContent, String nativeToscaDatatypes, String jsonSchemaTemplates) { + if (toscaYamlContent != null && !toscaYamlContent.isEmpty()) { + this.toscaElements = ToscaElementParser.searchAllToscaElements(toscaYamlContent, nativeToscaDatatypes); + this.jsonSchemaTemplates = initializeTemplates(jsonSchemaTemplates); + } + else { + toscaElements = null; + } + } + + //GETTERS & SETTERS + public LinkedHashMap getToscaElements() { + return toscaElements; + } + + public void setToscaElements(LinkedHashMap toscaElements) { + this.toscaElements = toscaElements; + } + + public LinkedHashMap getJsonSchemaTemplates() { + return jsonSchemaTemplates; + } + + public void setJsonSchemaTemplates(LinkedHashMap jsonSchemaTemplates) { + this.jsonSchemaTemplates = jsonSchemaTemplates; + } + + /** + * Add a template. + * + * @param name name + * @param jsonTemplateFields fields + */ + public void addTemplate(String name, List jsonTemplateFields) { + JsonTemplate jsonTemplate = new JsonTemplate(name, jsonTemplateFields); + //If it is true, the operation does not have any interest : + // replace OR put two different object with the same body + if (!jsonSchemaTemplates.containsKey(jsonTemplate.getName()) || !this.hasTemplate(jsonTemplate)) { + this.jsonSchemaTemplates.put(jsonTemplate.getName(), jsonTemplate); + } + } + + /** + * By name, find and remove a given template. + * + * @param nameTemplate name template + */ + public void removeTemplate(String nameTemplate) { + this.jsonSchemaTemplates.remove(nameTemplate); + } + + /** + * Update Template : adding with true flag, removing with false. + * + * @param nameTemplate name template + * @param jsonTemplateField field name + * @param operation operation + */ + public void updateTemplate(String nameTemplate, JsonTemplateField jsonTemplateField, Boolean operation) { + // Operation = true && field is not present => add Field + if (operation && !this.jsonSchemaTemplates.get(nameTemplate).getJsonTemplateFields().contains(jsonTemplateField)) { + this.jsonSchemaTemplates.get(nameTemplate).addField(jsonTemplateField); + } + // Operation = false && field is present => remove Field + else if (!operation && this.jsonSchemaTemplates.get(nameTemplate).getJsonTemplateFields().contains(jsonTemplateField)) { + this.jsonSchemaTemplates.get(nameTemplate).removeField(jsonTemplateField); + } + } + + /** + * Check if the JSONTemplates have the same bodies. + * + * @param jsonTemplate template + * @return a boolean + */ + public boolean hasTemplate(JsonTemplate jsonTemplate) { + boolean duplicateTemplate = false; + Collection templatesName = jsonSchemaTemplates.keySet(); + if (templatesName.contains(jsonTemplate.getName())) { + JsonTemplate existingJsonTemplate = jsonSchemaTemplates.get(jsonTemplate.getName()); + duplicateTemplate = existingJsonTemplate.checkFields(jsonTemplate); + } + return duplicateTemplate; + } + + /** + * For a given policy type, get a corresponding JsonObject from the tosca model. + * + * @param policyType The policy type in the tosca + * @param toscaMetadataParser The MetadataParser class that must be used if metadata section are encountered, if null + * they will be skipped + * @return an json object defining the equivalent json schema from the tosca for a given policy type + */ + public JsonObject getJsonSchemaForPolicyType(String policyType, ToscaMetadataParser toscaMetadataParser) + throws UnknownComponentException { + ToscaConverterToJsonSchema + toscaConverterToJsonSchema = new ToscaConverterToJsonSchema(toscaElements, jsonSchemaTemplates, + toscaMetadataParser); + if (toscaConverterToJsonSchema.getToscaElement(policyType) == null) { + throw new UnknownComponentException(policyType); + } + return toscaConverterToJsonSchema.getJsonSchemaOfToscaElement(policyType); + } + + /** + * Create and complete several Templates from file.properties. + * + * @param jsonTemplates The template properties as String + * @return a map + */ + @SuppressWarnings("unused") + private LinkedHashMap initializeTemplates(String jsonTemplates) { + + LinkedHashMap generatedTemplates = new LinkedHashMap<>(); + JsonObject templates = JsonUtils.GSON.fromJson(jsonTemplates, JsonObject.class); + + for (Map.Entry templateAsJson : templates.entrySet()) { + JsonTemplate jsonTemplate = new JsonTemplate(templateAsJson.getKey()); + JsonObject templateBody = (JsonObject) templateAsJson.getValue(); + for (Map.Entry field : templateBody.entrySet()) { + String fieldName = field.getKey(); + JsonObject bodyFieldAsJson = (JsonObject) field.getValue(); + Object fieldValue = bodyFieldAsJson.get("defaultValue").getAsString(); + Boolean fieldVisible = bodyFieldAsJson.get("visible").getAsBoolean(); + Boolean fieldStatic = bodyFieldAsJson.get("static").getAsBoolean(); + JsonTemplateField + bodyJsonTemplateField = new JsonTemplateField(fieldName, fieldValue, fieldVisible, fieldStatic); + jsonTemplate.getJsonTemplateFields().add(bodyJsonTemplateField); + } + generatedTemplates.put(jsonTemplate.getName(), jsonTemplate); + } + return generatedTemplates; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilder.java b/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilder.java index 846b3ab2..6cf342f2 100755 --- a/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilder.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilder.java @@ -88,7 +88,7 @@ public class ClampGraphBuilder { public ClampGraphBuilder addLoopElementModel(LoopElementModel loopElementModel) { if (LoopElementModel.MICRO_SERVICE_TYPE.equals(loopElementModel.getLoopElementType())) { microServices.add(new MicroServicePolicy(loopElementModel.getName(), - loopElementModel.getPolicyModels().first(), false, loopElementModel)); + loopElementModel.getPolicyModels().first(), false,null,loopElementModel,null,null)); } else if (LoopElementModel.OPERATIONAL_POLICY_TYPE.equals(loopElementModel.getLoopElementType())) { policies.add(new OperationalPolicy(loopElementModel.getName(), null, null, loopElementModel.getPolicyModels().first(), loopElementModel, null, null)); diff --git a/src/main/java/org/onap/clamp/loop/Loop.java b/src/main/java/org/onap/clamp/loop/Loop.java index 2bf3decd..dd6fbf05 100644 --- a/src/main/java/org/onap/clamp/loop/Loop.java +++ b/src/main/java/org/onap/clamp/loop/Loop.java @@ -27,6 +27,7 @@ import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; +import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; @@ -48,11 +49,11 @@ import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; -import org.apache.commons.lang3.RandomStringUtils; import org.hibernate.annotations.SortNatural; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; +import org.onap.clamp.clds.tosca.update.ToscaConverterWithDictionarySupport; import org.onap.clamp.clds.util.drawing.SvgLoopGenerator; import org.onap.clamp.dao.model.jsontype.StringJsonUserType; import org.onap.clamp.loop.common.AuditEntity; @@ -63,7 +64,6 @@ import org.onap.clamp.loop.log.LoopLog; import org.onap.clamp.loop.service.Service; import org.onap.clamp.loop.template.LoopElementModel; import org.onap.clamp.loop.template.LoopTemplate; -import org.onap.clamp.policy.Policy; import org.onap.clamp.policy.microservice.MicroServicePolicy; import org.onap.clamp.policy.operational.OperationalPolicy; @@ -164,24 +164,29 @@ public class Loop extends AuditEntity implements Serializable { * @param name The loop name * @param loopTemplate The loop template from which a new loop instance must be created */ - public Loop(String name, LoopTemplate loopTemplate) { - this(name,""); + public Loop(String name, LoopTemplate loopTemplate, ToscaConverterWithDictionarySupport toscaConverter) { + this(name, ""); this.setLoopTemplate(loopTemplate); this.setModelService(loopTemplate.getModelService()); loopTemplate.getLoopElementModelsUsed().forEach(element -> { if (LoopElementModel.MICRO_SERVICE_TYPE.equals(element.getLoopElementModel().getLoopElementType())) { - this.addMicroServicePolicy(new MicroServicePolicy(Policy.generatePolicyName("MICROSERVICE_", - loopTemplate.getModelService().getName(),loopTemplate.getModelService().getVersion(), - RandomStringUtils.randomAlphanumeric(3),RandomStringUtils.randomAlphanumeric(3)), - element.getLoopElementModel().getPolicyModels().first(), false, element.getLoopElementModel())); - } else if (LoopElementModel.OPERATIONAL_POLICY_TYPE + try { + this.addMicroServicePolicy((MicroServicePolicy) element.getLoopElementModel() + .createPolicyInstance(this, toscaConverter)); + } catch (IOException e) { + logger.error("Exception caught when creating the microservice policy instance of the loop " + + "instance", e); + } + } + else if (LoopElementModel.OPERATIONAL_POLICY_TYPE .equals(element.getLoopElementModel().getLoopElementType())) { - this.addOperationalPolicy(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL_", - loopTemplate.getModelService().getName(),loopTemplate.getModelService().getVersion(), - RandomStringUtils.randomAlphanumeric(3),RandomStringUtils.randomAlphanumeric(3)), null, - new JsonObject(), - element.getLoopElementModel().getPolicyModels().first(), element.getLoopElementModel(), - null,null)); + try { + this.addOperationalPolicy((OperationalPolicy) element.getLoopElementModel() + .createPolicyInstance(this, toscaConverter)); + } catch (IOException e) { + logger.error("Exception caught when creating the operational policy instance of the loop instance", + e); + } } }); } @@ -379,7 +384,8 @@ public class Loop extends AuditEntity implements Serializable { if (other.name != null) { return false; } - } else if (!name.equals(other.name)) { + } + else if (!name.equals(other.name)) { return false; } return true; diff --git a/src/main/java/org/onap/clamp/loop/LoopController.java b/src/main/java/org/onap/clamp/loop/LoopController.java index 1a4ae599..d230eb97 100644 --- a/src/main/java/org/onap/clamp/loop/LoopController.java +++ b/src/main/java/org/onap/clamp/loop/LoopController.java @@ -26,6 +26,7 @@ package org.onap.clamp.loop; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; +import java.io.IOException; import java.lang.reflect.Type; import java.util.List; import org.onap.clamp.clds.util.JsonUtils; @@ -105,7 +106,7 @@ public class LoopController { * @param policyVersion The policy model version * @return The loop modified */ - public Loop addOperationalPolicy(String loopName, String policyType, String policyVersion) { + public Loop addOperationalPolicy(String loopName, String policyType, String policyVersion) throws IOException { return loopService.addOperationalPolicy(loopName, policyType, policyVersion); } diff --git a/src/main/java/org/onap/clamp/loop/LoopService.java b/src/main/java/org/onap/clamp/loop/LoopService.java index 953a5947..acd125b7 100644 --- a/src/main/java/org/onap/clamp/loop/LoopService.java +++ b/src/main/java/org/onap/clamp/loop/LoopService.java @@ -24,14 +24,14 @@ package org.onap.clamp.loop; import com.google.gson.JsonObject; +import java.io.IOException; import java.util.List; import java.util.Set; import javax.persistence.EntityNotFoundException; -import org.apache.commons.lang3.RandomStringUtils; +import org.onap.clamp.clds.tosca.update.ToscaConverterWithDictionarySupport; import org.onap.clamp.loop.template.LoopTemplatesService; import org.onap.clamp.loop.template.PolicyModel; import org.onap.clamp.loop.template.PolicyModelsService; -import org.onap.clamp.policy.Policy; import org.onap.clamp.policy.microservice.MicroServicePolicy; import org.onap.clamp.policy.microservice.MicroServicePolicyService; import org.onap.clamp.policy.operational.OperationalPolicy; @@ -57,6 +57,9 @@ public class LoopService { @Autowired private LoopTemplatesService loopTemplateService; + @Autowired + private ToscaConverterWithDictionarySupport toscaConverter; + Loop saveOrUpdateLoop(Loop loop) { return loopsRepository.save(loop); } @@ -76,12 +79,13 @@ public class LoopService { /** * Creates a Loop Instance from Loop Template Name. * - * @param loopName Name of the Loop to be created + * @param loopName Name of the Loop to be created * @param templateName Loop Template to used for Loop * @return Loop Instance */ public Loop createLoopFromTemplate(String loopName, String templateName) { - return loopsRepository.save(new Loop(loopName,loopTemplateService.getLoopTemplate(templateName))); + return loopsRepository + .save(new Loop(loopName, loopTemplateService.getLoopTemplate(templateName), toscaConverter)); } /** @@ -104,22 +108,21 @@ public class LoopService { /** * This method add an operational policy to a loop instance. + * This creates an operational policy from the policy model info and not the loop element model * - * @param loopName The loop name - * @param policyType The policy model type + * @param loopName The loop name + * @param policyType The policy model type * @param policyVersion The policy model version * @return The loop modified */ - Loop addOperationalPolicy(String loopName, String policyType, String policyVersion) { + Loop addOperationalPolicy(String loopName, String policyType, String policyVersion) throws IOException { Loop loop = getLoop(loopName); PolicyModel policyModel = policyModelsService.getPolicyModel(policyType, policyVersion); if (policyModel == null) { return null; } loop.addOperationalPolicy( - new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL", loop.getModelService().getName(), - loop.getModelService().getVersion(), RandomStringUtils.randomAlphanumeric(3), - RandomStringUtils.randomAlphanumeric(4)), loop, null, policyModel, null, null, null)); + new OperationalPolicy(loop,loop.getModelService(), policyModel, toscaConverter)); return loopsRepository.saveAndFlush(loop); } diff --git a/src/main/java/org/onap/clamp/loop/service/CsarServiceInstaller.java b/src/main/java/org/onap/clamp/loop/service/CsarServiceInstaller.java index b7ed1de9..6db6d920 100644 --- a/src/main/java/org/onap/clamp/loop/service/CsarServiceInstaller.java +++ b/src/main/java/org/onap/clamp/loop/service/CsarServiceInstaller.java @@ -27,9 +27,7 @@ package org.onap.clamp.loop.service; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.google.gson.JsonObject; - import java.util.Map.Entry; - import org.onap.clamp.clds.client.CdsServices; import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException; import org.onap.clamp.clds.model.cds.CdsBpWorkFlowListResponse; @@ -96,7 +94,8 @@ public class CsarServiceInstaller { if (SdcTypes.PNF == type || SdcTypes.VF == type) { JsonObject controllerProperties = createCdsArtifactProperties(nodeTemplate); if (controllerProperties != null) { - resourcesPropByType.getAsJsonObject(nodeTemplate.getName()).add("controllerProperties", controllerProperties); + resourcesPropByType.getAsJsonObject(nodeTemplate.getName()) + .add("controllerProperties", controllerProperties); } } } @@ -151,7 +150,8 @@ public class CsarServiceInstaller { Object artifactName = nodeTemplate.getPropertyValue("sdnc_model_name"); Object artifactVersion = nodeTemplate.getPropertyValue("sdnc_model_version"); if (artifactName != null && artifactVersion != null) { - CdsBpWorkFlowListResponse response = queryCdsToGetWorkFlowList(artifactName.toString(), artifactVersion.toString()); + CdsBpWorkFlowListResponse response = + queryCdsToGetWorkFlowList(artifactName.toString(), artifactVersion.toString()); if (response == null) { return null; } @@ -159,7 +159,7 @@ public class CsarServiceInstaller { JsonObject workFlowProps = new JsonObject(); for (String workFlow : response.getWorkflows()) { JsonObject inputs = queryCdsToGetWorkFlowInputProperties(response.getBlueprintName(), - response.getVersion(), workFlow); + response.getVersion(), workFlow); workFlowProps.add(workFlow, inputs); } @@ -176,7 +176,8 @@ public class CsarServiceInstaller { return cdsServices.getBlueprintWorkflowList(artifactName, artifactVersion); } - private JsonObject queryCdsToGetWorkFlowInputProperties(String artifactName, String artifactVersion, String workFlow) { + private JsonObject queryCdsToGetWorkFlowInputProperties(String artifactName, String artifactVersion, + String workFlow) { return cdsServices.getWorkflowInputProperties(artifactName, artifactVersion, workFlow); } } diff --git a/src/main/java/org/onap/clamp/loop/service/Service.java b/src/main/java/org/onap/clamp/loop/service/Service.java index 89c0b2d4..338032a1 100644 --- a/src/main/java/org/onap/clamp/loop/service/Service.java +++ b/src/main/java/org/onap/clamp/loop/service/Service.java @@ -27,15 +27,12 @@ import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; - import java.io.Serializable; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; - import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; @@ -44,7 +41,7 @@ import org.onap.clamp.dao.model.jsontype.StringJsonUserType; @Entity @Table(name = "services") -@TypeDefs({ @TypeDef(name = "json", typeClass = StringJsonUserType.class) }) +@TypeDefs({@TypeDef(name = "json", typeClass = StringJsonUserType.class)}) public class Service implements Serializable { /** @@ -120,6 +117,8 @@ public class Service implements Serializable { } /** + * Name getter. + * * @return the name */ public String getName() { @@ -127,6 +126,8 @@ public class Service implements Serializable { } /** + * Version getter. + * * @return the version */ public String getVersion() { @@ -157,7 +158,8 @@ public class Service implements Serializable { if (other.serviceUuid != null) { return false; } - } else if (!serviceUuid.equals(other.serviceUuid)) { + } + else if (!serviceUuid.equals(other.serviceUuid)) { return false; } return true; 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 47960598..dfdfc42b 100644 --- a/src/main/java/org/onap/clamp/loop/template/LoopElementModel.java +++ b/src/main/java/org/onap/clamp/loop/template/LoopElementModel.java @@ -24,6 +24,7 @@ package org.onap.clamp.loop.template; import com.google.gson.annotations.Expose; +import java.io.IOException; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -40,7 +41,12 @@ import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.SortNatural; +import org.onap.clamp.clds.tosca.update.ToscaConverterWithDictionarySupport; +import org.onap.clamp.loop.Loop; import org.onap.clamp.loop.common.AuditEntity; +import org.onap.clamp.policy.Policy; +import org.onap.clamp.policy.microservice.MicroServicePolicy; +import org.onap.clamp.policy.operational.OperationalPolicy; /** * This class represents a micro service/operational/... model for a loop template. @@ -241,6 +247,24 @@ public class LoopElementModel extends AuditEntity implements Serializable { this.blueprint = blueprint; } + /** + * Create a policy instance from the current loop element model. + * + * @return A Policy object. + * @throws IOException in case of failure when creating an operational policy + */ + public Policy createPolicyInstance(Loop loop, ToscaConverterWithDictionarySupport toscaConverter) + throws IOException { + if (LoopElementModel.MICRO_SERVICE_TYPE.equals(this.getLoopElementType())) { + return new MicroServicePolicy(loop, loop.getModelService(), this, toscaConverter); + } + else if (LoopElementModel.OPERATIONAL_POLICY_TYPE.equals(this.getLoopElementType())) { + return new OperationalPolicy(loop, loop.getModelService(), this, toscaConverter); + } else { + return null; + } + } + @Override public int hashCode() { final int prime = 31; @@ -265,7 +289,8 @@ public class LoopElementModel extends AuditEntity implements Serializable { if (other.name != null) { return false; } - } else if (!name.equals(other.name)) { + } + else if (!name.equals(other.name)) { return false; } return true; 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 aeea55db..ae66c54b 100644 --- a/src/main/java/org/onap/clamp/loop/template/PolicyModelsService.java +++ b/src/main/java/org/onap/clamp/loop/template/PolicyModelsService.java @@ -56,7 +56,7 @@ public class PolicyModelsService { * @return The Policy Model */ public PolicyModel saveOrUpdatePolicyModel(PolicyModel policyModel) { - return policyModelsRepository.save(policyModel); + return policyModelsRepository.saveAndFlush(policyModel); } /** diff --git a/src/main/java/org/onap/clamp/policy/Policy.java b/src/main/java/org/onap/clamp/policy/Policy.java index c9055bf9..3b220646 100644 --- a/src/main/java/org/onap/clamp/policy/Policy.java +++ b/src/main/java/org/onap/clamp/policy/Policy.java @@ -30,7 +30,6 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; -import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; import javax.persistence.Column; @@ -44,9 +43,6 @@ import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; import org.json.JSONObject; -import org.onap.clamp.clds.tosca.update.ToscaConverterManager; -import org.onap.clamp.clds.tosca.update.UnknownComponentException; -import org.onap.clamp.clds.util.ResourceFileUtil; import org.onap.clamp.dao.model.jsontype.StringJsonUserType; import org.onap.clamp.loop.common.AuditEntity; import org.onap.clamp.loop.template.LoopElementModel; @@ -286,23 +282,4 @@ public abstract class Policy extends AuditEntity { .append(blueprintFilename.replaceAll(".yaml", "")); return buffer.toString().replace('.', '_').replaceAll(" ", ""); } - - /** - * This method can be used to generate the json Schema used by the UI. - * - * @param policyToscaModel The tosca model as String that must be converted - * @param policyModelType The tosca model type (the policy_type entry in the tosca) that will used to create the - * json schema - * @return THe Json Schema as JsonObject - * @throws IOException In case of failure when opening the templates.json file - * @throws UnknownComponentException If the policyModelType is not found in the tosca model - */ - public static JsonObject generateJsonRepresentationFromToscaModel(String policyToscaModel, - String policyModelType) - throws IOException, UnknownComponentException { - return new ToscaConverterManager(policyToscaModel,ResourceFileUtil.getResourceAsString( - "clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")) - .startConversionToJson(policyModelType); - } } diff --git a/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java b/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java index b8093ccf..321c12f6 100644 --- a/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java +++ b/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java @@ -27,7 +27,6 @@ import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; -import java.io.IOException; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -38,11 +37,13 @@ import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.persistence.Transient; +import org.apache.commons.lang3.RandomStringUtils; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; -import org.onap.clamp.clds.tosca.update.UnknownComponentException; +import org.onap.clamp.clds.tosca.update.ToscaConverterWithDictionarySupport; import org.onap.clamp.dao.model.jsontype.StringJsonUserType; import org.onap.clamp.loop.Loop; +import org.onap.clamp.loop.service.Service; import org.onap.clamp.loop.template.LoopElementModel; import org.onap.clamp.loop.template.PolicyModel; import org.onap.clamp.policy.Policy; @@ -91,31 +92,10 @@ public class MicroServicePolicy extends Policy implements Serializable { @Column(name = "dcae_blueprint_id") private String dcaeBlueprintId; - public MicroServicePolicy() { - // serialization - } - /** - * The constructor that creates the json representation from the policyTosca - * using the ToscaYamlToJsonConvertor. - * - * @param name The name of the MicroService - * @param policyModel The policy model of the MicroService - * @param shared The flag indicate whether the MicroService is shared + * Constructor for serialization. */ - public MicroServicePolicy(String name, PolicyModel policyModel, Boolean shared, LoopElementModel loopElementModel) { - this.name = name; - this.setPolicyModel(policyModel); - this.shared = shared; - try { - this.setJsonRepresentation( - Policy.generateJsonRepresentationFromToscaModel(policyModel.getPolicyModelTosca(), - policyModel.getPolicyModelType())); - } catch (UnknownComponentException | NullPointerException | IOException e) { - logger.error("Unable to generate the microservice policy Schema ... ", e); - this.setJsonRepresentation(new JsonObject()); - } - this.setLoopElementModel(loopElementModel); + public MicroServicePolicy() { } /** @@ -129,7 +109,7 @@ public class MicroServicePolicy extends Policy implements Serializable { * @param jsonRepresentation The UI representation in json format * @param loopElementModel The loop element model from which this instance should be created * @param pdpGroup The Pdp Group info - * @param pdpSubgroup The Pdp Subgrouop info + * @param pdpSubgroup The Pdp Subgroup info */ public MicroServicePolicy(String name, PolicyModel policyModel, Boolean shared, JsonObject jsonRepresentation, LoopElementModel loopElementModel, String pdpGroup, @@ -143,6 +123,25 @@ public class MicroServicePolicy extends Policy implements Serializable { this.setPdpSubgroup(pdpSubgroup); } + /** + * Constructor with tosca converter. + * + * @param loop The loop instance + * @param service The service model object + * @param loopElementModel The loop element model from which this microservice instance is created + * @param toscaConverter The tosca converter that will used to convert the tosca policy model + */ + public MicroServicePolicy(Loop loop, Service service, LoopElementModel loopElementModel, + ToscaConverterWithDictionarySupport toscaConverter) { + this(Policy.generatePolicyName("MICROSERVICE", service.getName(), service.getVersion(), + RandomStringUtils.randomAlphanumeric(3), RandomStringUtils.randomAlphanumeric(3)), + loopElementModel.getPolicyModels().first(), false, + toscaConverter.convertToscaToJsonSchemaObject( + loopElementModel.getPolicyModels().first().getPolicyModelTosca(), + loopElementModel.getPolicyModels().first().getPolicyModelType()), + loopElementModel, null, null); + } + @Override public String getName() { return name; diff --git a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java index 9cf51633..355a889e 100644 --- a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java +++ b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java @@ -48,11 +48,13 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; +import org.apache.commons.lang3.RandomStringUtils; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; -import org.onap.clamp.clds.tosca.update.UnknownComponentException; +import org.onap.clamp.clds.tosca.update.ToscaConverterWithDictionarySupport; import org.onap.clamp.dao.model.jsontype.StringJsonUserType; import org.onap.clamp.loop.Loop; +import org.onap.clamp.loop.service.Service; import org.onap.clamp.loop.template.LoopElementModel; import org.onap.clamp.loop.template.PolicyModel; import org.onap.clamp.policy.Policy; @@ -80,54 +82,101 @@ public class OperationalPolicy extends Policy implements Serializable { @JoinColumn(name = "loop_id", nullable = false) private Loop loop; + /** + * Constructor for serialization. + */ public OperationalPolicy() { - // Serialization } /** * The constructor. * * @param name The name of the operational policy - * @param loop The loop that uses this operational policy * @param configurationsJson The operational policy property in the format of * json + * @param jsonRepresentation The jsonObject defining the json schema * @param policyModel The policy model associated if any, can be null * @param loopElementModel The loop element from which this instance is supposed to be created * @param pdpGroup The Pdp Group info * @param pdpSubgroup The Pdp Subgroup info */ - public OperationalPolicy(String name, Loop loop, JsonObject configurationsJson, PolicyModel policyModel, + public OperationalPolicy(String name, JsonObject configurationsJson, + JsonObject jsonRepresentation, PolicyModel policyModel, LoopElementModel loopElementModel, String pdpGroup, String pdpSubgroup) { this.name = name; - this.loop = loop; this.setPolicyModel(policyModel); this.setConfigurationsJson(configurationsJson); this.setPdpGroup(pdpGroup); this.setPdpSubgroup(pdpSubgroup); this.setLoopElementModel(loopElementModel); - this.setJsonRepresentation(this.generateJsonRepresentation(policyModel)); + this.setJsonRepresentation(jsonRepresentation); + + } + /** + * Create an operational policy from a loop element model. + * + * @param loop The parent loop + * @param service The loop service + * @param loopElementModel The loop element model + * @param toscaConverter The tosca converter that must be used to create the Json representation + * @throws IOException In case of issues with the legacy files (generated from resource files + */ + public OperationalPolicy(Loop loop, Service service, LoopElementModel loopElementModel, + ToscaConverterWithDictionarySupport toscaConverter) throws IOException { + this(Policy.generatePolicyName("OPERATIONAL", service.getName(), service.getVersion(), + RandomStringUtils.randomAlphanumeric(3), RandomStringUtils.randomAlphanumeric(3)), new JsonObject(), + new JsonObject(), loopElementModel.getPolicyModels().first(), loopElementModel, null, null); + this.setLoop(loop); + this.setJsonRepresentation(generateJsonRepresentation(this, toscaConverter)); + } + + /** + * Create an operational policy from a policy model. + * + * @param loop The parent loop + * @param service The loop service + * @param policyModel The policy model + * @param toscaConverter The tosca converter that must be used to create the Json representation + * @throws IOException In case of issues with the legacy files (generated from resource files + */ + public OperationalPolicy(Loop loop, Service service, PolicyModel policyModel, + ToscaConverterWithDictionarySupport toscaConverter) throws IOException { + this(Policy.generatePolicyName("OPERATIONAL", service.getName(), service.getVersion(), + RandomStringUtils.randomAlphanumeric(3), RandomStringUtils.randomAlphanumeric(3)), new JsonObject(), + new JsonObject(), policyModel, null, null, null); + this.setLoop(loop); + this.setJsonRepresentation(generateJsonRepresentation(this, toscaConverter)); } - private JsonObject generateJsonRepresentation(PolicyModel policyModel) { + /** + * This method can generate a Json representation (json schema) for an operational policy. + * This is mainly to support a legacy case and a generic case. + * + * @param operationalPolicy The operational policy + * @param toscaConverter The tosca converter + * @return The Json Object with Json schema + */ + public static JsonObject generateJsonRepresentation(OperationalPolicy operationalPolicy, + ToscaConverterWithDictionarySupport toscaConverter) + throws IOException { JsonObject jsonReturned = new JsonObject(); - if (policyModel == null) { + if (operationalPolicy.getPolicyModel() == null) { return new JsonObject(); } - try { - if (isLegacy()) { - // Op policy Legacy case - LegacyOperationalPolicy.preloadConfiguration(jsonReturned, loop); - jsonReturned = - OperationalPolicyRepresentationBuilder.generateOperationalPolicySchema(loop.getModelService()); - } else { - // Generic Case - jsonReturned = Policy.generateJsonRepresentationFromToscaModel(policyModel.getPolicyModelTosca(), - policyModel.getPolicyModelType()); - } - } catch (UnknownComponentException | IOException | NullPointerException e) { - logger.error("Unable to generate the operational policy Schema ... ", e); + if (operationalPolicy.isLegacy()) { + // Op policy Legacy case + LegacyOperationalPolicy.preloadConfiguration(jsonReturned, operationalPolicy.loop); + jsonReturned = OperationalPolicyRepresentationBuilder + .generateOperationalPolicySchema(operationalPolicy.loop.getModelService()); + } + else { + // Generic Case + jsonReturned = toscaConverter.convertToscaToJsonSchemaObject( + operationalPolicy.getPolicyModel().getPolicyModelTosca(), + operationalPolicy.getPolicyModel().getPolicyModelType()); } + return jsonReturned; } @@ -178,7 +227,8 @@ public class OperationalPolicy extends Policy implements Serializable { if (other.name != null) { return false; } - } else if (!name.equals(other.name)) { + } + else if (!name.equals(other.name)) { return false; } return true; @@ -243,7 +293,8 @@ public class OperationalPolicy extends Policy implements Serializable { String opPayload = new GsonBuilder().setPrettyPrinting().create().toJson(payload); logger.info("Operational policy payload: " + opPayload); return opPayload; - } else { + } + else { return super.createPolicyPayload(); } } @@ -261,7 +312,7 @@ public class OperationalPolicy extends Policy implements Serializable { if (guardsList != null) { for (JsonElement guardElem : guardsList.getAsJsonArray()) { result.put(guardElem.getAsJsonObject().get("policy-id").getAsString(), - new GsonBuilder().create().toJson(guardElem)); + new GsonBuilder().create().toJson(guardElem)); } } } diff --git a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicyRepresentationBuilder.java b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicyRepresentationBuilder.java index 244f4c27..0298cfde 100644 --- a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicyRepresentationBuilder.java +++ b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicyRepresentationBuilder.java @@ -28,10 +28,8 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; - import java.io.IOException; import java.util.Map.Entry; - import org.onap.clamp.clds.util.JsonUtils; import org.onap.clamp.clds.util.ResourceFileUtil; import org.onap.clamp.loop.service.Service; @@ -79,7 +77,7 @@ public class OperationalPolicyRepresentationBuilder { } private static JsonObject createSchemaProperty(String title, String type, String defaultValue, String readOnlyFlag, - String[] enumArray) { + String[] enumArray) { JsonObject property = new JsonObject(); property.addProperty("title", title); property.addProperty("type", type); @@ -128,8 +126,9 @@ public class OperationalPolicyRepresentationBuilder { modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelName").getAsString(), "True", null)); properties.add("modelInvariantId", - createSchemaProperty("Model Invariant Id (ModelInvariantUUID)", "string", modelVfModules - .get(entry.getKey()).getAsJsonObject().get("vfModuleModelInvariantUUID").getAsString(), + createSchemaProperty("Model Invariant Id (ModelInvariantUUID)", "string", + modelVfModules.get(entry.getKey()).getAsJsonObject().get("vfModuleModelInvariantUUID") + .getAsString(), "True", null)); properties.add("modelVersionId", createSchemaProperty("Model Version Id (ModelUUID)", "string", @@ -144,8 +143,9 @@ public class OperationalPolicyRepresentationBuilder { "True", null)); properties .add("modelCustomizationId", - createSchemaProperty("Customization ID", "string", modelVfModules.get(entry.getKey()) - .getAsJsonObject().get("vfModuleModelCustomizationUUID").getAsString(), "True", + createSchemaProperty("Customization ID", "string", + modelVfModules.get(entry.getKey()).getAsJsonObject() + .get("vfModuleModelCustomizationUUID").getAsString(), "True", null)); vfModuleOneOfSchema.add("properties", properties); @@ -180,7 +180,7 @@ public class OperationalPolicyRepresentationBuilder { JsonObject obj = new JsonObject(); obj.addProperty("title", workflowsEntry.getKey()); obj.add("properties", createPayloadProperty(workflowsEntry.getValue().getAsJsonObject(), - controllerProperties)); + controllerProperties)); schemaArray.add(obj); } @@ -207,7 +207,8 @@ public class OperationalPolicyRepresentationBuilder { StringBuilder builder = new StringBuilder("'").append("artifact_name : ").append(artifactName).append("\n") .append("artifact_version : ").append(artifactVersion).append("\n") .append("mode : async").append("\n") - .append("data : ").append("'").append("\\").append("'").append(data).append("\\").append("'").append("'"); + .append("data : ").append("'").append("\\").append("'").append(data).append("\\").append("'") + .append("'"); return builder.toString(); } } diff --git a/src/main/resources/META-INF/resources/swagger.html b/src/main/resources/META-INF/resources/swagger.html index 29082abf..0451f1e0 100644 --- a/src/main/resources/META-INF/resources/swagger.html +++ b/src/main/resources/META-INF/resources/swagger.html @@ -444,236 +444,280 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
  • 2. Paths
  • 3. Definitions
  • @@ -692,7 +736,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b

    1.2. URI scheme

    -

    Host : localhost:46347
    +

    Host : localhost:41607
    BasePath : /restservices/clds/
    Schemes : HTTP

    @@ -703,7 +747,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b

    2. Paths

    -

    2.1. GET /v1/healthcheck

    +

    2.1. GET /v1/healthcheck

    2.1.1. Responses

    @@ -740,7 +784,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    @@ -774,7 +818,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    @@ -794,7 +838,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b - +

    200

    Output type

    Dictionary

    ClampInformation

    @@ -811,9 +855,46 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.4. PUT /v2/dictionary

    +

    2.4. GET /v2/dictionary

    +
    +

    2.4.1. Responses

    + +++++ + + + + + + + + + + + + + + +
    HTTP CodeDescriptionSchema

    200

    Output type

    Dictionary

    +
    +
    +

    2.4.2. Produces

    +
    +
      +
    • +

      application/json

      +
    • +
    +
    +
    +
    +
    +

    2.5. PUT /v2/dictionary

    -

    2.4.1. Parameters

    +

    2.5.1. Parameters

    @@ -838,7 +919,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.4.2. Responses

    +

    2.5.2. Responses

    @@ -862,7 +943,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.4.3. Consumes

    +

    2.5.3. Consumes

    • @@ -872,7 +953,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.4.4. Produces

    +

    2.5.4. Produces

    • @@ -883,9 +964,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.5. GET /v2/dictionary/secondary/names

    +

    2.6. GET /v2/dictionary/secondary/names

    -

    2.5.1. Responses

    +

    2.6.1. Responses

    @@ -909,7 +990,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.5.2. Produces

    +

    2.6.2. Produces

    • @@ -920,9 +1001,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.6. GET /v2/dictionary/{dictionaryName}

    +

    2.7. GET /v2/dictionary/{dictionaryName}

    -

    2.6.1. Parameters

    +

    2.7.1. Parameters

    @@ -947,7 +1028,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.6.2. Responses

    +

    2.7.2. Responses

    @@ -971,7 +1052,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.6.3. Produces

    +

    2.7.3. Produces

    • @@ -982,9 +1063,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.7. PUT /v2/dictionary/{name}

    +

    2.8. PUT /v2/dictionary/{name}

    -

    2.7.1. Parameters

    +

    2.8.1. Parameters

    @@ -1015,7 +1096,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.7.2. Responses

    +

    2.8.2. Responses

    @@ -1039,7 +1120,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.7.3. Consumes

    +

    2.8.3. Consumes

    • @@ -1049,7 +1130,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.7.4. Produces

    +

    2.8.4. Produces

    • @@ -1060,9 +1141,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.8. DELETE /v2/dictionary/{name}

    +

    2.9. DELETE /v2/dictionary/{name}

    -

    2.8.1. Parameters

    +

    2.9.1. Parameters

    @@ -1087,7 +1168,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.8.2. Responses

    +

    2.9.2. Responses

    @@ -1108,7 +1189,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.8.3. Produces

    +

    2.9.3. Produces

    • @@ -1119,9 +1200,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.9. DELETE /v2/dictionary/{name}/elements/{shortName}

    +

    2.10. DELETE /v2/dictionary/{name}/elements/{shortName}

    -

    2.9.1. Parameters

    +

    2.10.1. Parameters

    @@ -1152,7 +1233,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.9.2. Responses

    +

    2.10.2. Responses

    @@ -1173,7 +1254,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.9.3. Produces

    +

    2.10.3. Produces

    • @@ -1184,9 +1265,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.10. PUT /v2/loop/delete/{loopName}

    +

    2.11. PUT /v2/loop/addOperationaPolicy/{loopName}/policyModel/{policyType}/{policyVersion}

    -

    2.10.1. Parameters

    +

    2.11.1. Parameters

    @@ -1207,11 +1288,157 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b required

    + + + + + + + + + +

    string

    Path

    policyType
    +required

    string

    Path

    policyVersion
    +required

    string

    -

    2.10.2. Responses

    +

    2.11.2. Responses

    + +++++ + + + + + + + + + + + + + + +
    HTTP CodeDescriptionSchema

    200

    Output type

    Loop

    +
    +
    +

    2.11.3. Produces

    +
    +
      +
    • +

      application/json

      +
    • +
    +
    +
    +
    +
    +

    2.12. POST /v2/loop/create/{loopName}?templateName={templateName}

    +
    +

    2.12.1. Parameters

    + +++++ + + + + + + + + + + + + + + +
    TypeNameSchema

    Path

    loopName}?templateName={templateName
    +required

    string

    +
    +
    +

    2.12.2. Responses

    + +++++ + + + + + + + + + + + + + + +
    HTTP CodeDescriptionSchema

    200

    Output type

    Loop

    +
    +
    +

    2.12.3. Consumes

    +
    +
      +
    • +

      application/json

      +
    • +
    +
    +
    +
    +

    2.12.4. Produces

    +
    +
      +
    • +

      application/json

      +
    • +
    +
    +
    +
    +
    +

    2.13. PUT /v2/loop/delete/{loopName}

    +
    +

    2.13.1. Parameters

    + +++++ + + + + + + + + + + + + + + +
    TypeNameSchema

    Path

    loopName
    +required

    string

    +
    +
    +

    2.13.2. Responses

    @@ -1233,9 +1460,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    @@ -1260,7 +1487,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.11.2. Responses

    +

    2.14.2. Responses

    @@ -1284,7 +1511,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.11.3. Produces

    +

    2.14.3. Produces

    • @@ -1295,9 +1522,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.12. GET /v2/loop/getAllNames

    +

    2.15. GET /v2/loop/getAllNames

    -

    2.12.1. Responses

    +

    2.15.1. Responses

    @@ -1321,7 +1548,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.12.2. Produces

    +

    2.15.2. Produces

    • @@ -1332,9 +1559,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.13. GET /v2/loop/getstatus/{loopName}

    +

    2.16. GET /v2/loop/getstatus/{loopName}

    -

    2.13.1. Parameters

    +

    2.16.1. Parameters

    @@ -1359,7 +1586,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.13.2. Responses

    +

    2.16.2. Responses

    @@ -1383,7 +1610,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.13.3. Produces

    +

    2.16.3. Produces

    • @@ -1394,9 +1621,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.14. PUT /v2/loop/refreshOpPolicyJsonSchema/{loopName}

    +

    2.17. PUT /v2/loop/refreshOpPolicyJsonSchema/{loopName}

    -

    2.14.1. Parameters

    +

    2.17.1. Parameters

    @@ -1421,7 +1648,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.14.2. Responses

    +

    2.17.2. Responses

    @@ -1445,7 +1672,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.14.3. Produces

    +

    2.17.3. Produces

    • @@ -1456,9 +1683,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.15. PUT /v2/loop/restart/{loopName}

    +

    2.18. PUT /v2/loop/removeOperationaPolicy/{loopName}/policyModel/{policyType}/{policyVersion}

    -

    2.15.1. Parameters

    +

    2.18.1. Parameters

    @@ -1479,11 +1706,23 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b required

    + + + + + + + + + +

    string

    Path

    policyType
    +required

    string

    Path

    policyVersion
    +required

    string

    -

    2.15.2. Responses

    +

    2.18.2. Responses

    @@ -1507,7 +1746,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.15.3. Produces

    +

    2.18.3. Produces

    • @@ -1518,9 +1757,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.16. PUT /v2/loop/stop/{loopName}

    +

    2.19. PUT /v2/loop/restart/{loopName}

    -

    2.16.1. Parameters

    +

    2.19.1. Parameters

    @@ -1545,7 +1784,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.16.2. Responses

    +

    2.19.2. Responses

    @@ -1569,7 +1808,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.16.3. Produces

    +

    2.19.3. Produces

    • @@ -1580,9 +1819,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.17. PUT /v2/loop/submit/{loopName}

    +

    2.20. PUT /v2/loop/stop/{loopName}

    -

    2.17.1. Parameters

    +

    2.20.1. Parameters

    @@ -1607,7 +1846,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.17.2. Responses

    +

    2.20.2. Responses

    @@ -1631,7 +1870,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.17.3. Produces

    +

    2.20.3. Produces

    • @@ -1642,9 +1881,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.18. GET /v2/loop/svgRepresentation/{loopName}

    +

    2.21. PUT /v2/loop/submit/{loopName}

    -

    2.18.1. Parameters

    +

    2.21.1. Parameters

    @@ -1669,7 +1908,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.18.2. Responses

    +

    2.21.2. Responses

    @@ -1687,13 +1926,75 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b + + + +

    200

    Output type

    Loop

    +
    +
    +

    2.21.3. Produces

    +
    +
      +
    • +

      application/json

      +
    • +
    +
    +
    +
    +
    +

    2.22. GET /v2/loop/svgRepresentation/{loopName}

    +
    +

    2.22.1. Parameters

    + +++++ + + + + + + + + + + +
    TypeNameSchema

    Path

    loopName
    +required

    string

    -

    2.18.3. Produces

    +

    2.22.2. Responses

    + +++++ + + + + + + + + + + + + + + +
    HTTP CodeDescriptionSchema

    200

    Output type

    string

    +
    +
    +

    2.22.3. Produces

    • @@ -1704,9 +2005,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.19. PUT /v2/loop/undeploy/{loopName}

    +

    2.23. PUT /v2/loop/undeploy/{loopName}

    -

    2.19.1. Parameters

    +

    2.23.1. Parameters

    @@ -1731,7 +2032,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.19.2. Responses

    +

    2.23.2. Responses

    @@ -1755,7 +2056,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.19.3. Produces

    +

    2.23.3. Produces

    • @@ -1766,9 +2067,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.20. POST /v2/loop/updateGlobalProperties/{loopName}

    +

    2.24. POST /v2/loop/updateGlobalProperties/{loopName}

    -

    2.20.1. Parameters

    +

    2.24.1. Parameters

    @@ -1799,7 +2100,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.20.2. Responses

    +

    2.24.2. Responses

    @@ -1823,7 +2124,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.20.3. Consumes

    +

    2.24.3. Consumes

    • @@ -1833,7 +2134,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.20.4. Produces

    +

    2.24.4. Produces

    • @@ -1844,9 +2145,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.21. POST /v2/loop/updateMicroservicePolicy/{loopName}

    +

    2.25. POST /v2/loop/updateMicroservicePolicy/{loopName}

    -

    2.21.1. Parameters

    +

    2.25.1. Parameters

    @@ -1877,7 +2178,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.21.2. Responses

    +

    2.25.2. Responses

    @@ -1901,7 +2202,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.21.3. Consumes

    +

    2.25.3. Consumes

    • @@ -1911,7 +2212,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.21.4. Produces

    +

    2.25.4. Produces

    • @@ -1922,9 +2223,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.22. POST /v2/loop/updateOperationalPolicies/{loopName}

    +

    2.26. POST /v2/loop/updateOperationalPolicies/{loopName}

    -

    2.22.1. Parameters

    +

    2.26.1. Parameters

    @@ -1955,7 +2256,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.22.2. Responses

    +

    2.26.2. Responses

    @@ -1979,7 +2280,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.22.3. Consumes

    +

    2.26.3. Consumes

    • @@ -1989,7 +2290,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.22.4. Produces

    +

    2.26.4. Produces

    • @@ -2000,9 +2301,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.23. GET /v2/loop/{loopName}

    +

    2.27. GET /v2/loop/{loopName}

    -

    2.23.1. Parameters

    +

    2.27.1. Parameters

    @@ -2027,7 +2328,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.23.2. Responses

    +

    2.27.2. Responses

    @@ -2051,7 +2352,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.23.3. Produces

    +

    2.27.3. Produces

    • @@ -2062,9 +2363,34 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.24. GET /v2/policyToscaModels

    +

    2.28. POST /v2/policyToscaModels

    -

    2.24.1. Responses

    +

    2.28.1. Parameters

    + +++++ + + + + + + + + + + + + + + +
    TypeNameSchema

    Body

    body
    +required

    string

    +
    +
    +

    2.28.2. Responses

    @@ -2088,7 +2414,17 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.24.2. Produces

    +

    2.28.3. Consumes

    +
    +
      +
    • +

      plain/text

      +
    • +
    +
    +
    +
    +

    2.28.4. Produces

    • @@ -2099,9 +2435,46 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.25. GET /v2/policyToscaModels/yaml/{policyModelType}

    +

    2.29. GET /v2/policyToscaModels

    -

    2.25.1. Parameters

    +

    2.29.1. Responses

    + +++++ + + + + + + + + + + + + + + +
    HTTP CodeDescriptionSchema

    200

    Output type

    PolicyModel

    +
    +
    +

    2.29.2. Produces

    +
    +
      +
    • +

      application/json

      +
    • +
    +
    +
    +
    +
    +

    2.30. GET /v2/policyToscaModels/yaml/{policyModelType}/{policyModelVersion}

    +
    +

    2.30.1. Parameters

    @@ -2122,11 +2495,17 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b required

    + + + + +

    string

    Path

    policyModelVersion
    +required

    string

    -

    2.25.2. Responses

    +

    2.30.2. Responses

    @@ -2150,7 +2529,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.25.3. Produces

    +

    2.30.3. Produces

    • @@ -2161,9 +2540,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.26. GET /v2/policyToscaModels/{policyModelType}

    +

    2.31. GET /v2/policyToscaModels/{policyModelType}/{policyModelVersion}

    -

    2.26.1. Parameters

    +

    2.31.1. Parameters

    @@ -2184,11 +2563,17 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b required

    + + + + +

    string

    Path

    policyModelVersion
    +required

    string

    -

    2.26.2. Responses

    +

    2.31.2. Responses

    @@ -2212,7 +2597,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.26.3. Produces

    +

    2.31.3. Produces

    • @@ -2223,9 +2608,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.27. PUT /v2/policyToscaModels/{policyModelType}

    +

    2.32. PUT /v2/policyToscaModels/{policyModelType}/{policyModelVersion}

    -

    2.27.1. Parameters

    +

    2.32.1. Parameters

    @@ -2247,6 +2632,12 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b + + + + + @@ -2256,7 +2647,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b

    string

    Path

    policyModelVersion
    +required

    string

    Body

    body
    required

    -

    2.27.2. Responses

    +

    2.32.2. Responses

    @@ -2280,7 +2671,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.27.3. Consumes

    +

    2.32.3. Consumes

    • @@ -2290,7 +2681,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.27.4. Produces

    +

    2.32.4. Produces

    • @@ -2301,9 +2692,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.28. GET /v2/templates

    +

    2.33. GET /v2/templates

    -

    2.28.1. Responses

    +

    2.33.1. Responses

    @@ -2327,7 +2718,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.28.2. Produces

    +

    2.33.2. Produces

    • @@ -2338,9 +2729,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.29. GET /v2/templates/names

    +

    2.34. GET /v2/templates/names

    -

    2.29.1. Responses

    +

    2.34.1. Responses

    @@ -2364,7 +2755,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.29.2. Produces

    +

    2.34.2. Produces

    • @@ -2375,9 +2766,9 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.30. GET /v2/templates/{templateName}

    +

    2.35. GET /v2/templates/{templateName}

    -

    2.30.1. Parameters

    +

    2.35.1. Parameters

    @@ -2402,7 +2793,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.30.2. Responses

    +

    2.35.2. Responses

    @@ -2426,7 +2817,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    2.30.3. Produces

    +

    2.35.3. Produces

    • @@ -2436,13 +2827,107 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    +
    +

    2.36. GET /v2/templates/{templateName}/svgRepresentation

    +
    +

    2.36.1. Parameters

    + +++++ + + + + + + + + + + + + + + +
    TypeNameSchema

    Path

    templateName
    +required

    string

    +
    +
    +

    2.36.2. Responses

    + +++++ + + + + + + + + + + + + + + +
    HTTP CodeDescriptionSchema

    200

    Output type

    string

    +
    +
    +

    2.36.3. Produces

    +
    +
      +
    • +

      application/xml

      +
    • +
    +
    +
    +

    3. Definitions

    -

    3.1. CldsHealthCheck

    +

    3.1. ClampInformation

    + ++++ + + + + + + + + + + + + + + + + + + + + +
    NameSchema

    allPermissions
    +optional

    < string > array

    cldsVersion
    +optional

    string

    userName
    +optional

    string

    +
    +
    +

    3.2. CldsHealthCheck

    @@ -2474,7 +2959,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.2. Dictionary

    +

    3.3. Dictionary

    @@ -2531,7 +3016,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.3. DictionaryElement

    +

    3.4. DictionaryElement

    @@ -2598,7 +3083,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.4. ExternalComponent

    +

    3.5. ExternalComponent

    @@ -2625,7 +3110,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.5. ExternalComponentState

    +

    3.6. ExternalComponentState

    @@ -2657,7 +3142,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.6. JsonArray

    +

    3.7. JsonArray

    @@ -2774,7 +3259,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.7. JsonNull

    +

    3.8. JsonNull

    @@ -2891,7 +3376,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.8. JsonObject

    +

    3.9. JsonObject

    @@ -3008,7 +3493,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.9. JsonPrimitive

    +

    3.10. JsonPrimitive

    @@ -3140,7 +3625,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.10. Loop

    +

    3.11. Loop

    @@ -3237,7 +3722,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.11. LoopElementModel

    +

    3.12. LoopElementModel

    @@ -3309,7 +3794,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.12. LoopLog

    +

    3.13. LoopLog

    @@ -3356,7 +3841,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.13. LoopTemplate

    +

    3.14. LoopTemplate

    @@ -3438,7 +3923,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.14. LoopTemplateLoopElementModel

    +

    3.15. LoopTemplateLoopElementModel

    @@ -3470,7 +3955,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.15. MicroServicePolicy

    +

    3.16. MicroServicePolicy

    @@ -3577,13 +4062,13 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.16. Number

    +

    3.17. Number

    Type : object

    -

    3.17. OperationalPolicy

    +

    3.18. OperationalPolicy

    @@ -3665,7 +4150,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.18. PolicyModel

    +

    3.19. PolicyModel

    @@ -3732,7 +4217,7 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
    -

    3.19. Service

    +

    3.20. Service

    diff --git a/src/main/resources/application-noaaf.properties b/src/main/resources/application-noaaf.properties index 3ce033f6..dbccb32d 100644 --- a/src/main/resources/application-noaaf.properties +++ b/src/main/resources/application-noaaf.properties @@ -176,7 +176,9 @@ clamp.config.security.permission.instance=dev clamp.config.security.authentication.class=org.onap.aaf.cadi.principal.X509Principal ## Tosca converter -clamp.config.tosca.converter.templates=classpath:/clds/tosca_updates/templates.json +clamp.config.tosca.converter.json.schema.templates=classpath:/clds/tosca-converter/templates.json +clamp.config.tosca.converter.default.datatypes=classpath:/clds/tosca-converter/default-tosca-types.yaml +clamp.config.tosca.converter.dictionary.support.enabled=true # Configuration settings for CDS clamp.config.cds.url=http4://blueprints-processor-http:8080 diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index a249d2d0..90c4186e 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -189,7 +189,9 @@ clamp.config.cadi.aafUrl=https://AAF_LOCATE_URL/onap.org.osaaf.aaf.service:2.1 clamp.config.cadi.cadiX509Issuers=CN=intermediateCA_1, OU=OSAAF, O=ONAP, C=US:CN=intermediateCA_7, OU=OSAAF, O=ONAP, C=US:CN=intermediateCA_9, OU=OSAAF, O=ONAP, C=US ## Tosca converter -clamp.config.tosca.converter.templates=classpath:/clds/tosca_updates/templates.json +clamp.config.tosca.converter.json.schema.templates=classpath:/clds/tosca-converter/templates.json +clamp.config.tosca.converter.default.datatypes=classpath:/clds/tosca-converter/default-tosca-types.yaml +clamp.config.tosca.converter.dictionary.support.enabled=true # Configuration settings for CDS clamp.config.cds.url=http4://blueprints-processor-http:8080 diff --git a/src/main/resources/clds/tosca-converter/default-tosca-types.yaml b/src/main/resources/clds/tosca-converter/default-tosca-types.yaml new file mode 100644 index 00000000..a11a7369 --- /dev/null +++ b/src/main/resources/clds/tosca-converter/default-tosca-types.yaml @@ -0,0 +1,87 @@ +tosca_definitions_version: tosca_simple_yaml_1_1_0 +data_types: + tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + protocol: + type: string + required: false + token_type: + type: string + default: password + token: + type: string + keys: + type: map + required: false + entry_schema: + type: string + user: + type: string + required: false + tosca.datatypes.TimeInterval: + derived_from: tosca.datatypes.Root + properties: + start_time: + type: timestamp + required: true + end_time: + type: timestamp + required: true + tosca.datatypes.network.NetworkInfo: + derived_from: tosca.datatypes.Root + properties: + network_name: + type: string + network_id: + type: string + addresses: + type: list + entry_schema: + type: string + tosca.datatypes.network.PortInfo: + derived_from: tosca.datatypes.Root + properties: + port_name: + type: string + port_id: + type: string + network_id: + type: string + mac_address: + type: string + addresses: + type: list + entry_schema: + type: string + # tosca.datatypes.network.PortDef: + # derived_from: integer + # constraints: + # - in_range: [ 1, 65535 ] + # tosca.datatypes.network.PortSpec: + # derived_from: tosca.datatypes.Root + # properties: + # protocol: + # type: string + # required: true + # default: tcp + # constraints: + # - valid_values: [ udp, tcp, igmp ] + # target: + # type: PortDef + # required: false + # target_range: + # type: range + # required: false + # constraints: + # - in_range: [ 1, 65535 ] + # source: + # type: PortDef + # required: false + # source_range: + # type: range + # required: false + # constraints: + # - in_range: [ 1, 65535 ] \ No newline at end of file diff --git a/src/main/resources/clds/tosca-converter/templates.json b/src/main/resources/clds/tosca-converter/templates.json new file mode 100644 index 00000000..f709e2f6 --- /dev/null +++ b/src/main/resources/clds/tosca-converter/templates.json @@ -0,0 +1,398 @@ +{ + "integer":{ + "type":{ + "defaultValue":"integer", + "visible":true, + "static":false + }, + "description":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "title":{ + "defaultValue":"", + "visible":true, + "static":false + + }, + "deprecated":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "default":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "enum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "const":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "multipleOf":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "maximum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "exclusiveMaximum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "minimum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "exclusiveMinimum":{ + "defaultValue":"", + "visible":true, + "static":false + } + }, + "number":{ + "type":{ + "defaultValue":"number", + "visible":true, + "static":false + }, + "description":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "title":{ + "defaultValue":"", + "visible":true, + "static":false + + }, + "deprecated":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "default":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "enum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "const":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "multipleOf":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "maximum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "exclusiveMaximum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "minimum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "exclusiveMinimum":{ + "defaultValue":"", + "visible":true, + "static":false + } + }, + "boolean":{ + "type":{ + "defaultValue":"boolean", + "visible":true, + "static":false + }, + "description":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "title":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "deprecated":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "default":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "const":{ + "defaultValue":"", + "visible":true, + "static":false + } + }, + "string":{ + "type":{ + "defaultValue":"string", + "visible":true, + "static":false + }, + "description":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "title":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "deprecated":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "default":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "enum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "const":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "length":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "minLength":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "maxLength":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "pattern":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "format":{ + "defaultValue":"", + "visible":true, + "static":false + } + }, + "timestamp":{ + "type":{ + "defaultValue":"string", + "visible":true, + "static":false + }, + "description":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "title":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "deprecated":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "default":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "enum":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "const":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "length":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "minLength":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "maxLength":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "pattern":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "format":{ + "defaultValue":"", + "visible":true, + "static":false + } + }, + "array":{ + "type":{ + "defaultValue":"array", + "visible":true, + "static":false + }, + "description":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "title":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "deprecated":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "default":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "const":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "uniqueItems":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "properties":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "minContains":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "maxContains":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "minItems":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "maxItems":{ + "defaultValue":"", + "visible":true, + "static":false + } + }, + "object":{ + "type":{ + "defaultValue":"object", + "visible":true, + "static":false + }, + "description":{ + "defaultValue":"", + "visible":true, + "static":true + }, + "title":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "format":{ + "defaultValue":"tabs", + "visible":true, + "static":true + }, + "required":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "minProperties":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "maxProperties":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "properties":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "dependentRequired":{ + "defaultValue":"", + "visible":true, + "static":false + }, + "dependencies":{ + "defaultValue":"", + "visible":true, + "static":false + } + } +} \ No newline at end of file diff --git a/src/main/resources/clds/tosca_update/default-tosca-types.yaml b/src/main/resources/clds/tosca_update/default-tosca-types.yaml deleted file mode 100644 index a11a7369..00000000 --- a/src/main/resources/clds/tosca_update/default-tosca-types.yaml +++ /dev/null @@ -1,87 +0,0 @@ -tosca_definitions_version: tosca_simple_yaml_1_1_0 -data_types: - tosca.datatypes.Root: - description: The TOSCA root Data Type all other TOSCA base Data Types derive from - tosca.datatypes.Credential: - derived_from: tosca.datatypes.Root - properties: - protocol: - type: string - required: false - token_type: - type: string - default: password - token: - type: string - keys: - type: map - required: false - entry_schema: - type: string - user: - type: string - required: false - tosca.datatypes.TimeInterval: - derived_from: tosca.datatypes.Root - properties: - start_time: - type: timestamp - required: true - end_time: - type: timestamp - required: true - tosca.datatypes.network.NetworkInfo: - derived_from: tosca.datatypes.Root - properties: - network_name: - type: string - network_id: - type: string - addresses: - type: list - entry_schema: - type: string - tosca.datatypes.network.PortInfo: - derived_from: tosca.datatypes.Root - properties: - port_name: - type: string - port_id: - type: string - network_id: - type: string - mac_address: - type: string - addresses: - type: list - entry_schema: - type: string - # tosca.datatypes.network.PortDef: - # derived_from: integer - # constraints: - # - in_range: [ 1, 65535 ] - # tosca.datatypes.network.PortSpec: - # derived_from: tosca.datatypes.Root - # properties: - # protocol: - # type: string - # required: true - # default: tcp - # constraints: - # - valid_values: [ udp, tcp, igmp ] - # target: - # type: PortDef - # required: false - # target_range: - # type: range - # required: false - # constraints: - # - in_range: [ 1, 65535 ] - # source: - # type: PortDef - # required: false - # source_range: - # type: range - # required: false - # constraints: - # - in_range: [ 1, 65535 ] \ No newline at end of file diff --git a/src/main/resources/clds/tosca_update/templates.json b/src/main/resources/clds/tosca_update/templates.json deleted file mode 100644 index f709e2f6..00000000 --- a/src/main/resources/clds/tosca_update/templates.json +++ /dev/null @@ -1,398 +0,0 @@ -{ - "integer":{ - "type":{ - "defaultValue":"integer", - "visible":true, - "static":false - }, - "description":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "title":{ - "defaultValue":"", - "visible":true, - "static":false - - }, - "deprecated":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "default":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "enum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "const":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "multipleOf":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "maximum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "exclusiveMaximum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "minimum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "exclusiveMinimum":{ - "defaultValue":"", - "visible":true, - "static":false - } - }, - "number":{ - "type":{ - "defaultValue":"number", - "visible":true, - "static":false - }, - "description":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "title":{ - "defaultValue":"", - "visible":true, - "static":false - - }, - "deprecated":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "default":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "enum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "const":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "multipleOf":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "maximum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "exclusiveMaximum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "minimum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "exclusiveMinimum":{ - "defaultValue":"", - "visible":true, - "static":false - } - }, - "boolean":{ - "type":{ - "defaultValue":"boolean", - "visible":true, - "static":false - }, - "description":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "title":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "deprecated":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "default":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "const":{ - "defaultValue":"", - "visible":true, - "static":false - } - }, - "string":{ - "type":{ - "defaultValue":"string", - "visible":true, - "static":false - }, - "description":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "title":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "deprecated":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "default":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "enum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "const":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "length":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "minLength":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "maxLength":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "pattern":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "format":{ - "defaultValue":"", - "visible":true, - "static":false - } - }, - "timestamp":{ - "type":{ - "defaultValue":"string", - "visible":true, - "static":false - }, - "description":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "title":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "deprecated":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "default":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "enum":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "const":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "length":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "minLength":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "maxLength":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "pattern":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "format":{ - "defaultValue":"", - "visible":true, - "static":false - } - }, - "array":{ - "type":{ - "defaultValue":"array", - "visible":true, - "static":false - }, - "description":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "title":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "deprecated":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "default":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "const":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "uniqueItems":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "properties":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "minContains":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "maxContains":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "minItems":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "maxItems":{ - "defaultValue":"", - "visible":true, - "static":false - } - }, - "object":{ - "type":{ - "defaultValue":"object", - "visible":true, - "static":false - }, - "description":{ - "defaultValue":"", - "visible":true, - "static":true - }, - "title":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "format":{ - "defaultValue":"tabs", - "visible":true, - "static":true - }, - "required":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "minProperties":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "maxProperties":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "properties":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "dependentRequired":{ - "defaultValue":"", - "visible":true, - "static":false - }, - "dependencies":{ - "defaultValue":"", - "visible":true, - "static":false - } - } -} \ No newline at end of file diff --git a/src/test/java/org/onap/clamp/clds/config/CldsUserJsonDecoderTest.java b/src/test/java/org/onap/clamp/clds/config/CldsUserJsonDecoderTest.java index 5a129221..7152ee11 100644 --- a/src/test/java/org/onap/clamp/clds/config/CldsUserJsonDecoderTest.java +++ b/src/test/java/org/onap/clamp/clds/config/CldsUserJsonDecoderTest.java @@ -26,12 +26,12 @@ package org.onap.clamp.clds.config; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; import org.onap.clamp.authorization.CldsUser; import org.onap.clamp.clds.exception.CldsUsersException; -import static org.assertj.core.api.Assertions.assertThat; - public class CldsUserJsonDecoderTest { private String user1 = "admin1"; diff --git a/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java b/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java index 4bf2de03..d985a5d7 100644 --- a/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java @@ -24,6 +24,7 @@ package org.onap.clamp.clds.it.config; import static org.junit.Assert.assertEquals; + import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTestItCase.java b/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTestItCase.java index db6fd5c0..a32d4995 100644 --- a/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTestItCase.java +++ b/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTestItCase.java @@ -57,7 +57,7 @@ public class ToscaYamlToJsonConvertorTestItCase { * Schema. * * @throws IOException In case of issue when opening the tosca yaml file and - * converted json file + * converted json file */ @Test public final void testParseToscaYaml() throws IOException { @@ -65,11 +65,11 @@ public class ToscaYamlToJsonConvertorTestItCase { ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(); String parsedJsonSchema = - convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.cdap.tca.hi.lo.app"); + 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); + ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json.json"), + parsedJsonSchema, true); } /** @@ -77,20 +77,20 @@ public class ToscaYamlToJsonConvertorTestItCase { * based on JSON Editor Schema. * * @throws IOException In case of issue when opening the tosca yaml file and - * converted json file + * converted json file */ @Test public final void testParseToscaYamlWithConstraints() throws IOException { String toscaModelYaml = - ResourceFileUtil.getResourceAsString("tosca/tosca-with-constraints.yaml"); + ResourceFileUtil.getResourceAsString("tosca/tosca-with-constraints.yaml"); ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(); String parsedJsonSchema = - convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.example.app"); + convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.example.app"); assertNotNull(parsedJsonSchema); JSONAssert.assertEquals( - ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json-with-constraints.json"), - parsedJsonSchema, true); + ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json-with-constraints.json"), + parsedJsonSchema, true); } /** @@ -98,20 +98,20 @@ public class ToscaYamlToJsonConvertorTestItCase { * conversion based on JSON Editor Schema. * * @throws IOException In case of issue when opening the tosca yaml file and - * converted json file + * converted json file */ @Test public final void testParseToscaYamlWithTypes() throws IOException { String toscaModelYaml = - ResourceFileUtil.getResourceAsString("tosca/tosca-with-datatypes.yaml"); + ResourceFileUtil.getResourceAsString("tosca/tosca-with-datatypes.yaml"); ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(); String parsedJsonSchema = - convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.example.app"); + convertor.parseToscaYaml(toscaModelYaml, "onap.policies.monitoring.example.app"); assertNotNull(parsedJsonSchema); JSONAssert.assertEquals( - ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json-with-datatypes.json"), - parsedJsonSchema, true); + ResourceFileUtil.getResourceAsString("tosca/policy-yaml-to-json-with-datatypes.json"), + parsedJsonSchema, true); } /** @@ -119,7 +119,7 @@ public class ToscaYamlToJsonConvertorTestItCase { * 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 + * converted json file */ @Test @Transactional @@ -165,24 +165,24 @@ public class ToscaYamlToJsonConvertorTestItCase { dictionaryService.saveOrUpdateDictionary(dictionaryTest2); String toscaModelYaml = - ResourceFileUtil.getResourceAsString("tosca/tosca_metadata_clamp_possible_values.yaml"); + 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); + ToscaSchemaConstants.METADATA_POLICY_MODEL_TYPE); String acronym = toscaYamlToJsonConvertor.getValueFromMetadata(jsonObject, - ToscaSchemaConstants.METADATA_ACRONYM); + ToscaSchemaConstants.METADATA_ACRONYM); String parsedJsonSchema = - toscaYamlToJsonConvertor.parseToscaYaml(toscaModelYaml, policyModelType); + 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); + ResourceFileUtil + .getResourceAsString("tosca/tosca_metadata_clamp_possible_values_json_schema.json"), + parsedJsonSchema, true); } } diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/ArrayFieldTest.java b/src/test/java/org/onap/clamp/clds/tosca/update/ArrayFieldTest.java index 83c374e9..421bd6ab 100644 --- a/src/test/java/org/onap/clamp/clds/tosca/update/ArrayFieldTest.java +++ b/src/test/java/org/onap/clamp/clds/tosca/update/ArrayFieldTest.java @@ -27,6 +27,10 @@ import com.google.gson.JsonArray; import java.io.IOException; import java.util.ArrayList; import junit.framework.TestCase; +import org.onap.clamp.clds.tosca.update.elements.ArrayField; +import org.onap.clamp.clds.tosca.update.elements.ToscaElement; +import org.onap.clamp.clds.tosca.update.elements.ToscaElementProperty; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplateManager; import org.onap.clamp.clds.util.ResourceFileUtil; public class ArrayFieldTest extends TestCase { @@ -37,13 +41,13 @@ public class ArrayFieldTest extends TestCase { * @throws IOException in case of failure */ public void testDeploy() throws IOException { - ToscaConverterManager toscaConverterManager = new ToscaConverterManager(ResourceFileUtil.getResourceAsString( + JsonTemplateManager jsonTemplateManager = new JsonTemplateManager(ResourceFileUtil.getResourceAsString( "tosca/new-converter/sampleOperationalPoliciesEXTENTED.yaml"),ResourceFileUtil.getResourceAsString( - "clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - ToscaElement toscaElement = toscaConverterManager.getComponents().get("onap.datatype.controlloop.Actor"); - Property property = toscaElement.getProperties().get("actor"); - ArrayField arrayParser = new ArrayField((ArrayList) property.getItems().get("default")); + "clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + ToscaElement toscaElement = jsonTemplateManager.getToscaElements().get("onap.datatype.controlloop.Actor"); + ToscaElementProperty toscaElementProperty = toscaElement.getProperties().get("actor"); + ArrayField arrayParser = new ArrayField((ArrayList) toscaElementProperty.getItems().get("default")); JsonArray toTest = arrayParser.deploy(); String reference = "[1,\"String\",5.5,true]"; assertEquals(reference, String.valueOf(toTest)); diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/ConstraintTest.java b/src/test/java/org/onap/clamp/clds/tosca/update/ConstraintTest.java index a73fd673..5215cbd4 100644 --- a/src/test/java/org/onap/clamp/clds/tosca/update/ConstraintTest.java +++ b/src/test/java/org/onap/clamp/clds/tosca/update/ConstraintTest.java @@ -27,16 +27,20 @@ import com.google.gson.JsonObject; import java.io.IOException; import java.util.ArrayList; import junit.framework.TestCase; +import org.onap.clamp.clds.tosca.update.elements.ToscaElement; +import org.onap.clamp.clds.tosca.update.elements.ToscaElementProperty; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplate; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplateManager; import org.onap.clamp.clds.util.ResourceFileUtil; public class ConstraintTest extends TestCase { - ToscaConverterManager toscaConverterManager = new ToscaConverterManager( + JsonTemplateManager jsonTemplateManager = new JsonTemplateManager( ResourceFileUtil.getResourceAsString("tosca/new-converter/constraints.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); - ToscaElement toscaElement = toscaConverterManager.getComponents().get("onap.datatype.controlloop.Operation"); + ToscaElement toscaElement = jsonTemplateManager.getToscaElements().get("onap.datatype.controlloop.Operation"); public ConstraintTest() throws IOException { } @@ -45,18 +49,20 @@ public class ConstraintTest extends TestCase { * Test get value array. */ public void testGetValuesArray() { - Property property = toscaElement.getProperties().get("timeout"); - Template template = toscaConverterManager.getTemplates().get("integer"); + ToscaElementProperty toscaElementProperty = toscaElement.getProperties().get("timeout"); + JsonTemplate jsonTemplate = jsonTemplateManager.getJsonSchemaTemplates().get("integer"); JsonObject resultProcess = new JsonObject(); - property.addConstraintsAsJson(resultProcess, (ArrayList) property.getItems().get("constraints"), - template); + toscaElementProperty.addConstraintsAsJson(resultProcess, + (ArrayList) toscaElementProperty.getItems().get("constraints"), + jsonTemplate); String reference = "{\"enum\":[3,4,5.5,6,10]}"; assertEquals(reference, String.valueOf(resultProcess)); - property = toscaElement.getProperties().get("success"); - template = toscaConverterManager.getTemplates().get("string"); + toscaElementProperty = toscaElement.getProperties().get("success"); + jsonTemplate = jsonTemplateManager.getJsonSchemaTemplates().get("string"); resultProcess = new JsonObject(); - property.addConstraintsAsJson(resultProcess, (ArrayList) property.getItems().get("constraints"), - template); + toscaElementProperty.addConstraintsAsJson(resultProcess, + (ArrayList) toscaElementProperty.getItems().get("constraints"), + jsonTemplate); reference = "{\"enum\":[\"VALID\",\"TERMINATED\"]}"; assertEquals(reference, String.valueOf(resultProcess)); } @@ -66,11 +72,12 @@ public class ConstraintTest extends TestCase { */ public void testGetSpecificLength() { //Test for string type, same process for array - Property property = toscaElement.getProperties().get("id"); - Template template = toscaConverterManager.getTemplates().get("string"); + ToscaElementProperty toscaElementProperty = toscaElement.getProperties().get("id"); + JsonTemplate jsonTemplate = jsonTemplateManager.getJsonSchemaTemplates().get("string"); JsonObject resultProcess = new JsonObject(); - property.addConstraintsAsJson(resultProcess, (ArrayList) property.getItems().get("constraints"), - template); + toscaElementProperty.addConstraintsAsJson(resultProcess, + (ArrayList) toscaElementProperty.getItems().get("constraints"), + jsonTemplate); int specificLength = 8; int toTest = resultProcess.get("minLength").getAsInt(); assertEquals(specificLength, toTest); @@ -83,11 +90,12 @@ public class ConstraintTest extends TestCase { */ public void testGetLimitValue() { //Test for array type, same process for string - Property property = toscaElement.getProperties().get("description"); - Template template = toscaConverterManager.getTemplates().get("array"); + ToscaElementProperty toscaElementProperty = toscaElement.getProperties().get("description"); + JsonTemplate jsonTemplate = jsonTemplateManager.getJsonSchemaTemplates().get("array"); JsonObject resultProcess = new JsonObject(); - property.addConstraintsAsJson(resultProcess, (ArrayList) property.getItems().get("constraints"), - template); + toscaElementProperty.addConstraintsAsJson(resultProcess, + (ArrayList) toscaElementProperty.getItems().get("constraints"), + jsonTemplate); int toTest = resultProcess.get("minItems").getAsInt(); assertEquals(5, toTest); diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/JsonTemplateManagerTest.java b/src/test/java/org/onap/clamp/clds/tosca/update/JsonTemplateManagerTest.java new file mode 100644 index 00000000..693377ee --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/tosca/update/JsonTemplateManagerTest.java @@ -0,0 +1,203 @@ +/*- + * ============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.clds.tosca.update; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import junit.framework.TestCase; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplate; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplateField; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplateManager; +import org.onap.clamp.clds.util.ResourceFileUtil; + +public class JsonTemplateManagerTest extends TestCase { + + /** + * Test the launch translation wit operational policies. + * + * @throws IOException In case of failure + * @throws UnknownComponentException In case of failure + */ + public void testLaunchTranslationTca() throws IOException, UnknownComponentException { + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("http-cache/example/policy/api/v1/policytypes/onap" + + ".policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0?" + + "connectionTimeToLive=5000/.file"), ResourceFileUtil.getResourceAsString( + "clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + String componentName = "onap.policies.monitoring.cdap.tca.hi.lo.app"; + jsonTemplateManager.getJsonSchemaForPolicyType(componentName, null); + } + + /** + * Test the launch translation wit operational policies. + * + * @throws IOException In case of failure + * @throws UnknownComponentException In case of failure + */ + public void testLaunchTranslationFrequencyLimiter() throws IOException, UnknownComponentException { + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("http-cache/example/policy/api/v1/policytypes/onap" + + ".policies.controlloop.guard.common.FrequencyLimiter/versions/1.0.0?" + + "connectionTimeToLive=5000/.file"), ResourceFileUtil.getResourceAsString( + "clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + String componentName = "onap.policies.controlloop.guard.common.FrequencyLimiter"; + jsonTemplateManager.getJsonSchemaForPolicyType(componentName, null); + } + + /** + * Test the launch translation wit operational policies. + * + * @throws IOException In case of failure + * @throws UnknownComponentException In case of failure + */ + public void testLaunchTranslationApex() throws IOException, UnknownComponentException { + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("http-cache/example/policy/api/v1/policytypes/onap" + + ".policies.controlloop.operational.common.Apex/versions/1.0.0?" + + "connectionTimeToLive=5000/.file"), ResourceFileUtil.getResourceAsString( + "clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + String componentName = "onap.policies.controlloop.operational.common.Apex"; + jsonTemplateManager.getJsonSchemaForPolicyType(componentName, null); + } + + /** + * Test the launch translation wit operational policies. + * + * @throws IOException In case of failure + * @throws UnknownComponentException In case of failure + */ + public void testLaunchTranslationDrools() throws IOException, UnknownComponentException { + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("http-cache/example/policy/api/v1/policytypes/onap" + + ".policies.controlloop.operational.common.Drools/versions/1.0.0?" + + "connectionTimeToLive=5000/.file"), ResourceFileUtil.getResourceAsString( + "clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + String componentName = "onap.policies.controlloop.operational.common.Drools"; + jsonTemplateManager.getJsonSchemaForPolicyType(componentName, null); + } + + + /** + * Test the launch translation. + * + * @throws IOException In case of failure + * @throws UnknownComponentException In case of failure + */ + public void testLaunchTranslation() throws IOException, UnknownComponentException { + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + String componentName = "onap.policies.controlloop.operational.common.Drools"; + jsonTemplateManager.getJsonSchemaForPolicyType(componentName, null); + } + + /** + * Test addTemplate. + * + * @throws IOException In case of failure + */ + public void testAddTemplate() throws IOException { + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + int count = jsonTemplateManager.getJsonSchemaTemplates().size(); + List + jsonTemplateFields = + new ArrayList<>(Arrays.asList(new JsonTemplateField("type"), new JsonTemplateField("description"), + new JsonTemplateField( + "required"), + new JsonTemplateField("metadata"), new JsonTemplateField("constraints"))); + jsonTemplateManager.addTemplate("test", jsonTemplateFields); + assertNotSame(count, jsonTemplateManager.getJsonSchemaTemplates().size()); + } + + /** + * test Remove template. + * + * @throws IOException In case of failure + */ + public void testRemoveTemplate() throws IOException { + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + int count = jsonTemplateManager.getJsonSchemaTemplates().size(); + jsonTemplateManager.removeTemplate("string"); + assertNotSame(count, jsonTemplateManager.getJsonSchemaTemplates().size()); + } + + /** + * Test update template. + * + * @throws IOException In case of failure + */ + public void testUpdateTemplate() throws IOException { + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + int count = jsonTemplateManager.getJsonSchemaTemplates().get("integer").getJsonTemplateFields().size(); + jsonTemplateManager.updateTemplate("integer", new JsonTemplateField("type"), false); + assertNotSame(count, + jsonTemplateManager.getJsonSchemaTemplates().get("integer").getJsonTemplateFields().size()); + } + + /** + * Test has template. + * + * @throws IOException In case of failure + */ + public void testHasTemplate() throws IOException { + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + boolean has = true; + List jsonTemplateFieldsString = + new ArrayList<>(Arrays.asList(new JsonTemplateField("type"), new JsonTemplateField("description"), + new JsonTemplateField("required"), + new JsonTemplateField("metadata"), new JsonTemplateField("constraints"))); + JsonTemplate jsonTemplateTest = new JsonTemplate("String", jsonTemplateFieldsString); + has = jsonTemplateManager.hasTemplate(jsonTemplateTest); + assertEquals(false, has); + } + +} diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/JsonTemplateTest.java b/src/test/java/org/onap/clamp/clds/tosca/update/JsonTemplateTest.java new file mode 100644 index 00000000..fab3030c --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/tosca/update/JsonTemplateTest.java @@ -0,0 +1,51 @@ +/*- + * ============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.clds.tosca.update; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import junit.framework.TestCase; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplate; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplateField; + +public class JsonTemplateTest extends TestCase { + + /** + * Test check failed. + */ + public void testCheckFields() { + JsonTemplate toTest = new JsonTemplate("toTest"); + List + jsonTemplateFields = new ArrayList<>( + Arrays.asList(new JsonTemplateField("type"), new JsonTemplateField("description"), + new JsonTemplateField( + "enum"))); + toTest.setJsonTemplateFields(jsonTemplateFields); + JsonTemplate reference = new JsonTemplate("toTest"); + reference.setJsonTemplateFields(jsonTemplateFields); + assertTrue(toTest.checkFields(reference)); + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/PropertyTest.java b/src/test/java/org/onap/clamp/clds/tosca/update/PropertyTest.java deleted file mode 100644 index bb1929f9..00000000 --- a/src/test/java/org/onap/clamp/clds/tosca/update/PropertyTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import java.io.IOException; -import java.util.ArrayList; -import junit.framework.TestCase; -import org.onap.clamp.clds.util.ResourceFileUtil; - -public class PropertyTest extends TestCase { - public PropertyTest() throws IOException { - } - - /** - * Test Parse array. - * - * @throws IOException In case of failure - */ - public void testParseArray() throws IOException { - ToscaConverterManager toscaConverterManager = new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPoliciesEXTENTED.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - ToscaElement toscaElement = toscaConverterManager.getComponents().get("onap.datatype.controlloop.Actor"); - Property property = toscaElement.getProperties().get("actor"); - JsonArray toTest = property.parseArray((ArrayList) property.getItems().get("default")); - assertNotNull(toTest); - } - - /** - * Test add constraint as json. - * - * @throws IOException In case of failure - */ - public void testAddConstraintsAsJson() throws IOException { - ToscaConverterManager toscaConverterManager = new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - ToscaElement toscaElement = toscaConverterManager.getComponents().get("onap.datatype.controlloop.operation.Failure"); - Property property = toscaElement.getProperties().get("category"); - Template template = toscaConverterManager.getTemplates().get("string"); - JsonObject toTest = new JsonObject(); - property.addConstraintsAsJson(toTest, (ArrayList) property.getItems().get("constraints"), template); - String test = "{\"enum\":[\"error\",\"timeout\",\"retries\",\"guard\",\"exception\"]}"; - assertEquals(test, String.valueOf(toTest)); - } -} \ No newline at end of file diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/TemplateTest.java b/src/test/java/org/onap/clamp/clds/tosca/update/TemplateTest.java deleted file mode 100644 index 02c5747b..00000000 --- a/src/test/java/org/onap/clamp/clds/tosca/update/TemplateTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import junit.framework.TestCase; - -public class TemplateTest extends TestCase { - - /** - * Test check failed. - */ - public void testCheckFields() { - Template toTest = new Template("toTest"); - List templateFields = new ArrayList<>(Arrays.asList(new TemplateField("type"), new TemplateField("description"),new TemplateField( - "enum"))); - toTest.setTemplateFields(templateFields); - Template reference = new Template("toTest"); - reference.setTemplateFields(templateFields); - assertTrue(toTest.checkFields(reference)); - } - -} \ No newline at end of file diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/ToscaConverterManagerTest.java b/src/test/java/org/onap/clamp/clds/tosca/update/ToscaConverterManagerTest.java deleted file mode 100644 index 49384121..00000000 --- a/src/test/java/org/onap/clamp/clds/tosca/update/ToscaConverterManagerTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/*- - * ============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.clds.tosca.update; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import junit.framework.TestCase; -import org.onap.clamp.clds.util.ResourceFileUtil; - -public class ToscaConverterManagerTest extends TestCase { - - /** - * Test the launch translation wit operational policies. - * - * @throws IOException In case of failure - * @throws UnknownComponentException In case of failure - */ - public void testLaunchTranslationTca() throws IOException, UnknownComponentException { - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("http-cache/example/policy/api/v1/policytypes/onap" - + ".policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0?" - + "connectionTimeToLive=5000/.file"), ResourceFileUtil.getResourceAsString( - "clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - assertNull(toscaConverterManager.getParseToJson()); - String componentName = "onap.policies.monitoring.cdap.tca.hi.lo.app"; - toscaConverterManager.startConversionToJson(componentName); - assertNotNull(toscaConverterManager.getParseToJson()); - } - - /** - * Test the launch translation wit operational policies. - * - * @throws IOException In case of failure - * @throws UnknownComponentException In case of failure - */ - public void testLaunchTranslationFrequencyLimiter() throws IOException, UnknownComponentException { - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("http-cache/example/policy/api/v1/policytypes/onap" - + ".policies.controlloop.guard.common.FrequencyLimiter/versions/1.0.0?" - + "connectionTimeToLive=5000/.file"), ResourceFileUtil.getResourceAsString( - "clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - assertNull(toscaConverterManager.getParseToJson()); - String componentName = "onap.policies.controlloop.guard.common.FrequencyLimiter"; - toscaConverterManager.startConversionToJson(componentName); - assertNotNull(toscaConverterManager.getParseToJson()); - } - - /** - * Test the launch translation wit operational policies. - * - * @throws IOException In case of failure - * @throws UnknownComponentException In case of failure - */ - public void testLaunchTranslationApex() throws IOException, UnknownComponentException { - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("http-cache/example/policy/api/v1/policytypes/onap" - + ".policies.controlloop.operational.common.Apex/versions/1.0.0?" - + "connectionTimeToLive=5000/.file"), ResourceFileUtil.getResourceAsString( - "clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - assertNull(toscaConverterManager.getParseToJson()); - String componentName = "onap.policies.controlloop.operational.common.Apex"; - toscaConverterManager.startConversionToJson(componentName); - assertNotNull(toscaConverterManager.getParseToJson()); - } - - /** - * Test the launch translation wit operational policies. - * - * @throws IOException In case of failure - * @throws UnknownComponentException In case of failure - */ - public void testLaunchTranslationDrools() throws IOException, UnknownComponentException { - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("http-cache/example/policy/api/v1/policytypes/onap" - + ".policies.controlloop.operational.common.Drools/versions/1.0.0?" - + "connectionTimeToLive=5000/.file"), ResourceFileUtil.getResourceAsString( - "clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - assertNull(toscaConverterManager.getParseToJson()); - String componentName = "onap.policies.controlloop.operational.common.Drools"; - toscaConverterManager.startConversionToJson(componentName); - assertNotNull(toscaConverterManager.getParseToJson()); - } - - /** - * Test the launch translation. - * - * @throws IOException In case of failure - * @throws UnknownComponentException In case of failure - */ - public void testLaunchTranslation() throws IOException, UnknownComponentException { - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - assertNull(toscaConverterManager.getParseToJson()); - String componentName = "onap.policies.controlloop.operational.common.Drools"; - toscaConverterManager.startConversionToJson(componentName); - assertNotNull(toscaConverterManager.getParseToJson()); - } - - /** - * Test addTemplate. - * - * @throws IOException In case of failure - */ - public void testAddTemplate() throws IOException { - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - int count = toscaConverterManager.getTemplates().size(); - List templateFields = new ArrayList<>(Arrays.asList(new TemplateField("type"), new TemplateField("description"), - new TemplateField( - "required"), - new TemplateField("metadata"), new TemplateField("constraints"))); - toscaConverterManager.addTemplate("test", templateFields); - assertNotSame(count, toscaConverterManager.getTemplates().size()); - } - - /** - * test Remove template. - * - * @throws IOException In case of failure - */ - public void testRemoveTemplate() throws IOException { - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - int count = toscaConverterManager.getTemplates().size(); - toscaConverterManager.removeTemplate("string"); - assertNotSame(count, toscaConverterManager.getTemplates().size()); - } - - /** - * Test update template. - * - * @throws IOException In case of failure - */ - public void testUpdateTemplate() throws IOException { - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - int count = toscaConverterManager.getTemplates().get("integer").getTemplateFields().size(); - toscaConverterManager.updateTemplate("integer", new TemplateField("type"), false); - assertNotSame(count, toscaConverterManager.getTemplates().get("integer").getTemplateFields().size()); - } - - /** - * Test has template. - * - * @throws IOException In case of failure - */ - public void testHasTemplate() throws IOException { - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( - ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - boolean has = true; - List templateFieldsString = - new ArrayList<>(Arrays.asList(new TemplateField("type"), new TemplateField("description"), new TemplateField("required"), - new TemplateField("metadata"), new TemplateField("constraints"))); - Template templateTest = new Template("String", templateFieldsString); - has = toscaConverterManager.hasTemplate(templateTest); - assertEquals(false, has); - } - -} diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/ToscaConverterWithDictionarySupportItCase.java b/src/test/java/org/onap/clamp/clds/tosca/update/ToscaConverterWithDictionarySupportItCase.java new file mode 100644 index 00000000..b4f8b124 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/tosca/update/ToscaConverterWithDictionarySupportItCase.java @@ -0,0 +1,118 @@ +/*- + * ============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.clds.tosca.update; + +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.tosca.update.parser.metadata.ToscaMetadataParserWithDictionarySupport; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplateManager; +import org.onap.clamp.clds.util.JsonUtils; +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = Application.class) +public class ToscaConverterWithDictionarySupportItCase { + + @Autowired + private DictionaryService dictionaryService; + + @Autowired + private ToscaMetadataParserWithDictionarySupport toscaMetadataParserWithDictionarySupport; + + /** + * 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, UnknownComponentException { + + // 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); + + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("tosca/tosca_metadata_clamp_possible_values.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + + JsonObject jsonSchema = jsonTemplateManager.getJsonSchemaForPolicyType( + "onap.policies.monitoring.cdap.tca.hi.lo.app", toscaMetadataParserWithDictionarySupport); + + JSONAssert.assertEquals( + ResourceFileUtil + .getResourceAsString("tosca/new-converter/tca-with-metadata.json"), + JsonUtils.GSON.toJson(jsonSchema), true); + } +} diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/ToscaElementPropertyTest.java b/src/test/java/org/onap/clamp/clds/tosca/update/ToscaElementPropertyTest.java new file mode 100644 index 00000000..967f330d --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/tosca/update/ToscaElementPropertyTest.java @@ -0,0 +1,79 @@ +/*- + * ============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.clds.tosca.update; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.io.IOException; +import java.util.ArrayList; +import junit.framework.TestCase; +import org.onap.clamp.clds.tosca.update.elements.ToscaElement; +import org.onap.clamp.clds.tosca.update.elements.ToscaElementProperty; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplate; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplateManager; +import org.onap.clamp.clds.util.ResourceFileUtil; + +public class ToscaElementPropertyTest extends TestCase { + public ToscaElementPropertyTest() throws IOException { + } + + /** + * Test Parse array. + * + * @throws IOException In case of failure + */ + public void testParseArray() throws IOException { + JsonTemplateManager jsonTemplateManager = new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPoliciesEXTENTED.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + ToscaElement toscaElement = jsonTemplateManager.getToscaElements().get("onap.datatype.controlloop.Actor"); + ToscaElementProperty toscaElementProperty = toscaElement.getProperties().get("actor"); + JsonArray toTest = + toscaElementProperty.parseArray((ArrayList) toscaElementProperty.getItems().get("default")); + assertNotNull(toTest); + } + + /** + * Test add constraint as json. + * + * @throws IOException In case of failure + */ + public void testAddConstraintsAsJson() throws IOException { + JsonTemplateManager jsonTemplateManager = new JsonTemplateManager( + ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + ToscaElement toscaElement = + jsonTemplateManager.getToscaElements().get("onap.datatype.controlloop.operation.Failure"); + ToscaElementProperty toscaElementProperty = toscaElement.getProperties().get("category"); + JsonTemplate jsonTemplate = jsonTemplateManager.getJsonSchemaTemplates().get("string"); + JsonObject toTest = new JsonObject(); + toscaElementProperty + .addConstraintsAsJson(toTest, (ArrayList) toscaElementProperty.getItems().get("constraints"), + jsonTemplate); + String test = "{\"enum\":[\"error\",\"timeout\",\"retries\",\"guard\",\"exception\"]}"; + assertEquals(test, String.valueOf(toTest)); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/clamp/clds/tosca/update/ToscaElementTest.java b/src/test/java/org/onap/clamp/clds/tosca/update/ToscaElementTest.java index 7ffba4e0..5f7de28a 100644 --- a/src/test/java/org/onap/clamp/clds/tosca/update/ToscaElementTest.java +++ b/src/test/java/org/onap/clamp/clds/tosca/update/ToscaElementTest.java @@ -27,6 +27,8 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import junit.framework.TestCase; +import org.onap.clamp.clds.tosca.update.elements.ToscaElement; +import org.onap.clamp.clds.tosca.update.templates.JsonTemplateManager; import org.onap.clamp.clds.util.ResourceFileUtil; public class ToscaElementTest extends TestCase { @@ -38,12 +40,12 @@ public class ToscaElementTest extends TestCase { */ public void testPropertiesNames() throws IOException { ArrayList reference = new ArrayList<>(Arrays.asList("actor", "operation", "target", "payload")); - ToscaConverterManager toscaConverterManager = - new ToscaConverterManager( + JsonTemplateManager jsonTemplateManager = + new JsonTemplateManager( ResourceFileUtil.getResourceAsString("tosca/new-converter/sampleOperationalPolicies.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/default-tosca-types.yaml"), - ResourceFileUtil.getResourceAsString("clds/tosca_update/templates.json")); - ToscaElement toscaElement = toscaConverterManager.getComponents().get("onap.datatype.controlloop.Actor"); + ResourceFileUtil.getResourceAsString("clds/tosca-converter/default-tosca-types.yaml"), + ResourceFileUtil.getResourceAsString("clds/tosca-converter/templates.json")); + ToscaElement toscaElement = jsonTemplateManager.getToscaElements().get("onap.datatype.controlloop.Actor"); assertEquals(reference, toscaElement.propertiesNames()); } diff --git a/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java b/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java index 184a391d..8eeba07e 100644 --- a/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java +++ b/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java @@ -39,7 +39,6 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import org.onap.clamp.loop.Loop; import org.onap.clamp.loop.template.PolicyModel; import org.onap.clamp.policy.microservice.MicroServicePolicy; import org.onap.clamp.policy.operational.OperationalPolicy; @@ -65,11 +64,11 @@ public class ClampGraphBuilderTest { public void clampGraphBuilderCompleteChainTest() { String collector = "VES"; MicroServicePolicy ms1 = new MicroServicePolicy("ms1", new PolicyModel("org.onap.ms1", "", "1.0.0"), false, - null); + null, null, null, null); MicroServicePolicy ms2 = new MicroServicePolicy("ms2", new PolicyModel("org.onap.ms2", "", "1.0.0"), false, - null); + null, null, null, null); - OperationalPolicy opPolicy = new OperationalPolicy("OperationalPolicy", new Loop(), new JsonObject(), + OperationalPolicy opPolicy = new OperationalPolicy("OperationalPolicy", new JsonObject(), new JsonObject(), new PolicyModel("org.onap.opolicy", null, "1.0.0", "opolicy1"), null, null, null); final Set opPolicies = Set.of(opPolicy); final Set microServices = Set.of(ms1, ms2); @@ -92,9 +91,11 @@ public class ClampGraphBuilderTest { public void clampGraphBuilderNoPolicyGivenTest() { String collector = "VES"; MicroServicePolicy ms1 = - new MicroServicePolicy("ms1", new PolicyModel("org.onap.ms1", "", "1.0.0"), false, null); + new MicroServicePolicy("ms1", new PolicyModel("org.onap.ms1", "", "1.0.0"), false, null, null, null, + null); MicroServicePolicy ms2 = - new MicroServicePolicy("ms2", new PolicyModel("org.onap.ms2", "", "1.0.0"), false, null); + new MicroServicePolicy("ms2", new PolicyModel("org.onap.ms2", "", "1.0.0"), false, null, null, null, + null); ClampGraphBuilder clampGraphBuilder = new ClampGraphBuilder(mockPainter); assertThat(clampGraphBuilder.collector(collector).addMicroService(ms1).addMicroService(ms2).build()) diff --git a/src/test/java/org/onap/clamp/clds/util/drawing/SvgLoopGeneratorTest.java b/src/test/java/org/onap/clamp/clds/util/drawing/SvgLoopGeneratorTest.java index a320131c..9559fa17 100644 --- a/src/test/java/org/onap/clamp/clds/util/drawing/SvgLoopGeneratorTest.java +++ b/src/test/java/org/onap/clamp/clds/util/drawing/SvgLoopGeneratorTest.java @@ -24,6 +24,7 @@ package org.onap.clamp.clds.util.drawing; import static org.assertj.core.api.Assertions.assertThat; + import com.google.gson.JsonObject; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; @@ -38,12 +39,11 @@ public class SvgLoopGeneratorTest { private Loop getLoop() { MicroServicePolicy ms1 = new MicroServicePolicy("ms1", new PolicyModel("org.onap.ms1", "", "1.0.0", "short.ms1"), - false, - null); + false,null,null,null,null); MicroServicePolicy ms2 = new MicroServicePolicy("ms2", new PolicyModel("org.onap.ms2", "", "1.0.0", "short.ms2"), - false, null); - OperationalPolicy opPolicy = new OperationalPolicy("OperationalPolicy", new Loop(), new JsonObject(), + false, null,null,null,null); + OperationalPolicy opPolicy = new OperationalPolicy("OperationalPolicy", new JsonObject(),new JsonObject(), new PolicyModel("org.onap.opolicy", null, "1.0.0", "short.OperationalPolicy"), null, null, null); Loop loop = new Loop(); loop.addMicroServicePolicy(ms1); diff --git a/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java b/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java index a57a35ea..d0669554 100644 --- a/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java +++ b/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java @@ -27,6 +27,7 @@ package org.onap.clamp.loop; import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -96,7 +97,8 @@ public class CsarInstallerItCase { private CsarInstaller csarInstaller; private BlueprintArtifact buildFakeBuildprintArtifact(String instanceName, String invariantResourceUuid, - String blueprintFilePath, String artifactName, String invariantServiceUuid) throws IOException { + String blueprintFilePath, String artifactName, + String invariantServiceUuid) throws IOException { IResourceInstance resource = Mockito.mock(IResourceInstance.class); Mockito.when(resource.getResourceInstanceName()).thenReturn(instanceName); Mockito.when(resource.getResourceInvariantUUID()).thenReturn(invariantResourceUuid); diff --git a/src/test/java/org/onap/clamp/loop/LoopControllerTestItCase.java b/src/test/java/org/onap/clamp/loop/LoopControllerTestItCase.java index 24a9037a..4d51bb27 100644 --- a/src/test/java/org/onap/clamp/loop/LoopControllerTestItCase.java +++ b/src/test/java/org/onap/clamp/loop/LoopControllerTestItCase.java @@ -30,6 +30,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import java.io.IOException; import java.util.Set; import javax.transaction.Transactional; import org.junit.Test; @@ -46,7 +47,6 @@ import org.onap.clamp.policy.operational.OperationalPolicy; import org.onap.clamp.policy.operational.OperationalPolicyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.Commit; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @@ -77,10 +77,10 @@ public class LoopControllerTestItCase { private void saveTestLoopToDb() { Loop testLoop = createTestLoop(EXAMPLE_LOOP_NAME, "blueprint", "representation"); testLoop.setGlobalPropertiesJson(JsonUtils.GSON.fromJson(EXAMPLE_JSON, JsonObject.class)); - LoopTemplate template = new LoopTemplate(); + LoopTemplate template = new LoopTemplate(); template.setName("testTemplate"); testLoop.setLoopTemplate(template); - Service modelService = new Service("{\"name\":\"serviceName\",\"UUID\":\"uuid\"}","{}"); + Service modelService = new Service("{\"name\":\"serviceName\",\"UUID\":\"uuid\"}", "{}"); testLoop.setModelService(modelService); loopService.saveOrUpdateLoop(testLoop); } @@ -140,7 +140,7 @@ public class LoopControllerTestItCase { public void testUpdateMicroservicePolicy() { saveTestLoopToDb(); PolicyModel policyModel = new PolicyModel("testPolicyModel", - "tosca_definitions_version: tosca_simple_yaml_1_0_0","1.0.0"); + "tosca_definitions_version: tosca_simple_yaml_1_0_0", "1.0.0"); policyModelsService.saveOrUpdatePolicyModel(policyModel); MicroServicePolicy policy = new MicroServicePolicy("policyName", policyModel, false, JsonUtils.GSON.fromJson(EXAMPLE_JSON, JsonObject.class), null, null, null); @@ -158,10 +158,10 @@ public class LoopControllerTestItCase { @Test @Transactional - public void testAddAndRemoveOperationalPolicies() { + public void testAddAndRemoveOperationalPolicies() throws IOException { saveTestLoopToDb(); PolicyModel policyModel = new PolicyModel("testPolicyModel", - "tosca_definitions_version: tosca_simple_yaml_1_0_0","1.0.0"); + null, "1.0.0"); policyModelsService.saveOrUpdatePolicyModel(policyModel); loopController.addOperationalPolicy(EXAMPLE_LOOP_NAME, "testPolicyModel", "1.0.0"); @@ -169,7 +169,7 @@ public class LoopControllerTestItCase { Loop newLoop = loopController.getLoop(EXAMPLE_LOOP_NAME); Set opPolicyList = newLoop.getOperationalPolicies(); assertThat(opPolicyList.size()).isEqualTo(1); - for(OperationalPolicy policy : opPolicyList) { + for (OperationalPolicy policy : opPolicyList) { assertThat(policy.getName().contains("OPERATIONAL_serviceName")).isTrue(); assertThat(policy.getPolicyModel().getPolicyModelType()).isEqualTo("testPolicyModel"); assertThat(policy.getPolicyModel().getVersion()).isEqualTo("1.0.0"); diff --git a/src/test/java/org/onap/clamp/loop/PolicyComponentTest.java b/src/test/java/org/onap/clamp/loop/PolicyComponentTest.java index 89d3e617..1c9b1018 100644 --- a/src/test/java/org/onap/clamp/loop/PolicyComponentTest.java +++ b/src/test/java/org/onap/clamp/loop/PolicyComponentTest.java @@ -28,7 +28,6 @@ import static org.assertj.core.api.Assertions.assertThat; import com.google.gson.Gson; import com.google.gson.JsonObject; import java.io.IOException; -import java.util.HashSet; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.junit.Test; @@ -265,9 +264,12 @@ public class PolicyComponentTest { loopTest.addMicroServicePolicy(microServicePolicy); PolicyModel policyModel2 = new PolicyModel("onap.policies.controlloop.Operational", null, "1.0.0"); - OperationalPolicy opPolicy = new OperationalPolicy("opPolicy", loopTest, - new Gson().fromJson("{\"configtype\":\"json\"}", JsonObject.class), policyModel2, null, "pdpGroup2", - "pdpSubgroup2"); + OperationalPolicy opPolicy = + new OperationalPolicy("opPolicy", new Gson().fromJson("{\"configtype\":\"json\"}", JsonObject.class), + new Gson().fromJson("{\"jsonschema\":\"schema\"}", JsonObject.class), policyModel2, null, + "pdpGroup2", + "pdpSubgroup2"); + loopTest.addOperationalPolicy(opPolicy); LoopTemplate loopTemplate = new LoopTemplate("test", "yaml", "svg", 1, null); diff --git a/src/test/java/org/onap/clamp/policy/microservice/MicroServicePayloadTest.java b/src/test/java/org/onap/clamp/policy/microservice/MicroServicePayloadTest.java index ea121820..01e2184a 100644 --- a/src/test/java/org/onap/clamp/policy/microservice/MicroServicePayloadTest.java +++ b/src/test/java/org/onap/clamp/policy/microservice/MicroServicePayloadTest.java @@ -37,7 +37,7 @@ public class MicroServicePayloadTest { public void testPayloadConstruction() throws IOException { MicroServicePolicy policy = new MicroServicePolicy("testPolicy", new PolicyModel( "onap.policies.monitoring.cdap.tca.hi.lo.app", - ResourceFileUtil.getResourceAsString("tosca/tosca_example.yaml"),"1.0.0"), false, null); + ResourceFileUtil.getResourceAsString("tosca/tosca_example.yaml"),"1.0.0"), false,null,null, null,null); policy.setConfigurationsJson(JsonUtils.GSON.fromJson( ResourceFileUtil.getResourceAsString("tosca/micro-service-policy-properties.json"), JsonObject.class)); JSONAssert.assertEquals(ResourceFileUtil.getResourceAsString("tosca/micro-service-policy-payload.json"), diff --git a/src/test/java/org/onap/clamp/policy/microservice/OperationalPolicyPayloadTest.java b/src/test/java/org/onap/clamp/policy/microservice/OperationalPolicyPayloadTest.java index 4b8eee92..58a432d3 100644 --- a/src/test/java/org/onap/clamp/policy/microservice/OperationalPolicyPayloadTest.java +++ b/src/test/java/org/onap/clamp/policy/microservice/OperationalPolicyPayloadTest.java @@ -42,8 +42,8 @@ public class OperationalPolicyPayloadTest { public void testOperationalPolicyLegacyPayloadConstruction() throws IOException { JsonObject jsonConfig = new GsonBuilder().create().fromJson( ResourceFileUtil.getResourceAsString("tosca/operational-policy-properties.json"), JsonObject.class); - OperationalPolicy policy = new OperationalPolicy("testPolicy.legacy", null, jsonConfig, - new PolicyModel("onap.policies.controlloop.Operational.legacy","","1.0.0","test"), null,null,null); + OperationalPolicy policy = new OperationalPolicy("testPolicy.legacy", jsonConfig, null, + new PolicyModel("onap.policies.controlloop.Operational.legacy", "", "1.0.0", "test"), null, null, null); assertThat(policy.createPolicyPayloadYaml()) .isEqualTo(ResourceFileUtil.getResourceAsString("tosca/operational-policy-payload.yaml")); @@ -65,7 +65,7 @@ public class OperationalPolicyPayloadTest { JsonObject jsonConfig = new GsonBuilder().create().fromJson( ResourceFileUtil.getResourceAsString("tosca/operational-policy-no-guard-properties.json"), JsonObject.class); - OperationalPolicy policy = new OperationalPolicy("testPolicy", null, jsonConfig, null, null, null, null); + OperationalPolicy policy = new OperationalPolicy("testPolicy", jsonConfig, null, null, null, null, null); Map guardsMap = policy.createGuardPolicyPayloads(); assertThat(guardsMap).isEmpty(); assertThat(guardsMap.entrySet()).isEmpty(); @@ -75,7 +75,7 @@ public class OperationalPolicyPayloadTest { public void testGuardPolicyPayloadConstruction() throws IOException { JsonObject jsonConfig = new GsonBuilder().create().fromJson( ResourceFileUtil.getResourceAsString("tosca/operational-policy-properties.json"), JsonObject.class); - OperationalPolicy policy = new OperationalPolicy("testPolicy", null, jsonConfig, null, null, null, null); + OperationalPolicy policy = new OperationalPolicy("testPolicy", jsonConfig, null, null, null, null, null); Map guardsMap = policy.createGuardPolicyPayloads(); diff --git a/src/test/java/org/onap/clamp/util/SemanticVersioningTest.java b/src/test/java/org/onap/clamp/util/SemanticVersioningTest.java index e018f095..88f2bbe1 100644 --- a/src/test/java/org/onap/clamp/util/SemanticVersioningTest.java +++ b/src/test/java/org/onap/clamp/util/SemanticVersioningTest.java @@ -23,12 +23,15 @@ package org.onap.clamp.util; -import org.junit.Test; - import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + public class SemanticVersioningTest { + /** + * compare test. + */ @Test public void compareTest() { assertThat(SemanticVersioning.compare("1.0.0", "2.0.0")).isEqualTo(-1); @@ -53,6 +56,9 @@ public class SemanticVersioningTest { assertThat(SemanticVersioning.compare("1.2", "1")).isEqualTo(1); } + /** + * Compare test. + */ @Test public void compareEqualsTest() { assertThat(SemanticVersioning.compare("1.0.0", "1.0.0")).isEqualTo(0); @@ -62,6 +68,9 @@ public class SemanticVersioningTest { } + /** + * Compare with null. + */ @Test public void compareNullTest() { assertThat(SemanticVersioning.compare(null, null)).isEqualTo(0); @@ -69,6 +78,9 @@ public class SemanticVersioningTest { assertThat(SemanticVersioning.compare("1.0", null)).isEqualTo(1); } + /** + * Increment major version test. + */ @Test public void incrementVersionTest() { assertThat(SemanticVersioning.incrementMajorVersion("1.0")).isEqualTo("2.0.0"); diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 0e453535..ea17836a 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -168,4 +168,6 @@ clamp.config.cds.userName=ccsdkapps clamp.config.cds.password=ccsdkapps ## Tosca converter -clamp.config.tosca.converter.templates=classpath:/clds/tosca_updates/templates.json \ No newline at end of file +clamp.config.tosca.converter.json.schema.templates=classpath:/clds/tosca-converter/templates.json +clamp.config.tosca.converter.default.datatypes=classpath:/clds/tosca-converter/default-tosca-types.yaml +clamp.config.tosca.converter.dictionary.support.enabled=true \ No newline at end of file diff --git a/src/test/resources/clds/camel/rest/clamp-api-v2.xml b/src/test/resources/clds/camel/rest/clamp-api-v2.xml deleted file mode 100644 index b0a8d2fd..00000000 --- a/src/test/resources/clds/camel/rest/clamp-api-v2.xml +++ /dev/null @@ -1,984 +0,0 @@ - - - - - - - - - - - - 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/http-cache/example/policy/api/v1/policytypes/onap.policies.controlloop.operational.common.Apex/versions/1.0.0?connectionTimeToLive=5000/.file b/src/test/resources/http-cache/example/policy/api/v1/policytypes/onap.policies.controlloop.operational.common.Apex/versions/1.0.0?connectionTimeToLive=5000/.file index 44f55879..64ba559c 100644 --- a/src/test/resources/http-cache/example/policy/api/v1/policytypes/onap.policies.controlloop.operational.common.Apex/versions/1.0.0?connectionTimeToLive=5000/.file +++ b/src/test/resources/http-cache/example/policy/api/v1/policytypes/onap.policies.controlloop.operational.common.Apex/versions/1.0.0?connectionTimeToLive=5000/.file @@ -91,7 +91,7 @@ data_types: description: The resource the operation should be performed on. required: true metadata: - clamp_possible_values: + clamp_possible_values: test payload: type: map description: Name/value pairs of payload information passed by Policy to the actor @@ -116,7 +116,7 @@ data_types: description: The definition of the operation to be performed. required: true metadata: - clamp_possible_values: + clamp_possible_values: test timeout: type: integer description: The amount of time for the actor to perform the operation. diff --git a/src/test/resources/http-cache/example/policy/api/v1/policytypes/onap.policies.controlloop.operational.common.Drools/versions/1.0.0?connectionTimeToLive=5000/.file b/src/test/resources/http-cache/example/policy/api/v1/policytypes/onap.policies.controlloop.operational.common.Drools/versions/1.0.0?connectionTimeToLive=5000/.file index 72897be0..1c082b1e 100644 --- a/src/test/resources/http-cache/example/policy/api/v1/policytypes/onap.policies.controlloop.operational.common.Drools/versions/1.0.0?connectionTimeToLive=5000/.file +++ b/src/test/resources/http-cache/example/policy/api/v1/policytypes/onap.policies.controlloop.operational.common.Drools/versions/1.0.0?connectionTimeToLive=5000/.file @@ -79,7 +79,7 @@ data_types: description: The resource the operation should be performed on. required: true metadata: - clamp_possible_values: + clamp_possible_values: test payload: type: map description: Name/value pairs of payload information passed by Policy to the actor @@ -104,7 +104,7 @@ data_types: description: The definition of the operation to be performed. required: true metadata: - clamp_possible_values: + clamp_possible_values: test timeout: type: integer description: The amount of time for the actor to perform the operation. diff --git a/src/test/resources/tosca/new-converter/tca-with-metadata.json b/src/test/resources/tosca/new-converter/tca-with-metadata.json new file mode 100644 index 00000000..1b95f8c9 --- /dev/null +++ b/src/test/resources/tosca/new-converter/tca-with-metadata.json @@ -0,0 +1,222 @@ +{ + "title": "onap.policies.monitoring.cdap.tca.hi.lo.app", + "type": "object", + "required": [], + "properties": { + "tca_policy": { + "type": "object", + "description": "TCA Policy JSON", + "properties": { + "onap.datatypes.monitoring.tca_policy": { + "title": "onap.datatypes.monitoring.tca_policy", + "type": "object", + "required": [ + "domain", + "metricsPerEventName" + ], + "properties": { + "domain": { + "type": "string", + "description": "Domain name to which TCA needs to be applied", + "default": "measurementsForVfScaling", + "const": "measurementsForVfScaling" + }, + "metricsPerEventName": { + "type": "array", + "description": "Contains eventName and threshold details that need to be applied to given eventName", + "items": { + "title": "onap.datatypes.monitoring.metricsPerEventName", + "type": "object", + "required": [ + "controlLoopSchemaType", + "eventName", + "policyName", + "policyScope", + "policyVersion", + "thresholds", + "context", + "signature" + ], + "properties": { + "controlLoopSchemaType": { + "type": "string", + "description": "Specifies Control Loop Schema Type for the event Name e.g. VNF, VM", + "enum": [ + "VM", + "VNF" + ] + }, + "eventName": { + "type": "string", + "description": "Event name to which thresholds need to be applied" + }, + "policyName": { + "type": "string", + "description": "TCA Policy Scope Name" + }, + "policyScope": { + "type": "string", + "description": "TCA Policy Scope" + }, + "policyVersion": { + "type": "string", + "description": "TCA Policy Scope Version" + }, + "thresholds": { + "type": "array", + "description": "Thresholds associated with eventName", + "items": { + "title": "onap.datatypes.monitoring.thresholds", + "type": "object", + "required": [ + "closedLoopControlName", + "closedLoopEventStatus", + "direction", + "fieldPath", + "severity", + "thresholdValue", + "version" + ], + "properties": { + "closedLoopControlName": { + "type": "string", + "description": "Closed Loop Control Name associated with the threshold" + }, + "closedLoopEventStatus": { + "type": "string", + "description": "Closed Loop Event Status of the threshold", + "enum": [ + "ONSET", + "ABATED" + ] + }, + "direction": { + "type": "string", + "description": "Direction of the threshold", + "enum": [ + "LESS", + "LESS_OR_EQUAL", + "GREATER", + "GREATER_OR_EQUAL", + "EQUAL" + ] + }, + "fieldPath": { + "type": "string", + "description": "Json field Path as per CEF message which needs to be analyzed for TCA", + "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" + ] + }, + "severity": { + "type": "string", + "description": "Threshold Event Severity", + "enum": [ + "CRITICAL", + "MAJOR", + "MINOR", + "WARNING", + "NORMAL" + ] + }, + "thresholdValue": { + "type": "integer", + "description": "Threshold value for the field Path inside CEF message" + }, + "version": { + "type": "string", + "description": "Version number associated with the threshold" + } + } + } + }, + "context": { + "type": "string", + "description": "TCA Policy Dummy Context", + "enum": [ + "PROD" + ], + "options": { + "enum_titles": [ + "PROD" + ] + } + }, + "signature": { + "title": "onap.datatypes.monitoring.Dummy_Signature", + "type": "object", + "required": [ + "filter_clause" + ], + "properties": { + "filter_clause": { + "type": "qbldr", + "description": "Filter Clause", + "minLength": 1, + "qschema": { + "filters": [ + { + "type": "string", + "minLength": 1, + "id": "alarmCondition", + "label": "alarmCondition", + "operators": [ + "equals" + ] + } + ] + } + } + } + } + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/test/resources/tosca/new-converter/tca-with-metadata.yaml b/src/test/resources/tosca/new-converter/tca-with-metadata.yaml new file mode 100644 index 00000000..c0d2a86e --- /dev/null +++ b/src/test/resources/tosca/new-converter/tca-with-metadata.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 -- cgit 1.2.3-korg