diff options
Diffstat (limited to 'src/main/java/org/onap/sdc/toscaparser/api/elements')
34 files changed, 2542 insertions, 2507 deletions
diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/ArtifactTypeDef.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/ArtifactTypeDef.java index 3dce5e6..9cf8c6c 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/ArtifactTypeDef.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/ArtifactTypeDef.java @@ -7,9 +7,9 @@ * 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. @@ -23,67 +23,63 @@ package org.onap.sdc.toscaparser.api.elements; import java.util.LinkedHashMap; public class ArtifactTypeDef extends StatefulEntityType { - - private String type; - private LinkedHashMap<String,Object> customDef; - private LinkedHashMap<String,Object> properties; - private LinkedHashMap<String,Object> parentArtifacts; - - - - public ArtifactTypeDef(String atype,LinkedHashMap<String,Object> _customDef) { - super(atype,ARTIFACT_PREFIX,_customDef); - - type = atype; - customDef = _customDef; - properties = null; - if(defs != null) { - properties = (LinkedHashMap<String,Object>)defs.get(PROPERTIES); - } - parentArtifacts = _getParentArtifacts(); - } - - private LinkedHashMap<String,Object> _getParentArtifacts() { - LinkedHashMap<String,Object> artifacts = new LinkedHashMap<>(); - String parentArtif = null; - if(getParentType() != null) { - parentArtif = getParentType().getType(); - } - if(parentArtif != null && !parentArtif.isEmpty()) { - while(!parentArtif.equals("tosca.artifacts.Root")) { - Object ob = TOSCA_DEF.get(parentArtif); - artifacts.put(parentArtif,ob); - parentArtif = - (String)((LinkedHashMap<String,Object>)ob).get("derived_from"); + + private String type; + private LinkedHashMap<String, Object> customDef; + private LinkedHashMap<String, Object> properties; + private LinkedHashMap<String, Object> parentArtifacts; + + + public ArtifactTypeDef(String type, LinkedHashMap<String, Object> customDef) { + super(type, ARTIFACT_PREFIX, customDef); + + this.type = type; + this.customDef = customDef; + properties = defs != null ? (LinkedHashMap<String, Object>) defs.get(PROPERTIES) : null; + parentArtifacts = getParentArtifacts(); + } + + private LinkedHashMap<String, Object> getParentArtifacts() { + LinkedHashMap<String, Object> artifacts = new LinkedHashMap<>(); + String parentArtif = null; + if (getParentType() != null) { + parentArtif = getParentType().getType(); + } + if (parentArtif != null && !parentArtif.isEmpty()) { + while (!parentArtif.equals("tosca.artifacts.Root")) { + Object ob = TOSCA_DEF.get(parentArtif); + artifacts.put(parentArtif, ob); + parentArtif = + (String) ((LinkedHashMap<String, Object>) ob).get("derived_from"); } - } - return artifacts; - } - - public ArtifactTypeDef getParentType() { + } + return artifacts; + } + + public ArtifactTypeDef getParentType() { // Return a artifact entity from which this entity is derived - if(defs == null) { - return null; + if (defs == null) { + return null; } String partifactEntity = derivedFrom(defs); - if(partifactEntity != null) { - return new ArtifactTypeDef(partifactEntity,customDef); + if (partifactEntity != null) { + return new ArtifactTypeDef(partifactEntity, customDef); } return null; - } - - public Object getArtifact(String name) { + } + + public Object getArtifact(String name) { // Return the definition of an artifact field by name - if(defs != null) { + if (defs != null) { return defs.get(name); } return null; - } - - public String getType() { - return type; - } - + } + + public String getType() { + return type; + } + } /*python diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/AttributeDef.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/AttributeDef.java index 2070c50..e4a30f1 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/AttributeDef.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/AttributeDef.java @@ -7,9 +7,9 @@ * 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. @@ -24,27 +24,27 @@ import java.util.LinkedHashMap; public class AttributeDef { // TOSCA built-in Attribute type - - private String name; - private Object value; - private LinkedHashMap<String,Object> schema; - public AttributeDef(String adName, Object adValue, LinkedHashMap<String,Object> adSchema) { + private String name; + private Object value; + private LinkedHashMap<String, Object> schema; + + public AttributeDef(String adName, Object adValue, LinkedHashMap<String, Object> adSchema) { name = adName; value = adValue; schema = adSchema; } - + public String getName() { - return name; + return name; } public Object getValue() { - return value; + return value; } - public LinkedHashMap<String,Object> getSchema() { - return schema; + public LinkedHashMap<String, Object> getSchema() { + return schema; } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/CapabilityTypeDef.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/CapabilityTypeDef.java index 9f9610e..e3c24b3 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/CapabilityTypeDef.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/CapabilityTypeDef.java @@ -7,9 +7,9 @@ * 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. @@ -25,134 +25,132 @@ import java.util.LinkedHashMap; import java.util.Map; public class CapabilityTypeDef extends StatefulEntityType { - // TOSCA built-in capabilities type + // TOSCA built-in capabilities type - private static final String TOSCA_TYPEURI_CAPABILITY_ROOT = "tosca.capabilities.Root"; + private static final String TOSCA_TYPEURI_CAPABILITY_ROOT = "tosca.capabilities.Root"; - private String name; - private String nodetype; - private LinkedHashMap<String,Object> customDef; - private LinkedHashMap<String,Object> properties; - private LinkedHashMap<String,Object> parentCapabilities; + private String name; + private String nodetype; + private LinkedHashMap<String, Object> customDef; + private LinkedHashMap<String, Object> properties; + private LinkedHashMap<String, Object> parentCapabilities; - @SuppressWarnings("unchecked") - public CapabilityTypeDef(String cname,String ctype,String ntype,LinkedHashMap<String,Object> ccustomDef) { - super(ctype,CAPABILITY_PREFIX,ccustomDef); - - name = cname; + @SuppressWarnings("unchecked") + public CapabilityTypeDef(String cname, String ctype, String ntype, LinkedHashMap<String, Object> ccustomDef) { + super(ctype, CAPABILITY_PREFIX, ccustomDef); + + name = cname; nodetype = ntype; properties = null; customDef = ccustomDef; - if(defs != null) { - properties = (LinkedHashMap<String,Object>)defs.get(PROPERTIES); + if (defs != null) { + properties = (LinkedHashMap<String, Object>) defs.get(PROPERTIES); } - parentCapabilities = _getParentCapabilities(customDef); - } - - @SuppressWarnings("unchecked") - public ArrayList<PropertyDef> getPropertiesDefObjects () { + parentCapabilities = getParentCapabilities(customDef); + } + + @SuppressWarnings("unchecked") + public ArrayList<PropertyDef> getPropertiesDefObjects() { // Return a list of property definition objects - ArrayList<PropertyDef> propsdefs = new ArrayList<>(); - LinkedHashMap<String,Object> parentProperties = new LinkedHashMap<>(); - if(parentCapabilities != null) { - for(Map.Entry<String,Object> me: parentCapabilities.entrySet()) { - parentProperties.put(me.getKey(),((LinkedHashMap<String,Object>)me.getValue()).get("properties")); - } - } - if(properties != null) { - for(Map.Entry<String,Object> me: properties.entrySet()) { - propsdefs.add(new PropertyDef(me.getKey(),null,(LinkedHashMap<String,Object>)me.getValue())); - } - } - if(parentProperties != null) { - for(Map.Entry<String,Object> me: parentProperties.entrySet()) { - LinkedHashMap<String,Object> props = (LinkedHashMap<String,Object>)me.getValue(); - if (props != null) { - for(Map.Entry<String,Object> pe: props.entrySet()) { - String prop = pe.getKey(); - LinkedHashMap<String,Object> schema = (LinkedHashMap<String,Object>)pe.getValue(); - // add parent property if not overridden by children type - if(properties == null || properties.get(prop) == null) { - propsdefs.add(new PropertyDef(prop, null, schema)); - } - } - } - } - } - return propsdefs; - } - - public LinkedHashMap<String,PropertyDef> getPropertiesDef() { - LinkedHashMap<String,PropertyDef> pds = new LinkedHashMap<>(); - for(PropertyDef pd: getPropertiesDefObjects()) { - pds.put(pd.getName(),pd); - } - return pds; - } - - public PropertyDef getPropertyDefValue(String pdname) { + ArrayList<PropertyDef> propsdefs = new ArrayList<>(); + LinkedHashMap<String, Object> parentProperties = new LinkedHashMap<>(); + if (parentCapabilities != null) { + for (Map.Entry<String, Object> me : parentCapabilities.entrySet()) { + parentProperties.put(me.getKey(), ((LinkedHashMap<String, Object>) me.getValue()).get("properties")); + } + } + if (properties != null) { + for (Map.Entry<String, Object> me : properties.entrySet()) { + propsdefs.add(new PropertyDef(me.getKey(), null, (LinkedHashMap<String, Object>) me.getValue())); + } + } + if (parentProperties != null) { + for (Map.Entry<String, Object> me : parentProperties.entrySet()) { + LinkedHashMap<String, Object> props = (LinkedHashMap<String, Object>) me.getValue(); + if (props != null) { + for (Map.Entry<String, Object> pe : props.entrySet()) { + String prop = pe.getKey(); + LinkedHashMap<String, Object> schema = (LinkedHashMap<String, Object>) pe.getValue(); + // add parent property if not overridden by children type + if (properties == null || properties.get(prop) == null) { + propsdefs.add(new PropertyDef(prop, null, schema)); + } + } + } + } + } + return propsdefs; + } + + public LinkedHashMap<String, PropertyDef> getPropertiesDef() { + LinkedHashMap<String, PropertyDef> pds = new LinkedHashMap<>(); + for (PropertyDef pd : getPropertiesDefObjects()) { + pds.put(pd.getName(), pd); + } + return pds; + } + + public PropertyDef getPropertyDefValue(String pdname) { // Return the definition of a given property name - LinkedHashMap<String,PropertyDef> propsDef = getPropertiesDef(); - if(propsDef != null && propsDef.get(pdname) != null) { - return (PropertyDef)propsDef.get(pdname).getPDValue(); - } - return null; - } - - @SuppressWarnings("unchecked") - private LinkedHashMap<String,Object> _getParentCapabilities(LinkedHashMap<String,Object> customDef) { - LinkedHashMap<String,Object> capabilities = new LinkedHashMap<>(); - CapabilityTypeDef parentCap = getParentType(); - if(parentCap != null) { - String sParentCap = parentCap.getType(); - while(!sParentCap.equals(TOSCA_TYPEURI_CAPABILITY_ROOT)) { - if(TOSCA_DEF.get(sParentCap) != null) { - capabilities.put(sParentCap,TOSCA_DEF.get(sParentCap)); - } - else if(customDef != null && customDef.get(sParentCap) != null) { - capabilities.put(sParentCap,customDef.get(sParentCap)); - } - sParentCap = (String)((LinkedHashMap<String,Object>)capabilities.get(sParentCap)).get("derived_from"); - } - } - return capabilities; - } - - public CapabilityTypeDef getParentType() { + LinkedHashMap<String, PropertyDef> propsDef = getPropertiesDef(); + if (propsDef != null && propsDef.get(pdname) != null) { + return (PropertyDef) propsDef.get(pdname).getPDValue(); + } + return null; + } + + @SuppressWarnings("unchecked") + private LinkedHashMap<String, Object> getParentCapabilities(LinkedHashMap<String, Object> customDef) { + LinkedHashMap<String, Object> capabilities = new LinkedHashMap<>(); + CapabilityTypeDef parentCap = getParentType(); + if (parentCap != null) { + String sParentCap = parentCap.getType(); + while (!sParentCap.equals(TOSCA_TYPEURI_CAPABILITY_ROOT)) { + if (TOSCA_DEF.get(sParentCap) != null) { + capabilities.put(sParentCap, TOSCA_DEF.get(sParentCap)); + } else if (customDef != null && customDef.get(sParentCap) != null) { + capabilities.put(sParentCap, customDef.get(sParentCap)); + } + sParentCap = (String) ((LinkedHashMap<String, Object>) capabilities.get(sParentCap)).get("derived_from"); + } + } + return capabilities; + } + + public CapabilityTypeDef getParentType() { // Return a capability this capability is derived from - if(defs == null) { - return null; - } - String pnode = derivedFrom(defs); - if(pnode != null && !pnode.isEmpty()) { + if (defs == null) { + return null; + } + String pnode = derivedFrom(defs); + if (pnode != null && !pnode.isEmpty()) { return new CapabilityTypeDef(name, pnode, nodetype, customDef); - } - return null; - } + } + return null; + } - public boolean inheritsFrom(ArrayList<String> typeNames) { + public boolean inheritsFrom(ArrayList<String> typeNames) { // Check this capability is in type_names // Check if this capability or some of its parent types // are in the list of types: type_names - if(typeNames.contains(getType())) { - return true; - } - else if(getParentType() != null) { - return getParentType().inheritsFrom(typeNames); - } - return false; - } - - // getters/setters - - public LinkedHashMap<String,Object> getProperties() { - return properties; - } - - public String getName() { - return name; - } + if (typeNames.contains(getType())) { + return true; + } else if (getParentType() != null) { + return getParentType().inheritsFrom(typeNames); + } + return false; + } + + // getters/setters + + public LinkedHashMap<String, Object> getProperties() { + return properties; + } + + public String getName() { + return name; + } } /*python @@ -227,7 +225,7 @@ class CapabilityTypeDef(StatefulEntityType): if pnode: return CapabilityTypeDef(self.name, pnode, self.nodetype, self.custom_def) - + def inherits_from(self, type_names): '''Check this capability is in type_names diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/DataType.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/DataType.java index 4b6451d..d8cf460 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/DataType.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/DataType.java @@ -7,9 +7,9 @@ * 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. @@ -24,66 +24,66 @@ import java.util.ArrayList; import java.util.LinkedHashMap; public class DataType extends StatefulEntityType { - - LinkedHashMap<String,Object> customDef; - - public DataType(String _dataTypeName,LinkedHashMap<String,Object> _customDef) { - super(_dataTypeName,DATATYPE_NETWORK_PREFIX,_customDef); - - customDef = _customDef; - } - - public DataType getParentType() { + + LinkedHashMap<String, Object> customDef; + + public DataType(String _dataTypeName, LinkedHashMap<String, Object> _customDef) { + super(_dataTypeName, DATATYPE_NETWORK_PREFIX, _customDef); + + customDef = _customDef; + } + + public DataType getParentType() { // Return a datatype this datatype is derived from - if(defs != null) { - String ptype = derivedFrom(defs); - if(ptype != null) { - return new DataType(ptype,customDef); - } - } + if (defs != null) { + String ptype = derivedFrom(defs); + if (ptype != null) { + return new DataType(ptype, customDef); + } + } return null; - } + } - public String getValueType() { + public String getValueType() { // Return 'type' section in the datatype schema - if(defs != null) { - return (String)entityValue(defs,"type"); - } - return null; - } + if (defs != null) { + return (String) entityValue(defs, "type"); + } + return null; + } - public ArrayList<PropertyDef> getAllPropertiesObjects() { + public ArrayList<PropertyDef> getAllPropertiesObjects() { //Return all properties objects defined in type and parent type - ArrayList<PropertyDef> propsDef = getPropertiesDefObjects(); + ArrayList<PropertyDef> propsDef = getPropertiesDefObjects(); DataType ptype = getParentType(); - while(ptype != null) { + while (ptype != null) { propsDef.addAll(ptype.getPropertiesDefObjects()); ptype = ptype.getParentType(); } return propsDef; - } - - public LinkedHashMap<String,PropertyDef> getAllProperties() { + } + + public LinkedHashMap<String, PropertyDef> getAllProperties() { // Return a dictionary of all property definition name-object pairs - LinkedHashMap<String,PropertyDef> pno = new LinkedHashMap<>(); - for(PropertyDef pd: getAllPropertiesObjects()) { - pno.put(pd.getName(),pd); - } + LinkedHashMap<String, PropertyDef> pno = new LinkedHashMap<>(); + for (PropertyDef pd : getAllPropertiesObjects()) { + pno.put(pd.getName(), pd); + } return pno; - } + } - public Object getAllPropertyValue(String name) { + public Object getAllPropertyValue(String name) { // Return the value of a given property name - LinkedHashMap<String,PropertyDef> propsDef = getAllProperties(); - if(propsDef != null && propsDef.get(name) != null) { + LinkedHashMap<String, PropertyDef> propsDef = getAllProperties(); + if (propsDef != null && propsDef.get(name) != null) { return propsDef.get(name).getPDValue(); } return null; - } - - public LinkedHashMap<String,Object> getDefs() { - return defs; - } + } + + public LinkedHashMap<String, Object> getDefs() { + return defs; + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/EntityType.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/EntityType.java index 62f51d2..efc6ac9 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/EntityType.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/EntityType.java @@ -7,9 +7,9 @@ * 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. @@ -36,189 +36,189 @@ import org.yaml.snakeyaml.Yaml; public class EntityType { - private static Logger log = LoggerFactory.getLogger(EntityType.class.getName()); - - private static final String TOSCA_DEFINITION_1_0_YAML = "TOSCA_definition_1_0.yaml"; - protected static final String DERIVED_FROM = "derived_from"; - protected static final String PROPERTIES = "properties"; - protected static final String ATTRIBUTES = "attributes"; - protected static final String REQUIREMENTS = "requirements"; - protected static final String INTERFACES = "interfaces"; - protected static final String CAPABILITIES = "capabilities"; - protected static final String TYPE = "type"; - protected static final String ARTIFACTS = "artifacts"; - - @SuppressWarnings("unused") - private static final String SECTIONS[] = { - DERIVED_FROM, PROPERTIES, ATTRIBUTES, REQUIREMENTS, + private static Logger log = LoggerFactory.getLogger(EntityType.class.getName()); + + private static final String TOSCA_DEFINITION_1_0_YAML = "TOSCA_definition_1_0.yaml"; + protected static final String DERIVED_FROM = "derived_from"; + protected static final String PROPERTIES = "properties"; + protected static final String ATTRIBUTES = "attributes"; + protected static final String REQUIREMENTS = "requirements"; + protected static final String INTERFACES = "interfaces"; + protected static final String CAPABILITIES = "capabilities"; + protected static final String TYPE = "type"; + protected static final String ARTIFACTS = "artifacts"; + + @SuppressWarnings("unused") + private static final String SECTIONS[] = { + DERIVED_FROM, PROPERTIES, ATTRIBUTES, REQUIREMENTS, INTERFACES, CAPABILITIES, TYPE, ARTIFACTS - }; + }; - public static final String TOSCA_DEF_SECTIONS[] = { - "node_types", "data_types", "artifact_types", - "group_types", "relationship_types", - "capability_types", "interface_types", - "policy_types"}; + public static final String TOSCA_DEF_SECTIONS[] = { + "node_types", "data_types", "artifact_types", + "group_types", "relationship_types", + "capability_types", "interface_types", + "policy_types"}; // TOSCA definition file - //private final static String path = EntityType.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - - //private final static String path = EntityType.class.getClassLoader().getResource("TOSCA_definition_1_0.yaml").getFile(); + //private final static String path = EntityType.class.getProtectionDomain().getCodeSource().getLocation().getPath(); + + //private final static String path = EntityType.class.getClassLoader().getResource("TOSCA_definition_1_0.yaml").getFile(); //private final static String TOSCA_DEF_FILE = EntityType.class.getClassLoader().getResourceAsStream("TOSCA_definition_1_0.yaml"); - - private static LinkedHashMap<String,Object> TOSCA_DEF_LOAD_AS_IS = loadTdf(); - - //EntityType.class.getClassLoader().getResourceAsStream("TOSCA_definition_1_0.yaml"); - - @SuppressWarnings("unchecked") - private static LinkedHashMap<String,Object> loadTdf() { - String toscaDefLocation = EntityType.class.getClassLoader().getResource(TOSCA_DEFINITION_1_0_YAML).getFile(); - InputStream input = EntityType.class.getClassLoader().getResourceAsStream(TOSCA_DEFINITION_1_0_YAML); - if (input == null){ - log.error("EntityType - loadTdf - Couldn't load TOSCA_DEF_FILE {}", toscaDefLocation); - } - Yaml yaml = new Yaml(); - Object loaded = yaml.load(input); - //@SuppressWarnings("unchecked") - return (LinkedHashMap<String,Object>) loaded; - } + + private static LinkedHashMap<String, Object> TOSCA_DEF_LOAD_AS_IS = loadTdf(); + + //EntityType.class.getClassLoader().getResourceAsStream("TOSCA_definition_1_0.yaml"); + + @SuppressWarnings("unchecked") + private static LinkedHashMap<String, Object> loadTdf() { + String toscaDefLocation = EntityType.class.getClassLoader().getResource(TOSCA_DEFINITION_1_0_YAML).getFile(); + InputStream input = EntityType.class.getClassLoader().getResourceAsStream(TOSCA_DEFINITION_1_0_YAML); + if (input == null) { + log.error("EntityType - loadTdf - Couldn't load TOSCA_DEF_FILE {}", toscaDefLocation); + } + Yaml yaml = new Yaml(); + Object loaded = yaml.load(input); + //@SuppressWarnings("unchecked") + return (LinkedHashMap<String, Object>) loaded; + } // Map of definition with pre-loaded values of TOSCA_DEF_FILE_SECTIONS - public static LinkedHashMap<String,Object> TOSCA_DEF; - static { - TOSCA_DEF = new LinkedHashMap<String,Object>(); - for(String section: TOSCA_DEF_SECTIONS) { - @SuppressWarnings("unchecked") - LinkedHashMap<String,Object> value = (LinkedHashMap<String,Object>)TOSCA_DEF_LOAD_AS_IS.get(section); - if(value != null) { - for(String key: value.keySet()) { - TOSCA_DEF.put(key, value.get(key)); - } - } + public static LinkedHashMap<String, Object> TOSCA_DEF; + + static { + TOSCA_DEF = new LinkedHashMap<String, Object>(); + for (String section : TOSCA_DEF_SECTIONS) { + @SuppressWarnings("unchecked") + LinkedHashMap<String, Object> value = (LinkedHashMap<String, Object>) TOSCA_DEF_LOAD_AS_IS.get(section); + if (value != null) { + for (String key : value.keySet()) { + TOSCA_DEF.put(key, value.get(key)); + } + } } - } - - public static final String DEPENDSON = "tosca.relationships.DependsOn"; - public static final String HOSTEDON = "tosca.relationships.HostedOn"; - public static final String CONNECTSTO = "tosca.relationships.ConnectsTo"; - public static final String ATTACHESTO = "tosca.relationships.AttachesTo"; - public static final String LINKSTO = "tosca.relationships.network.LinksTo"; - public static final String BINDSTO = "tosca.relationships.network.BindsTo"; - - public static final String RELATIONSHIP_TYPE[] = { - "tosca.relationships.DependsOn", - "tosca.relationships.HostedOn", - "tosca.relationships.ConnectsTo", - "tosca.relationships.AttachesTo", - "tosca.relationships.network.LinksTo", - "tosca.relationships.network.BindsTo"}; - - public static final String NODE_PREFIX = "tosca.nodes."; - public static final String RELATIONSHIP_PREFIX = "tosca.relationships."; - public static final String CAPABILITY_PREFIX = "tosca.capabilities."; - public static final String INTERFACE_PREFIX = "tosca.interfaces."; - public static final String ARTIFACT_PREFIX = "tosca.artifacts."; - public static final String POLICY_PREFIX = "tosca.policies."; - public static final String GROUP_PREFIX = "tosca.groups."; - //currently the data types are defined only for network - // but may have changes in the future. - public static final String DATATYPE_PREFIX = "tosca.datatypes."; - public static final String DATATYPE_NETWORK_PREFIX = DATATYPE_PREFIX + "network."; - public static final String TOSCA = "tosca"; - - protected String type; - protected LinkedHashMap<String,Object> defs = null; - public Object getParentType() { return null; } - - public String derivedFrom(LinkedHashMap<String,Object> defs) { + } + + public static final String DEPENDSON = "tosca.relationships.DependsOn"; + public static final String HOSTEDON = "tosca.relationships.HostedOn"; + public static final String CONNECTSTO = "tosca.relationships.ConnectsTo"; + public static final String ATTACHESTO = "tosca.relationships.AttachesTo"; + public static final String LINKSTO = "tosca.relationships.network.LinksTo"; + public static final String BINDSTO = "tosca.relationships.network.BindsTo"; + + public static final String RELATIONSHIP_TYPE[] = { + "tosca.relationships.DependsOn", + "tosca.relationships.HostedOn", + "tosca.relationships.ConnectsTo", + "tosca.relationships.AttachesTo", + "tosca.relationships.network.LinksTo", + "tosca.relationships.network.BindsTo"}; + + public static final String NODE_PREFIX = "tosca.nodes."; + public static final String RELATIONSHIP_PREFIX = "tosca.relationships."; + public static final String CAPABILITY_PREFIX = "tosca.capabilities."; + public static final String INTERFACE_PREFIX = "tosca.interfaces."; + public static final String ARTIFACT_PREFIX = "tosca.artifacts."; + public static final String POLICY_PREFIX = "tosca.policies."; + public static final String GROUP_PREFIX = "tosca.groups."; + //currently the data types are defined only for network + // but may have changes in the future. + public static final String DATATYPE_PREFIX = "tosca.datatypes."; + public static final String DATATYPE_NETWORK_PREFIX = DATATYPE_PREFIX + "network."; + public static final String TOSCA = "tosca"; + + protected String type; + protected LinkedHashMap<String, Object> defs = null; + + public Object getParentType() { + return null; + } + + public String derivedFrom(LinkedHashMap<String, Object> defs) { // Return a type this type is derived from - return (String)entityValue(defs, "derived_from"); + return (String) entityValue(defs, "derived_from"); } public boolean isDerivedFrom(String type_str) { // Check if object inherits from the given type // Returns true if this object is derived from 'type_str' // False otherwise. - if(type == null || this.type.isEmpty()) { + if (type == null || this.type.isEmpty()) { return false; - } - else if(type == type_str) { + } else if (type == type_str) { return true; - } - else if(getParentType() != null) { - return ((EntityType)getParentType()).isDerivedFrom(type_str); - } - else { + } else if (getParentType() != null) { + return ((EntityType) getParentType()).isDerivedFrom(type_str); + } else { return false; } } - public Object entityValue(LinkedHashMap<String,Object> defs, String key) { - if(defs != null) { - return defs.get(key); - } - return null; + public Object entityValue(LinkedHashMap<String, Object> defs, String key) { + if (defs != null) { + return defs.get(key); + } + return null; } @SuppressWarnings("unchecked") - public Object getValue(String ndtype, LinkedHashMap<String,Object> _defs, boolean parent) { + public Object getValue(String ndtype, LinkedHashMap<String, Object> _defs, boolean parent) { Object value = null; - if(_defs == null) { - if(defs == null) { + if (_defs == null) { + if (defs == null) { return null; } _defs = this.defs; } - Object defndt = _defs.get(ndtype); - if(defndt != null) { + Object defndt = _defs.get(ndtype); + if (defndt != null) { // copy the value to avoid that next operations add items in the // item definitions //value = copy.copy(defs[ndtype]) - value = CopyUtils.copyLhmOrAl(defndt); + value = CopyUtils.copyLhmOrAl(defndt); } - - if(parent) { + + if (parent) { EntityType p = this; - if(p != null) { - while(p != null) { - if(p.defs != null && p.defs.get(ndtype) != null) { + if (p != null) { + while (p != null) { + if (p.defs != null && p.defs.get(ndtype) != null) { // get the parent value Object parentValue = p.defs.get(ndtype); - if(value != null) { - if(value instanceof LinkedHashMap) { - for(Map.Entry<String,Object> me: ((LinkedHashMap<String,Object>)parentValue).entrySet()) { - String k = me.getKey(); - if(((LinkedHashMap<String,Object>)value).get(k) == null) { - ((LinkedHashMap<String,Object>)value).put(k,me.getValue()); - } - } + if (value != null) { + if (value instanceof LinkedHashMap) { + for (Map.Entry<String, Object> me : ((LinkedHashMap<String, Object>) parentValue).entrySet()) { + String k = me.getKey(); + if (((LinkedHashMap<String, Object>) value).get(k) == null) { + ((LinkedHashMap<String, Object>) value).put(k, me.getValue()); + } + } } - if(value instanceof ArrayList) { - for(Object pValue: (ArrayList<Object>)parentValue) { - if(!((ArrayList<Object>)value).contains(pValue)) { - ((ArrayList<Object>)value).add(pValue); - } - } + if (value instanceof ArrayList) { + for (Object pValue : (ArrayList<Object>) parentValue) { + if (!((ArrayList<Object>) value).contains(pValue)) { + ((ArrayList<Object>) value).add(pValue); + } + } } - } - else { - // value = copy.copy(parent_value) + } else { + // value = copy.copy(parent_value) value = CopyUtils.copyLhmOrAl(parentValue); } - } - p = (EntityType)p.getParentType(); + } + p = (EntityType) p.getParentType(); } } } - - return value; - } + + return value; + } @SuppressWarnings("unchecked") - public Object getDefinition(String ndtype) { + public Object getDefinition(String ndtype) { Object value = null; - LinkedHashMap<String,Object> _defs; + LinkedHashMap<String, Object> _defs; // no point in hasattr, because we have it, and it // doesn't do anything except emit an exception anyway //if not hasattr(self, 'defs'): @@ -228,59 +228,57 @@ public class EntityType { //else: // defs = self.defs _defs = this.defs; - - if(_defs != null && _defs.get(ndtype) != null) { - value = _defs.get(ndtype); + + if (_defs != null && _defs.get(ndtype) != null) { + value = _defs.get(ndtype); } Object p = getParentType(); - if(p != null) { - Object inherited = ((EntityType)p).getDefinition(ndtype); - if(inherited != null) { + if (p != null) { + Object inherited = ((EntityType) p).getDefinition(ndtype); + if (inherited != null) { // inherited = dict(inherited) WTF?!? - if(value == null) { - value = inherited; - } - else { - //????? + if (value == null) { + value = inherited; + } else { + //????? //inherited.update(value) //value.update(inherited) - for(Map.Entry<String,Object> me: ((LinkedHashMap<String,Object>)inherited).entrySet()) { - ((LinkedHashMap<String,Object>)value).put(me.getKey(),me.getValue()); - } - } - } + for (Map.Entry<String, Object> me : ((LinkedHashMap<String, Object>) inherited).entrySet()) { + ((LinkedHashMap<String, Object>) value).put(me.getKey(), me.getValue()); + } + } + } } return value; } - - public static void updateDefinitions(String version) { + + public static void updateDefinitions(String version) { ExtTools exttools = new ExtTools(); String extensionDefsFile = exttools.getDefsFile(version); - try (InputStream input = EntityType.class.getClassLoader().getResourceAsStream(extensionDefsFile);){ - Yaml yaml = new Yaml(); - LinkedHashMap<String,Object> nfvDefFile = (LinkedHashMap<String,Object>)yaml.load(input); - LinkedHashMap<String,Object> nfvDef = new LinkedHashMap<>(); - for(String section: TOSCA_DEF_SECTIONS) { - if(nfvDefFile.get(section) != null) { - LinkedHashMap<String,Object> value = - (LinkedHashMap<String,Object>)nfvDefFile.get(section); - for(String key: value.keySet()) { - nfvDef.put(key, value.get(key)); - } - } - } - TOSCA_DEF.putAll(nfvDef); - } - catch (IOException e) { - log.error("EntityType - updateDefinitions - Failed to update definitions from defs file {}",extensionDefsFile); - log.error("Exception:", e); - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE280", - String.format("Failed to update definitions from defs file \"%s\" ",extensionDefsFile))); - return; - } + try (InputStream input = EntityType.class.getClassLoader().getResourceAsStream(extensionDefsFile);) { + Yaml yaml = new Yaml(); + LinkedHashMap<String, Object> nfvDefFile = (LinkedHashMap<String, Object>) yaml.load(input); + LinkedHashMap<String, Object> nfvDef = new LinkedHashMap<>(); + for (String section : TOSCA_DEF_SECTIONS) { + if (nfvDefFile.get(section) != null) { + LinkedHashMap<String, Object> value = + (LinkedHashMap<String, Object>) nfvDefFile.get(section); + for (String key : value.keySet()) { + nfvDef.put(key, value.get(key)); + } + } + } + TOSCA_DEF.putAll(nfvDef); + } catch (IOException e) { + log.error("EntityType - updateDefinitions - Failed to update definitions from defs file {}", extensionDefsFile); + log.error("Exception:", e); + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE280", + String.format("Failed to update definitions from defs file \"%s\" ", extensionDefsFile))); + return; + } } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/GroupType.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/GroupType.java index cbcb6f6..db6f2b7 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/GroupType.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/GroupType.java @@ -7,9 +7,9 @@ * 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. @@ -29,151 +29,150 @@ import java.util.Map; public class GroupType extends StatefulEntityType { - private static final String DERIVED_FROM = "derived_from"; - private static final String VERSION = "version"; - private static final String METADATA = "metadata"; - private static final String DESCRIPTION = "description"; - private static final String PROPERTIES = "properties"; - private static final String MEMBERS = "members"; - private static final String INTERFACES = "interfaces"; - - private static final String SECTIONS[] = { - DERIVED_FROM, VERSION, METADATA, DESCRIPTION, PROPERTIES, MEMBERS, INTERFACES}; - - private String groupType; - private LinkedHashMap<String,Object> customDef; - private String groupDescription; - private String groupVersion; - //private LinkedHashMap<String,Object> groupProperties; - //private ArrayList<String> groupMembers; - private LinkedHashMap<String,Object> metaData; - - @SuppressWarnings("unchecked") - public GroupType(String _grouptype,LinkedHashMap<String,Object> _customDef) { - super(_grouptype,GROUP_PREFIX,_customDef); - - groupType = _grouptype; - customDef = _customDef; - _validateFields(); - if(defs != null) { - groupDescription = (String)defs.get(DESCRIPTION); - groupVersion = (String)defs.get(VERSION); - //groupProperties = (LinkedHashMap<String,Object>)defs.get(PROPERTIES); - //groupMembers = (ArrayList<String>)defs.get(MEMBERS); - Object mdo = defs.get(METADATA); - if(mdo instanceof LinkedHashMap) { - metaData = (LinkedHashMap<String,Object>)mdo; - } - else { - metaData = null; - } - - if(metaData != null) { - _validateMetadata(metaData); - } - } - } - - public GroupType getParentType() { + private static final String DERIVED_FROM = "derived_from"; + private static final String VERSION = "version"; + private static final String METADATA = "metadata"; + private static final String DESCRIPTION = "description"; + private static final String PROPERTIES = "properties"; + private static final String MEMBERS = "members"; + private static final String INTERFACES = "interfaces"; + + private static final String[] SECTIONS = { + DERIVED_FROM, VERSION, METADATA, DESCRIPTION, PROPERTIES, MEMBERS, INTERFACES}; + + private String groupType; + private LinkedHashMap<String, Object> customDef; + private String groupDescription; + private String groupVersion; + //private LinkedHashMap<String,Object> groupProperties; + //private ArrayList<String> groupMembers; + private LinkedHashMap<String, Object> metaData; + + @SuppressWarnings("unchecked") + public GroupType(String groupType, LinkedHashMap<String, Object> customDef) { + super(groupType, GROUP_PREFIX, customDef); + + this.groupType = groupType; + this.customDef = customDef; + validateFields(); + if (defs != null) { + groupDescription = (String) defs.get(DESCRIPTION); + groupVersion = (String) defs.get(VERSION); + //groupProperties = (LinkedHashMap<String,Object>)defs.get(PROPERTIES); + //groupMembers = (ArrayList<String>)defs.get(MEMBERS); + Object mdo = defs.get(METADATA); + if (mdo instanceof LinkedHashMap) { + metaData = (LinkedHashMap<String, Object>) mdo; + } else { + metaData = null; + } + + if (metaData != null) { + validateMetadata(metaData); + } + } + } + + public GroupType getParentType() { // Return a group statefulentity of this entity is derived from. - if(defs == null) { + if (defs == null) { return null; } String pgroupEntity = derivedFrom(defs); - if(pgroupEntity != null) { - return new GroupType(pgroupEntity,customDef); + if (pgroupEntity != null) { + return new GroupType(pgroupEntity, customDef); } return null; - } - - public String getDescription() { - return groupDescription; - } - - public String getVersion() { - return groupVersion; - } - - @SuppressWarnings("unchecked") - public LinkedHashMap<String,Object> getInterfaces() { - Object ifo = getValue(INTERFACES,null,false); - if(ifo instanceof LinkedHashMap) { - return (LinkedHashMap<String, Object>)ifo; - } - return new LinkedHashMap<String,Object>(); - } - - private void _validateFields() { - if(defs != null) { - for(String name: defs.keySet()) { - boolean bFound = false; - for(String sect: SECTIONS) { - if(name.equals(sect)) { - bFound = true; - break; - } - } - if(!bFound) { + } + + public String getDescription() { + return groupDescription; + } + + public String getVersion() { + return groupVersion; + } + + @SuppressWarnings("unchecked") + public LinkedHashMap<String, Object> getInterfaces() { + Object ifo = getValue(INTERFACES, null, false); + if (ifo instanceof LinkedHashMap) { + return (LinkedHashMap<String, Object>) ifo; + } + return new LinkedHashMap<String, Object>(); + } + + private void validateFields() { + if (defs != null) { + for (String name : defs.keySet()) { + boolean bFound = false; + for (String sect : SECTIONS) { + if (name.equals(sect)) { + bFound = true; + break; + } + } + if (!bFound) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE120", String.format( - "UnknownFieldError: Group Type \"%s\" contains unknown field \"%s\"", - groupType,name))); - } - } - } - } - - @SuppressWarnings("unchecked") - private void _validateMetadata(LinkedHashMap<String,Object> metadata) { - String mtt = (String) metadata.get("type"); - if(mtt != null && !mtt.equals("map") && !mtt.equals("tosca:map")) { + "UnknownFieldError: Group Type \"%s\" contains unknown field \"%s\"", + groupType, name))); + } + } + } + } + + @SuppressWarnings("unchecked") + private void validateMetadata(LinkedHashMap<String, Object> metadata) { + String mtt = (String) metadata.get("type"); + if (mtt != null && !mtt.equals("map") && !mtt.equals("tosca:map")) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE121", String.format( - "InvalidTypeError: \"%s\" defined in group for metadata is invalid", - mtt))); - } - for(String entrySchema: metadata.keySet()) { - Object estob = metadata.get(entrySchema); - if(estob instanceof LinkedHashMap) { - String est = (String)((LinkedHashMap<String,Object>)estob).get("type"); - if(!est.equals("string")) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE122", String.format( - "InvalidTypeError: \"%s\" defined in group for metadata \"%s\" is invalid", - est,entrySchema))); - } - } - } - } - - public String getType() { - return groupType; - } - + "InvalidTypeError: \"%s\" defined in group for metadata is invalid", + mtt))); + } + for (String entrySchema : metadata.keySet()) { + Object estob = metadata.get(entrySchema); + if (estob instanceof LinkedHashMap) { + String est = (String) ((LinkedHashMap<String, Object>) estob).get("type"); + if (!est.equals("string")) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE122", String.format( + "InvalidTypeError: \"%s\" defined in group for metadata \"%s\" is invalid", + est, entrySchema))); + } + } + } + } + + public String getType() { + return groupType; + } + @SuppressWarnings("unchecked") - public ArrayList<CapabilityTypeDef> getCapabilitiesObjects() { + public ArrayList<CapabilityTypeDef> getCapabilitiesObjects() { // Return a list of capability objects - ArrayList<CapabilityTypeDef> typecapabilities = new ArrayList<>(); - LinkedHashMap<String,Object> caps = (LinkedHashMap<String,Object>)getValue(CAPABILITIES, null, true); - if(caps != null) { + ArrayList<CapabilityTypeDef> typecapabilities = new ArrayList<>(); + LinkedHashMap<String, Object> caps = (LinkedHashMap<String, Object>) getValue(CAPABILITIES, null, true); + if (caps != null) { // 'cname' is symbolic name of the capability // 'cvalue' is a dict { 'type': <capability type name> } - for(Map.Entry<String,Object> me: caps.entrySet()) { - String cname = me.getKey(); - LinkedHashMap<String,String> cvalue = (LinkedHashMap<String,String>)me.getValue(); - String ctype = cvalue.get("type"); - CapabilityTypeDef cap = new CapabilityTypeDef(cname,ctype,type,customDef); - typecapabilities.add(cap); - } + for (Map.Entry<String, Object> me : caps.entrySet()) { + String cname = me.getKey(); + LinkedHashMap<String, String> cvalue = (LinkedHashMap<String, String>) me.getValue(); + String ctype = cvalue.get("type"); + CapabilityTypeDef cap = new CapabilityTypeDef(cname, ctype, type, customDef); + typecapabilities.add(cap); + } } return typecapabilities; - } - - public LinkedHashMap<String,CapabilityTypeDef> getCapabilities() { + } + + public LinkedHashMap<String, CapabilityTypeDef> getCapabilities() { // Return a dictionary of capability name-objects pairs - LinkedHashMap<String,CapabilityTypeDef> caps = new LinkedHashMap<>(); - for(CapabilityTypeDef ctd: getCapabilitiesObjects()) { - caps.put(ctd.getName(),ctd); - } - return caps; - } + LinkedHashMap<String, CapabilityTypeDef> caps = new LinkedHashMap<>(); + for (CapabilityTypeDef ctd : getCapabilitiesObjects()) { + caps.put(ctd.getName(), ctd); + } + return caps; + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/InterfacesDef.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/InterfacesDef.java index ceb8fb9..2862a11 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/InterfacesDef.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/InterfacesDef.java @@ -7,9 +7,9 @@ * 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. @@ -30,167 +30,163 @@ import java.util.Map; public class InterfacesDef extends StatefulEntityType { - public static final String LIFECYCLE = "tosca.interfaces.node.lifecycle.Standard"; - public static final String CONFIGURE = "tosca.interfaces.relationship.Configure"; - public static final String LIFECYCLE_SHORTNAME = "Standard"; - public static final String CONFIGURE_SHORTNAME = "Configure"; - - public static final String SECTIONS[] = { - LIFECYCLE, CONFIGURE, LIFECYCLE_SHORTNAME,CONFIGURE_SHORTNAME - }; - - public static final String IMPLEMENTATION = "implementation"; - public static final String DESCRIPTION = "description"; - public static final String INPUTS = "inputs"; - - public static final String INTERFACE_DEF_RESERVED_WORDS[] = { - "type", "inputs", "derived_from", "version", "description"}; - - private EntityType ntype; - private EntityTemplate nodeTemplate; - - private String operationName; - private Object operationDef; - private Object implementation; - private LinkedHashMap<String,Object> inputs; - private String description; - - @SuppressWarnings("unchecked") - public InterfacesDef(EntityType inodeType, - String interfaceType, - EntityTemplate inodeTemplate, - String iname, - Object ivalue) { - // void - super(); - - ntype = inodeType; - nodeTemplate = inodeTemplate; - type = interfaceType; - operationName = iname; - operationDef = ivalue; - implementation = null; - inputs = null; - defs = new LinkedHashMap<String,Object>(); - - if(interfaceType.equals(LIFECYCLE_SHORTNAME)) { - interfaceType = LIFECYCLE; - } - if(interfaceType.equals(CONFIGURE_SHORTNAME)) { - interfaceType = CONFIGURE; - } - - // only NodeType has getInterfaces "hasattr(ntype,interfaces)" - // while RelationshipType does not - if(ntype instanceof NodeType) { - if(((NodeType)ntype).getInterfaces() != null && - ((NodeType)ntype).getInterfaces().values().contains(interfaceType)) { - LinkedHashMap<String,Object> nii = (LinkedHashMap<String,Object>) - ((NodeType)ntype).getInterfaces().get(interfaceType); - interfaceType = (String)nii.get("type"); - } - } - if(inodeType != null) { - if(nodeTemplate != null && nodeTemplate.getCustomDef() != null && - nodeTemplate.getCustomDef().containsKey(interfaceType)) { - defs = (LinkedHashMap<String,Object>) - nodeTemplate.getCustomDef().get(interfaceType); - } - else { - defs = (LinkedHashMap<String,Object>)TOSCA_DEF.get(interfaceType); - } - } - - if(ivalue != null) { - if(ivalue instanceof LinkedHashMap) { - for(Map.Entry<String,Object> me: ((LinkedHashMap<String,Object>)ivalue).entrySet()) { - if(me.getKey().equals(IMPLEMENTATION)) { - implementation = me.getValue(); - } - else if(me.getKey().equals(INPUTS)) { - inputs = (LinkedHashMap<String,Object>)me.getValue(); - } - else if(me.getKey().equals(DESCRIPTION)) { - description = (String)me.getValue(); - } - else { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE123", String.format( - "UnknownFieldError: \"interfaces\" of template \"%s\" contain unknown field \"%s\"", - nodeTemplate.getName(),me.getKey()))); - } - } - } - } - } - - public ArrayList<String> getLifecycleOps() { - if(defs != null) { - if(type.equals(LIFECYCLE)) { - return _ops(); - } - } - return null; - } - - public ArrayList<String> getInterfaceOps() { - if(defs != null) { - ArrayList<String> ops = _ops(); - ArrayList<String> idrw = new ArrayList<>(); - for(int i=0; i<InterfacesDef.INTERFACE_DEF_RESERVED_WORDS.length; i++) { - idrw.add(InterfacesDef.INTERFACE_DEF_RESERVED_WORDS[i]); - } - ops.removeAll(idrw); - return ops; - } - return null; - } - - public ArrayList<String> getConfigureOps() { - if(defs != null) { - if(type.equals(CONFIGURE)) { - return _ops(); - } - } - return null; - } - - private ArrayList<String> _ops() { - return new ArrayList<String>(defs.keySet()); - } - - // getters/setters - - public LinkedHashMap<String,Object> getInputs() { - return inputs; - } - - public void setInput(String name,Object value) { - inputs.put(name, value); - } - - public Object getImplementation(){ - return implementation; - } - - public void setImplementation(Object implementation){ - this.implementation = implementation; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getOperationName() { - return operationName; - } - - public void setOperationName(String operationName) { - this.operationName = operationName; - } + public static final String LIFECYCLE = "tosca.interfaces.node.lifecycle.Standard"; + public static final String CONFIGURE = "tosca.interfaces.relationship.Configure"; + public static final String LIFECYCLE_SHORTNAME = "Standard"; + public static final String CONFIGURE_SHORTNAME = "Configure"; + + public static final String[] SECTIONS = { + LIFECYCLE, CONFIGURE, LIFECYCLE_SHORTNAME, CONFIGURE_SHORTNAME + }; + + public static final String IMPLEMENTATION = "implementation"; + public static final String DESCRIPTION = "description"; + public static final String INPUTS = "inputs"; + + public static final String[] INTERFACE_DEF_RESERVED_WORDS = { + "type", "inputs", "derived_from", "version", "description"}; + + private EntityType ntype; + private EntityTemplate nodeTemplate; + + private String operationName; + private Object operationDef; + private Object implementation; + private LinkedHashMap<String, Object> inputs; + private String description; + + @SuppressWarnings("unchecked") + public InterfacesDef(EntityType inodeType, + String interfaceType, + EntityTemplate inodeTemplate, + String iname, + Object ivalue) { + // void + super(); + + ntype = inodeType; + nodeTemplate = inodeTemplate; + type = interfaceType; + operationName = iname; + operationDef = ivalue; + implementation = null; + inputs = null; + defs = new LinkedHashMap<>(); + + if (interfaceType.equals(LIFECYCLE_SHORTNAME)) { + interfaceType = LIFECYCLE; + } + if (interfaceType.equals(CONFIGURE_SHORTNAME)) { + interfaceType = CONFIGURE; + } + + // only NodeType has getInterfaces "hasattr(ntype,interfaces)" + // while RelationshipType does not + if (ntype instanceof NodeType) { + if (((NodeType) ntype).getInterfaces() != null + && ((NodeType) ntype).getInterfaces().values().contains(interfaceType)) { + LinkedHashMap<String, Object> nii = (LinkedHashMap<String, Object>) + ((NodeType) ntype).getInterfaces().get(interfaceType); + interfaceType = (String) nii.get("type"); + } + } + if (inodeType != null) { + if (nodeTemplate != null && nodeTemplate.getCustomDef() != null + && nodeTemplate.getCustomDef().containsKey(interfaceType)) { + defs = (LinkedHashMap<String, Object>) + nodeTemplate.getCustomDef().get(interfaceType); + } else { + defs = (LinkedHashMap<String, Object>) TOSCA_DEF.get(interfaceType); + } + } + + if (ivalue != null) { + if (ivalue instanceof LinkedHashMap) { + for (Map.Entry<String, Object> me : ((LinkedHashMap<String, Object>) ivalue).entrySet()) { + if (me.getKey().equals(IMPLEMENTATION)) { + implementation = me.getValue(); + } else if (me.getKey().equals(INPUTS)) { + inputs = (LinkedHashMap<String, Object>) me.getValue(); + } else if (me.getKey().equals(DESCRIPTION)) { + description = (String) me.getValue(); + } else { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE123", String.format( + "UnknownFieldError: \"interfaces\" of template \"%s\" contain unknown field \"%s\"", + nodeTemplate.getName(), me.getKey()))); + } + } + } + } + } + + public ArrayList<String> getLifecycleOps() { + if (defs != null) { + if (type.equals(LIFECYCLE)) { + return ops(); + } + } + return null; + } + + public ArrayList<String> getInterfaceOps() { + if (defs != null) { + ArrayList<String> ops = ops(); + ArrayList<String> idrw = new ArrayList<>(); + for (int i = 0; i < InterfacesDef.INTERFACE_DEF_RESERVED_WORDS.length; i++) { + idrw.add(InterfacesDef.INTERFACE_DEF_RESERVED_WORDS[i]); + } + ops.removeAll(idrw); + return ops; + } + return null; + } + + public ArrayList<String> getConfigureOps() { + if (defs != null) { + if (type.equals(CONFIGURE)) { + return ops(); + } + } + return null; + } + + private ArrayList<String> ops() { + return new ArrayList<String>(defs.keySet()); + } + + // getters/setters + + public LinkedHashMap<String, Object> getInputs() { + return inputs; + } + + public void setInput(String name, Object value) { + inputs.put(name, value); + } + + public Object getImplementation() { + return implementation; + } + + public void setImplementation(Object implementation) { + this.implementation = implementation; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getOperationName() { + return operationName; + } + + public void setOperationName(String operationName) { + this.operationName = operationName; + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/Metadata.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/Metadata.java index dd914d4..f3de49e 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/Metadata.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/Metadata.java @@ -7,9 +7,9 @@ * 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. @@ -26,36 +26,37 @@ import java.util.Map; import java.util.stream.Collectors; public class Metadata { - - private final Map<String, Object> metadataMap; - public Metadata(Map<String, Object> metadataMap) { + private final Map<String, Object> metadataMap; + + public Metadata(Map<String, Object> metadataMap) { this.metadataMap = metadataMap != null ? metadataMap : new HashMap<>(); } - public String getValue(String key) { - - Object obj = this.metadataMap.get(key); - if (obj != null){ - return String.valueOf(obj); - } - return null; - } - - /** - * Get all properties of a Metadata object.<br> - * This object represents the "metadata" section of some entity. - * @return all properties of this Metadata, as a key-value. - */ - public Map<String, String> getAllProperties() { - return metadataMap.entrySet().stream().map(e-> new AbstractMap.SimpleEntry<String, String>(e.getKey(), String.valueOf(e.getValue()))).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue)); - } - - @Override - public String toString() { - return "Metadata{" + - "metadataMap=" + metadataMap + - '}'; - } + public String getValue(String key) { + + Object obj = this.metadataMap.get(key); + if (obj != null) { + return String.valueOf(obj); + } + return null; + } + + /** + * Get all properties of a Metadata object.<br> + * This object represents the "metadata" section of some entity. + * + * @return all properties of this Metadata, as a key-value. + */ + public Map<String, String> getAllProperties() { + return metadataMap.entrySet().stream().map(e -> new AbstractMap.SimpleEntry<String, String>(e.getKey(), String.valueOf(e.getValue()))).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + @Override + public String toString() { + return "Metadata{" + + "metadataMap=" + metadataMap + + '}'; + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/NodeType.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/NodeType.java index 918c629..c251be9 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/NodeType.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/NodeType.java @@ -7,9 +7,9 @@ * 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. @@ -28,305 +28,300 @@ import java.util.LinkedHashMap; import java.util.Map; public class NodeType extends StatefulEntityType { - // TOSCA built-in node type - - private static final String DERIVED_FROM = "derived_from"; - private static final String METADATA = "metadata"; - private static final String PROPERTIES = "properties"; - private static final String VERSION = "version"; - private static final String DESCRIPTION = "description"; - private static final String ATTRIBUTES = "attributes"; - private static final String REQUIREMENTS = "requirements"; - private static final String CAPABILITIES = "capabilities"; - private static final String INTERFACES = "interfaces"; - private static final String ARTIFACTS = "artifacts"; - - private static final String SECTIONS[] = { - DERIVED_FROM, METADATA, PROPERTIES, VERSION, DESCRIPTION, ATTRIBUTES, REQUIREMENTS, CAPABILITIES, INTERFACES, ARTIFACTS - }; - - private String ntype; - public LinkedHashMap<String,Object> customDef; - - public NodeType(String nttype,LinkedHashMap<String,Object> ntcustomDef) { - super(nttype,NODE_PREFIX, ntcustomDef); + // TOSCA built-in node type + + private static final String DERIVED_FROM = "derived_from"; + private static final String METADATA = "metadata"; + private static final String PROPERTIES = "properties"; + private static final String VERSION = "version"; + private static final String DESCRIPTION = "description"; + private static final String ATTRIBUTES = "attributes"; + private static final String REQUIREMENTS = "requirements"; + private static final String CAPABILITIES = "capabilities"; + private static final String INTERFACES = "interfaces"; + private static final String ARTIFACTS = "artifacts"; + + private static final String SECTIONS[] = { + DERIVED_FROM, METADATA, PROPERTIES, VERSION, DESCRIPTION, ATTRIBUTES, REQUIREMENTS, CAPABILITIES, INTERFACES, ARTIFACTS + }; + + private String ntype; + public LinkedHashMap<String, Object> customDef; + + public NodeType(String nttype, LinkedHashMap<String, Object> ntcustomDef) { + super(nttype, NODE_PREFIX, ntcustomDef); ntype = nttype; customDef = ntcustomDef; _validateKeys(); - } + } - public Object getParentType() { + public Object getParentType() { // Return a node this node is derived from - if(defs == null) { - return null; - } - String pnode = derivedFrom(defs); - if(pnode != null && !pnode.isEmpty()) { - return new NodeType(pnode,customDef); - } - return null; - } - - @SuppressWarnings("unchecked") - public LinkedHashMap<RelationshipType,NodeType> getRelationship() { + if (defs == null) { + return null; + } + String pnode = derivedFrom(defs); + if (pnode != null && !pnode.isEmpty()) { + return new NodeType(pnode, customDef); + } + return null; + } + + @SuppressWarnings("unchecked") + public LinkedHashMap<RelationshipType, NodeType> getRelationship() { // Return a dictionary of relationships to other node types // This method returns a dictionary of named relationships that nodes // of the current node type (self) can have to other nodes (of specific // types) in a TOSCA template. - LinkedHashMap<RelationshipType,NodeType> relationship = new LinkedHashMap<>(); - ArrayList<LinkedHashMap<String,Object>> requires; - Object treq = getAllRequirements(); - if(treq != null) { + LinkedHashMap<RelationshipType, NodeType> relationship = new LinkedHashMap<>(); + ArrayList<LinkedHashMap<String, Object>> requires; + Object treq = getAllRequirements(); + if (treq != null) { // NOTE(sdmonov): Check if requires is a dict. // If it is a dict convert it to a list of dicts. // This is needed because currently the code below supports only // lists as requirements definition. The following check will // make sure if a map (dict) was provided it will be converted to // a list before proceeding to the parsing. - if(treq instanceof LinkedHashMap) { - requires = new ArrayList<>(); - for(Map.Entry<String,Object> me: ((LinkedHashMap<String,Object>)treq).entrySet()) { - LinkedHashMap<String,Object> tl = new LinkedHashMap<>(); - tl.put(me.getKey(),me.getValue()); - requires.add(tl); - } - } - else { - requires = (ArrayList<LinkedHashMap<String,Object>>)treq; + if (treq instanceof LinkedHashMap) { + requires = new ArrayList<>(); + for (Map.Entry<String, Object> me : ((LinkedHashMap<String, Object>) treq).entrySet()) { + LinkedHashMap<String, Object> tl = new LinkedHashMap<>(); + tl.put(me.getKey(), me.getValue()); + requires.add(tl); + } + } else { + requires = (ArrayList<LinkedHashMap<String, Object>>) treq; } - + String keyword = null; String nodeType = null; - for(LinkedHashMap<String,Object> require: requires) { - String relation = null; - for(Map.Entry<String,Object> re: require.entrySet()) { - String key = re.getKey(); - LinkedHashMap<String,Object> req = (LinkedHashMap<String,Object>)re.getValue(); - if(req.get("relationship") != null) { - Object trelation = req.get("relationship"); - // trelation is a string or a dict with "type" mapped to the string we want - if(trelation instanceof String) { - relation = (String)trelation; - } - else { - if(((LinkedHashMap<String,Object>)trelation).get("type") != null) { - relation = (String)((LinkedHashMap<String,Object>)trelation).get("type"); - } - } - nodeType = (String)req.get("node"); - //BUG meaningless?? LinkedHashMap<String,Object> value = req; - if(nodeType != null) { - keyword = "node"; - } - else { - String getRelation = null; + for (LinkedHashMap<String, Object> require : requires) { + String relation = null; + for (Map.Entry<String, Object> re : require.entrySet()) { + String key = re.getKey(); + LinkedHashMap<String, Object> req = (LinkedHashMap<String, Object>) re.getValue(); + if (req.get("relationship") != null) { + Object trelation = req.get("relationship"); + // trelation is a string or a dict with "type" mapped to the string we want + if (trelation instanceof String) { + relation = (String) trelation; + } else { + if (((LinkedHashMap<String, Object>) trelation).get("type") != null) { + relation = (String) ((LinkedHashMap<String, Object>) trelation).get("type"); + } + } + nodeType = (String) req.get("node"); + //BUG meaningless?? LinkedHashMap<String,Object> value = req; + if (nodeType != null) { + keyword = "node"; + } else { + String getRelation = null; // If nodeTypeByCap is a dict and has a type key // we need to lookup the node type using // the capability type - String captype = (String)req.get("capability"); - nodeType = _getNodeTypeByCap(captype); - if (nodeType != null){ - getRelation = _getRelation(key, nodeType); - } else { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE11", String.format( - "NodeTypeRequirementForCapabilityUnfulfilled: Node type: \"%s\" with requrement \"%s\" for node type with capability type \"%s\" is not found\\unfulfilled", this.ntype, key, captype))); - } - if (getRelation != null) { - relation = getRelation; - } - keyword = key; - } - } - } - if(relation == null || nodeType == null){ - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE11", String.format( - "NodeTypeForRelationUnfulfilled: Node type \"%s\" - relationship type \"%s\" is unfulfilled", this.ntype, relation))); - } else { - RelationshipType rtype = new RelationshipType(relation, keyword, customDef); - NodeType relatednode = new NodeType(nodeType, customDef); - relationship.put(rtype, relatednode); - } + String captype = (String) req.get("capability"); + nodeType = _getNodeTypeByCap(captype); + if (nodeType != null) { + getRelation = _getRelation(key, nodeType); + } else { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE11", String.format( + "NodeTypeRequirementForCapabilityUnfulfilled: Node type: \"%s\" with requrement \"%s\" for node type with capability type \"%s\" is not found\\unfulfilled", this.ntype, key, captype))); + } + if (getRelation != null) { + relation = getRelation; + } + keyword = key; + } + } + } + if (relation == null || nodeType == null) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE11", String.format( + "NodeTypeForRelationUnfulfilled: Node type \"%s\" - relationship type \"%s\" is unfulfilled", this.ntype, relation))); + } else { + RelationshipType rtype = new RelationshipType(relation, keyword, customDef); + NodeType relatednode = new NodeType(nodeType, customDef); + relationship.put(rtype, relatednode); + } } - } - return relationship; - - } - + } + return relationship; + + } + @SuppressWarnings("unchecked") - private String _getNodeTypeByCap(String cap) { + private String _getNodeTypeByCap(String cap) { // Find the node type that has the provided capability // This method will lookup all node types if they have the // provided capability. // Filter the node types ArrayList<String> nodeTypes = new ArrayList<>(); - for(String nt: customDef.keySet()) { - if(nt.startsWith(NODE_PREFIX) || nt.startsWith("org.openecomp") && !nt.equals("tosca.nodes.Root")) { - nodeTypes.add(nt); - } + for (String nt : customDef.keySet()) { + if (nt.startsWith(NODE_PREFIX) || nt.startsWith("org.openecomp") && !nt.equals("tosca.nodes.Root")) { + nodeTypes.add(nt); + } } - for(String nt: nodeTypes) { - LinkedHashMap<String,Object> nodeDef = (LinkedHashMap<String,Object>)customDef.get(nt); - if(nodeDef instanceof LinkedHashMap && nodeDef.get("capabilities") != null) { - LinkedHashMap<String,Object> nodeCaps = (LinkedHashMap<String,Object>)nodeDef.get("capabilities"); - if(nodeCaps != null) { - for(Object val: nodeCaps.values()) { - if(val instanceof LinkedHashMap) { - String tp = (String)((LinkedHashMap<String,Object>)val).get("type"); - if(tp != null && tp.equals(cap)) { - return nt; - } - } - } - } + for (String nt : nodeTypes) { + LinkedHashMap<String, Object> nodeDef = (LinkedHashMap<String, Object>) customDef.get(nt); + if (nodeDef instanceof LinkedHashMap && nodeDef.get("capabilities") != null) { + LinkedHashMap<String, Object> nodeCaps = (LinkedHashMap<String, Object>) nodeDef.get("capabilities"); + if (nodeCaps != null) { + for (Object val : nodeCaps.values()) { + if (val instanceof LinkedHashMap) { + String tp = (String) ((LinkedHashMap<String, Object>) val).get("type"); + if (tp != null && tp.equals(cap)) { + return nt; + } + } + } + } } - } + } return null; - } - + } + @SuppressWarnings("unchecked") - private String _getRelation(String key,String ndtype) { - String relation = null; - NodeType ntype = new NodeType(ndtype, customDef); - LinkedHashMap<String,CapabilityTypeDef> caps = ntype.getCapabilities(); - if(caps != null && caps.get(key) != null) { - CapabilityTypeDef c = caps.get(key); - for(int i=0; i< RELATIONSHIP_TYPE.length; i++) { - String r = RELATIONSHIP_TYPE[i]; - if(r != null) { - relation = r; - break; - } - LinkedHashMap<String,Object> rtypedef = (LinkedHashMap<String,Object>)customDef.get(r); - for(Object o: rtypedef.values()) { - LinkedHashMap<String,Object> properties = (LinkedHashMap<String,Object>)o; - if(properties.get(c.getType()) != null) { - relation = r; - break; - } - } - if(relation != null) { - break; - } - else { - for(Object o: rtypedef.values()) { - LinkedHashMap<String,Object> properties = (LinkedHashMap<String,Object>)o; - if(properties.get(c.getParentType()) != null) { - relation = r; - break; - } - } - } - } - } - return relation; + private String _getRelation(String key, String ndtype) { + String relation = null; + NodeType ntype = new NodeType(ndtype, customDef); + LinkedHashMap<String, CapabilityTypeDef> caps = ntype.getCapabilities(); + if (caps != null && caps.get(key) != null) { + CapabilityTypeDef c = caps.get(key); + for (int i = 0; i < RELATIONSHIP_TYPE.length; i++) { + String r = RELATIONSHIP_TYPE[i]; + if (r != null) { + relation = r; + break; + } + LinkedHashMap<String, Object> rtypedef = (LinkedHashMap<String, Object>) customDef.get(r); + for (Object o : rtypedef.values()) { + LinkedHashMap<String, Object> properties = (LinkedHashMap<String, Object>) o; + if (properties.get(c.getType()) != null) { + relation = r; + break; + } + } + if (relation != null) { + break; + } else { + for (Object o : rtypedef.values()) { + LinkedHashMap<String, Object> properties = (LinkedHashMap<String, Object>) o; + if (properties.get(c.getParentType()) != null) { + relation = r; + break; + } + } + } + } + } + return relation; } @SuppressWarnings("unchecked") - public ArrayList<CapabilityTypeDef> getCapabilitiesObjects() { + public ArrayList<CapabilityTypeDef> getCapabilitiesObjects() { // Return a list of capability objects - ArrayList<CapabilityTypeDef> typecapabilities = new ArrayList<>(); - LinkedHashMap<String,Object> caps = (LinkedHashMap<String,Object>)getValue(CAPABILITIES, null, true); - if(caps != null) { + ArrayList<CapabilityTypeDef> typecapabilities = new ArrayList<>(); + LinkedHashMap<String, Object> caps = (LinkedHashMap<String, Object>) getValue(CAPABILITIES, null, true); + if (caps != null) { // 'cname' is symbolic name of the capability // 'cvalue' is a dict { 'type': <capability type name> } - for(Map.Entry<String,Object> me: caps.entrySet()) { - String cname = me.getKey(); - LinkedHashMap<String,String> cvalue = (LinkedHashMap<String,String>)me.getValue(); - String ctype = cvalue.get("type"); - CapabilityTypeDef cap = new CapabilityTypeDef(cname,ctype,type,customDef); - typecapabilities.add(cap); - } + for (Map.Entry<String, Object> me : caps.entrySet()) { + String cname = me.getKey(); + LinkedHashMap<String, String> cvalue = (LinkedHashMap<String, String>) me.getValue(); + String ctype = cvalue.get("type"); + CapabilityTypeDef cap = new CapabilityTypeDef(cname, ctype, type, customDef); + typecapabilities.add(cap); + } } return typecapabilities; - } - - public LinkedHashMap<String,CapabilityTypeDef> getCapabilities() { + } + + public LinkedHashMap<String, CapabilityTypeDef> getCapabilities() { // Return a dictionary of capability name-objects pairs - LinkedHashMap<String,CapabilityTypeDef> caps = new LinkedHashMap<>(); - for(CapabilityTypeDef ctd: getCapabilitiesObjects()) { - caps.put(ctd.getName(),ctd); - } - return caps; - } - - @SuppressWarnings("unchecked") - public ArrayList<Object> getRequirements() { - return (ArrayList<Object>)getValue(REQUIREMENTS,null,true); - } - - public ArrayList<Object> getAllRequirements() { - return getRequirements(); - } - - @SuppressWarnings("unchecked") - public LinkedHashMap<String,Object> getInterfaces() { - return (LinkedHashMap<String,Object>)getValue(INTERFACES,null,false); - } - - - @SuppressWarnings("unchecked") - public ArrayList<String> getLifecycleInputs() - { + LinkedHashMap<String, CapabilityTypeDef> caps = new LinkedHashMap<>(); + for (CapabilityTypeDef ctd : getCapabilitiesObjects()) { + caps.put(ctd.getName(), ctd); + } + return caps; + } + + @SuppressWarnings("unchecked") + public ArrayList<Object> getRequirements() { + return (ArrayList<Object>) getValue(REQUIREMENTS, null, true); + } + + public ArrayList<Object> getAllRequirements() { + return getRequirements(); + } + + @SuppressWarnings("unchecked") + public LinkedHashMap<String, Object> getInterfaces() { + return (LinkedHashMap<String, Object>) getValue(INTERFACES, null, false); + } + + + @SuppressWarnings("unchecked") + public ArrayList<String> getLifecycleInputs() { // Return inputs to life cycle operations if found ArrayList<String> inputs = new ArrayList<>(); - LinkedHashMap<String,Object> interfaces = getInterfaces(); - if(interfaces != null) { - for(Map.Entry<String,Object> me: interfaces.entrySet()) { - String iname = me.getKey(); - LinkedHashMap<String,Object> ivalue = (LinkedHashMap<String,Object>)me.getValue(); - if(iname.equals(InterfacesDef.LIFECYCLE)) { - for(Map.Entry<String,Object> ie: ivalue.entrySet()) { - if(ie.getKey().equals("input")) { - LinkedHashMap<String,Object> y = (LinkedHashMap<String,Object>)ie.getValue(); - for(String i: y.keySet()) { - inputs.add(i); - } - } - } - } - } + LinkedHashMap<String, Object> interfaces = getInterfaces(); + if (interfaces != null) { + for (Map.Entry<String, Object> me : interfaces.entrySet()) { + String iname = me.getKey(); + LinkedHashMap<String, Object> ivalue = (LinkedHashMap<String, Object>) me.getValue(); + if (iname.equals(InterfacesDef.LIFECYCLE)) { + for (Map.Entry<String, Object> ie : ivalue.entrySet()) { + if (ie.getKey().equals("input")) { + LinkedHashMap<String, Object> y = (LinkedHashMap<String, Object>) ie.getValue(); + for (String i : y.keySet()) { + inputs.add(i); + } + } + } + } + } } return inputs; - } - - public ArrayList<String> getLifecycleOperations() { - // Return available life cycle operations if found - ArrayList<String> ops = null; - LinkedHashMap<String,Object> interfaces = getInterfaces(); - if(interfaces != null) { - InterfacesDef i = new InterfacesDef(this,InterfacesDef.LIFECYCLE,null,null,null); - ops = i.getLifecycleOps(); - } - return ops; - } - - public CapabilityTypeDef getCapability(String name) { - //BUG?? the python code has to be wrong - // it refers to a bad attribute 'value'... - LinkedHashMap<String,CapabilityTypeDef> caps = getCapabilities(); - if(caps != null) { - return caps.get(name); - } - return null; + } + + public ArrayList<String> getLifecycleOperations() { + // Return available life cycle operations if found + ArrayList<String> ops = null; + LinkedHashMap<String, Object> interfaces = getInterfaces(); + if (interfaces != null) { + InterfacesDef i = new InterfacesDef(this, InterfacesDef.LIFECYCLE, null, null, null); + ops = i.getLifecycleOps(); + } + return ops; + } + + public CapabilityTypeDef getCapability(String name) { + //BUG?? the python code has to be wrong + // it refers to a bad attribute 'value'... + LinkedHashMap<String, CapabilityTypeDef> caps = getCapabilities(); + if (caps != null) { + return caps.get(name); + } + return null; /* def get_capability(self, name): caps = self.get_capabilities() if caps and name in caps.keys(): return caps[name].value */ - } + } public String getCapabilityType(String name) { - //BUG?? the python code has to be wrong - // it refers to a bad attribute 'value'... - CapabilityTypeDef captype = getCapability(name); - if(captype != null) { - return captype.getType(); - } - return null; + //BUG?? the python code has to be wrong + // it refers to a bad attribute 'value'... + CapabilityTypeDef captype = getCapability(name); + if (captype != null) { + return captype.getType(); + } + return null; /* def get_capability_type(self, name): captype = self.get_capability(name) @@ -336,21 +331,21 @@ public class NodeType extends StatefulEntityType { } private void _validateKeys() { - if(defs != null) { - for(String key: defs.keySet()) { - boolean bFound = false; - for(int i=0; i< SECTIONS.length; i++) { - if(key.equals(SECTIONS[i])) { - bFound = true; - break; - } - } - if(!bFound) { + if (defs != null) { + for (String key : defs.keySet()) { + boolean bFound = false; + for (int i = 0; i < SECTIONS.length; i++) { + if (key.equals(SECTIONS[i])) { + bFound = true; + break; + } + } + if (!bFound) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE124", String.format( - "UnknownFieldError: Nodetype \"%s\" has unknown field \"%s\"",ntype,key))); - } - } - } + "UnknownFieldError: Nodetype \"%s\" has unknown field \"%s\"", ntype, key))); + } + } + } } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/PolicyType.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/PolicyType.java index e4d1dd6..b227a31 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/PolicyType.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/PolicyType.java @@ -7,9 +7,9 @@ * 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. @@ -21,180 +21,178 @@ package org.onap.sdc.toscaparser.api.elements; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; +import org.onap.sdc.toscaparser.api.utils.TOSCAVersionProperty; +import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; import java.util.ArrayList; import java.util.LinkedHashMap; -import org.onap.sdc.toscaparser.api.utils.TOSCAVersionProperty; -import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; - public class PolicyType extends StatefulEntityType { - - private static final String DERIVED_FROM = "derived_from"; - private static final String METADATA = "metadata"; - private static final String PROPERTIES = "properties"; - private static final String VERSION = "version"; - private static final String DESCRIPTION = "description"; - private static final String TARGETS = "targets"; - private static final String TRIGGERS = "triggers"; - private static final String TYPE = "type"; - - private static final String SECTIONS[] = { - DERIVED_FROM, METADATA, PROPERTIES, VERSION, DESCRIPTION, TARGETS, TRIGGERS, TYPE - }; - - private LinkedHashMap<String,Object> customDef; - private String policyDescription; - private Object policyVersion; - private LinkedHashMap<String,Object> properties; - private LinkedHashMap<String,Object> parentPolicies; - private LinkedHashMap<String,Object> metaData; - private ArrayList<String> targetsList; - - - public PolicyType(String _type, LinkedHashMap<String,Object> _customDef) { - super(_type,POLICY_PREFIX,_customDef); - - type = _type; - customDef = _customDef; - _validateKeys(); - + + private static final String DERIVED_FROM = "derived_from"; + private static final String METADATA = "metadata"; + private static final String PROPERTIES = "properties"; + private static final String VERSION = "version"; + private static final String DESCRIPTION = "description"; + private static final String TARGETS = "targets"; + private static final String TRIGGERS = "triggers"; + private static final String TYPE = "type"; + + private static final String[] SECTIONS = { + DERIVED_FROM, METADATA, PROPERTIES, VERSION, DESCRIPTION, TARGETS, TRIGGERS, TYPE + }; + + private LinkedHashMap<String, Object> customDef; + private String policyDescription; + private Object policyVersion; + private LinkedHashMap<String, Object> properties; + private LinkedHashMap<String, Object> parentPolicies; + private LinkedHashMap<String, Object> metaData; + private ArrayList<String> targetsList; + + + public PolicyType(String type, LinkedHashMap<String, Object> customDef) { + super(type, POLICY_PREFIX, customDef); + + this.type = type; + this.customDef = customDef; + validateKeys(); + metaData = null; - if(defs != null && defs.get(METADATA) != null) { - metaData = (LinkedHashMap<String,Object>)defs.get(METADATA); - _validateMetadata(metaData); + if (defs != null && defs.get(METADATA) != null) { + metaData = (LinkedHashMap<String, Object>) defs.get(METADATA); + validateMetadata(metaData); } properties = null; - if(defs != null && defs.get(PROPERTIES) != null) { - properties = (LinkedHashMap<String,Object>)defs.get(PROPERTIES); + if (defs != null && defs.get(PROPERTIES) != null) { + properties = (LinkedHashMap<String, Object>) defs.get(PROPERTIES); } - parentPolicies = _getParentPolicies(); + parentPolicies = getParentPolicies(); policyVersion = null; - if(defs != null && defs.get(VERSION) != null) { + if (defs != null && defs.get(VERSION) != null) { policyVersion = (new TOSCAVersionProperty( - defs.get(VERSION))).getVersion(); + defs.get(VERSION).toString())).getVersion(); } policyDescription = null; - if(defs != null && defs.get(DESCRIPTION) != null) { - policyDescription = (String)defs.get(DESCRIPTION); + if (defs != null && defs.get(DESCRIPTION) != null) { + policyDescription = (String) defs.get(DESCRIPTION); } - + targetsList = null; - if(defs != null && defs.get(TARGETS) != null) { - targetsList = (ArrayList<String>)defs.get(TARGETS); - _validateTargets(targetsList,customDef); + if (defs != null && defs.get(TARGETS) != null) { + targetsList = (ArrayList<String>) defs.get(TARGETS); + validateTargets(targetsList, this.customDef); + } + + } + + private LinkedHashMap<String, Object> getParentPolicies() { + LinkedHashMap<String, Object> policies = new LinkedHashMap<>(); + String parentPolicy; + if (getParentType() != null) { + parentPolicy = getParentType().getType(); + } else { + parentPolicy = null; } - - } - - private LinkedHashMap<String,Object> _getParentPolicies() { - LinkedHashMap<String,Object> policies = new LinkedHashMap<>(); - String parentPolicy; - if(getParentType() != null) { - parentPolicy = getParentType().getType(); - } - else { - parentPolicy = null; - } - if(parentPolicy != null) { - while(parentPolicy != null && !parentPolicy.equals("tosca.policies.Root")) { - policies.put(parentPolicy, TOSCA_DEF.get(parentPolicy)); - parentPolicy = (String) - ((LinkedHashMap<String,Object>)policies.get(parentPolicy)).get("derived_from);"); - } - } - return policies; - } - - public String getType() { - return type; - } - - public PolicyType getParentType() { + if (parentPolicy != null) { + while (parentPolicy != null && !parentPolicy.equals("tosca.policies.Root")) { + policies.put(parentPolicy, TOSCA_DEF.get(parentPolicy)); + parentPolicy = (String) + ((LinkedHashMap<String, Object>) policies.get(parentPolicy)).get("derived_from);"); + } + } + return policies; + } + + public String getType() { + return type; + } + + public PolicyType getParentType() { // Return a policy statefulentity of this node is derived from - if(defs == null) { - return null; - } - String ppolicyEntity = derivedFrom(defs); - if(ppolicyEntity != null) { - return new PolicyType(ppolicyEntity,customDef); + if (defs == null) { + return null; + } + String policyEntity = derivedFrom(defs); + if (policyEntity != null) { + return new PolicyType(policyEntity, customDef); } return null; - } - - public Object getPolicy(String name) { + } + + public Object getPolicy(String name) { // Return the definition of a policy field by name - if(defs != null && defs.get(name) != null) { + if (defs != null && defs.get(name) != null) { return defs.get(name); } return null; - } + } - public ArrayList<String> getTargets() { + public ArrayList<String> getTargets() { // Return targets return targetsList; - } - - public String getDescription() { - return policyDescription; - } - - public Object getVersion() { - return policyVersion; - } - - private void _validateKeys() { - for(String key: defs.keySet()) { - boolean bFound = false; - for(String sect: SECTIONS) { - if(key.equals(sect)) { - bFound = true; - break; - } - } - if(!bFound) { + } + + public String getDescription() { + return policyDescription; + } + + public Object getVersion() { + return policyVersion; + } + + private void validateKeys() { + for (String key : defs.keySet()) { + boolean bFound = false; + for (String sect : SECTIONS) { + if (key.equals(sect)) { + bFound = true; + break; + } + } + if (!bFound) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE125", String.format( - "UnknownFieldError: Policy \"%s\" contains unknown field \"%s\"", - type,key))); - } - } - } - - private void _validateTargets(ArrayList<String> _targetsList, - LinkedHashMap<String,Object> _customDef) { - for(String nodetype: _targetsList) { - if(_customDef.get(nodetype) == null) { + "UnknownFieldError: Policy \"%s\" contains unknown field \"%s\"", + type, key))); + } + } + } + + private void validateTargets(ArrayList<String> targetsList, + LinkedHashMap<String, Object> customDef) { + for (String nodetype : targetsList) { + if (customDef.get(nodetype) == null) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE126", String.format( - "InvalidTypeError: \"%s\" defined in targets for policy \"%s\"", - nodetype,type))); - - } - } - } - - private void _validateMetadata(LinkedHashMap<String,Object> _metaData) { - String mtype = (String)_metaData.get("type"); - if(mtype != null && !mtype.equals("map") && !mtype.equals("tosca:map")) { + "InvalidTypeError: \"%s\" defined in targets for policy \"%s\"", + nodetype, type))); + + } + } + } + + private void validateMetadata(LinkedHashMap<String, Object> metaData) { + String mtype = (String) metaData.get("type"); + if (mtype != null && !mtype.equals("map") && !mtype.equals("tosca:map")) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE127", String.format( - "InvalidTypeError: \"%s\" defined in policy for metadata", - mtype))); - } - for(String entrySchema: metaData.keySet()) { - Object estob = metaData.get(entrySchema); - if(estob instanceof LinkedHashMap) { - String est = (String) - ((LinkedHashMap<String,Object>)estob).get("type"); - if(!est.equals("string")) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE128", String.format( - "InvalidTypeError: \"%s\" defined in policy for metadata \"%s\"", - est,entrySchema))); - } - } - } - } + "InvalidTypeError: \"%s\" defined in policy for metadata", + mtype))); + } + for (String entrySchema : this.metaData.keySet()) { + Object estob = this.metaData.get(entrySchema); + if (estob instanceof LinkedHashMap) { + String est = (String) + ((LinkedHashMap<String, Object>) estob).get("type"); + if (!est.equals("string")) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE128", String.format( + "InvalidTypeError: \"%s\" defined in policy for metadata \"%s\"", + est, entrySchema))); + } + } + } + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/PortSpec.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/PortSpec.java index 65304dd..01fb9fc 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/PortSpec.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/PortSpec.java @@ -7,9 +7,9 @@ * 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. @@ -38,16 +38,16 @@ public class PortSpec { private static final String SOURCE_RANGE = "source_range"; private static final String TARGET = "target"; private static final String TARGET_RANGE = "target_range"; - + private static final String PROPERTY_NAMES[] = { - PROTOCOL, SOURCE, SOURCE_RANGE, - TARGET, TARGET_RANGE + PROTOCOL, SOURCE, SOURCE_RANGE, + TARGET, TARGET_RANGE }; - + // todo(TBD) May want to make this a subclass of DataType // and change init method to set PortSpec's properties public PortSpec() { - + } // The following additional requirements MUST be tested: @@ -59,47 +59,44 @@ public class PortSpec { // 3) A valid PortSpec MUST have a value for the target property that is // within the numeric range specified by the property target_range // when target_range is specified. - public static void validateAdditionalReq(Object _properties, - String propName, - LinkedHashMap<String,Object> custom_def) { - + public static void validateAdditionalReq(Object _properties, + String propName, + LinkedHashMap<String, Object> custom_def) { + try { - LinkedHashMap<String,Object> properties = (LinkedHashMap<String,Object>)_properties; + LinkedHashMap<String, Object> properties = (LinkedHashMap<String, Object>) _properties; Object source = properties.get(PortSpec.SOURCE); Object sourceRange = properties.get(PortSpec.SOURCE_RANGE); Object target = properties.get(PortSpec.TARGET); Object targetRange = properties.get(PortSpec.TARGET_RANGE); // verify one of the specified values is set - if(source == null && sourceRange == null && - target == null && targetRange == null) { + if (source == null && sourceRange == null && + target == null && targetRange == null) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE129", String.format( - "InvalidTypeAdditionalRequirementsError: Additional requirements for type \"%s\" not met", - TYPE_URI))); + "InvalidTypeAdditionalRequirementsError: Additional requirements for type \"%s\" not met", + TYPE_URI))); } // Validate source value is in specified range - if(source != null && sourceRange != null) { - ValidateUtils.validateValueInRange(source,sourceRange,SOURCE); - } - else { + if (source != null && sourceRange != null) { + ValidateUtils.validateValueInRange(source, sourceRange, SOURCE); + } else { DataEntity portdef = new DataEntity("PortDef", source, null, SOURCE); portdef.validate(); } // Validate target value is in specified range - if(target != null && targetRange != null) { - ValidateUtils.validateValueInRange(target,targetRange,SOURCE); - } - else { + if (target != null && targetRange != null) { + ValidateUtils.validateValueInRange(target, targetRange, SOURCE); + } else { DataEntity portdef = new DataEntity("PortDef", source, null, TARGET); portdef.validate(); } - } - catch(Exception e) { + } catch (Exception e) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE130", String.format( - "ValueError: \"%s\" do not meet requirements for type \"%s\"", - _properties.toString(),SHORTNAME))); + "ValueError: \"%s\" do not meet requirements for type \"%s\"", + _properties.toString(), SHORTNAME))); } - } + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/PropertyDef.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/PropertyDef.java index 6e1fe61..484d17e 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/PropertyDef.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/PropertyDef.java @@ -7,9 +7,9 @@ * 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. @@ -27,12 +27,12 @@ import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; public class PropertyDef { - - private static final String PROPERTY_KEYNAME_DEFAULT = "default"; - private static final String PROPERTY_KEYNAME_REQUIRED = "required"; - private static final String PROPERTY_KEYNAME_STATUS = "status"; - private static final String VALID_PROPERTY_KEYNAMES[] = { - PROPERTY_KEYNAME_DEFAULT, + + private static final String PROPERTY_KEYNAME_DEFAULT = "default"; + private static final String PROPERTY_KEYNAME_REQUIRED = "required"; + private static final String PROPERTY_KEYNAME_STATUS = "status"; + private static final String VALID_PROPERTY_KEYNAMES[] = { + PROPERTY_KEYNAME_DEFAULT, PROPERTY_KEYNAME_REQUIRED, PROPERTY_KEYNAME_STATUS}; @@ -41,122 +41,120 @@ public class PropertyDef { private static final String VALID_REQUIRED_VALUES[] = {"true", "false"}; private static final String PROPERTY_STATUS_SUPPORTED = "supported"; - private static final String PROPERTY_STATUS_EXPERIMENTAL = "experimental"; - private static final String VALID_STATUS_VALUES[] = { - PROPERTY_STATUS_SUPPORTED, PROPERTY_STATUS_EXPERIMENTAL}; - - private static final String PROPERTY_STATUS_DEFAULT = PROPERTY_STATUS_SUPPORTED; - - private String name; - private Object value; - private LinkedHashMap<String,Object> schema; - private String _status; - private boolean _required; - - public PropertyDef(String pdName, Object pdValue, - LinkedHashMap<String,Object> pdSchema) { - name = pdName; - value = pdValue; - schema = pdSchema; + private static final String PROPERTY_STATUS_EXPERIMENTAL = "experimental"; + private static final String VALID_STATUS_VALUES[] = { + PROPERTY_STATUS_SUPPORTED, PROPERTY_STATUS_EXPERIMENTAL}; + + private static final String PROPERTY_STATUS_DEFAULT = PROPERTY_STATUS_SUPPORTED; + + private String name; + private Object value; + private LinkedHashMap<String, Object> schema; + private String _status; + private boolean _required; + + public PropertyDef(String pdName, Object pdValue, + LinkedHashMap<String, Object> pdSchema) { + name = pdName; + value = pdValue; + schema = pdSchema; _status = PROPERTY_STATUS_DEFAULT; _required = PROPERTY_REQUIRED_DEFAULT; - if(schema != null) { - // Validate required 'type' property exists - if(schema.get("type") == null) { - //msg = (_('Schema definition of "%(pname)s" must have a "type" ' - // 'attribute.') % dict(pname=self.name)) - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE131", String.format( - "InvalidSchemaError: Schema definition of \"%s\" must have a \"type\" attribute",name))); - } - _loadRequiredAttrFromSchema(); - _loadStatusAttrFromSchema(); + if (schema != null) { + // Validate required 'type' property exists + if (schema.get("type") == null) { + //msg = (_('Schema definition of "%(pname)s" must have a "type" ' + // 'attribute.') % dict(pname=self.name)) + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE131", String.format( + "InvalidSchemaError: Schema definition of \"%s\" must have a \"type\" attribute", name))); + } + _loadRequiredAttrFromSchema(); + _loadStatusAttrFromSchema(); + } + } + + public Object getDefault() { + if (schema != null) { + for (Map.Entry<String, Object> me : schema.entrySet()) { + if (me.getKey().equals(PROPERTY_KEYNAME_DEFAULT)) { + return me.getValue(); + } + } } - } - - public Object getDefault() { - if(schema != null) { - for(Map.Entry<String,Object> me: schema.entrySet()) { - if(me.getKey().equals(PROPERTY_KEYNAME_DEFAULT)) { - return me.getValue(); - } - } - } - return null; - } - - public boolean isRequired() { - return _required; - } - - private void _loadRequiredAttrFromSchema() { + return null; + } + + public boolean isRequired() { + return _required; + } + + private void _loadRequiredAttrFromSchema() { // IF 'required' keyname exists verify it's a boolean, // if so override default - Object val = schema.get(PROPERTY_KEYNAME_REQUIRED); - if(val != null) { - if(val instanceof Boolean) { - _required = (boolean)val; - } - else { + Object val = schema.get(PROPERTY_KEYNAME_REQUIRED); + if (val != null) { + if (val instanceof Boolean) { + _required = (boolean) val; + } else { //valid_values = ', '.join(self.VALID_REQUIRED_VALUES) //attr = self.PROPERTY_KEYNAME_REQUIRED //TOSCAException.generate_inv_schema_property_error(self, // attr, // value, // valid_values) - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE132", String.format( - "Schema definition of \"%s\" has \"required\" attribute with an invalid value", - name))); - } - } - } - - public String getStatus() { - return _status; - } - - private void _loadStatusAttrFromSchema() { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE132", String.format( + "Schema definition of \"%s\" has \"required\" attribute with an invalid value", + name))); + } + } + } + + public String getStatus() { + return _status; + } + + private void _loadStatusAttrFromSchema() { // IF 'status' keyname exists verify it's a boolean, // if so override default - String sts = (String)schema.get(PROPERTY_KEYNAME_STATUS); - if(sts != null) { - boolean bFound = false; - for(String vsv: VALID_STATUS_VALUES) { - if(vsv.equals(sts)) { - bFound = true; - break; - } - } - if(bFound) { - _status = sts; - } - else { + String sts = (String) schema.get(PROPERTY_KEYNAME_STATUS); + if (sts != null) { + boolean bFound = false; + for (String vsv : VALID_STATUS_VALUES) { + if (vsv.equals(sts)) { + bFound = true; + break; + } + } + if (bFound) { + _status = sts; + } else { //valid_values = ', '.join(self.VALID_STATUS_VALUES) //attr = self.PROPERTY_KEYNAME_STATUS //TOSCAException.generate_inv_schema_property_error(self, // attr, // value, // valid_values) - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE006", String.format( - "Schema definition of \"%s\" has \"status\" attribute with an invalid value", - name))); - } - } - } - - public String getName() { - return name; - } - - public LinkedHashMap<String,Object> getSchema() { - return schema; - } - - public Object getPDValue() { - // there's getValue in EntityType... - return value; - } - + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE006", String.format( + "Schema definition of \"%s\" has \"status\" attribute with an invalid value", + name))); + } + } + } + + public String getName() { + return name; + } + + public LinkedHashMap<String, Object> getSchema() { + return schema; + } + + public Object getPDValue() { + // there's getValue in EntityType... + return value; + } + } /*python diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/RelationshipType.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/RelationshipType.java index 17f420d..4c39ec2 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/RelationshipType.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/RelationshipType.java @@ -7,9 +7,9 @@ * 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. @@ -27,56 +27,56 @@ import java.util.LinkedHashMap; public class RelationshipType extends StatefulEntityType { - private static final String DERIVED_FROM = "derived_from"; - private static final String VALID_TARGET_TYPES = "valid_target_types"; - private static final String INTERFACES = "interfaces"; - private static final String ATTRIBUTES = "attributes"; - private static final String PROPERTIES = "properties"; - private static final String DESCRIPTION = "description"; - private static final String VERSION = "version"; - private static final String CREDENTIAL = "credential"; - - private static final String SECTIONS[] = { - DERIVED_FROM, VALID_TARGET_TYPES, INTERFACES, - ATTRIBUTES, PROPERTIES, DESCRIPTION, VERSION, CREDENTIAL}; - - private String capabilityName; - private LinkedHashMap<String,Object> customDef; - - public RelationshipType(String _type, String _capabilityName, LinkedHashMap<String,Object> _customDef) { - super(_type,RELATIONSHIP_PREFIX,_customDef); - capabilityName = _capabilityName; - customDef = _customDef; - } - - public RelationshipType getParentType() { + private static final String DERIVED_FROM = "derived_from"; + private static final String VALID_TARGET_TYPES = "valid_target_types"; + private static final String INTERFACES = "interfaces"; + private static final String ATTRIBUTES = "attributes"; + private static final String PROPERTIES = "properties"; + private static final String DESCRIPTION = "description"; + private static final String VERSION = "version"; + private static final String CREDENTIAL = "credential"; + + private static final String[] SECTIONS = { + DERIVED_FROM, VALID_TARGET_TYPES, INTERFACES, + ATTRIBUTES, PROPERTIES, DESCRIPTION, VERSION, CREDENTIAL}; + + private String capabilityName; + private LinkedHashMap<String, Object> customDef; + + public RelationshipType(String type, String capabilityName, LinkedHashMap<String, Object> customDef) { + super(type, RELATIONSHIP_PREFIX, customDef); + this.capabilityName = capabilityName; + this.customDef = customDef; + } + + public RelationshipType getParentType() { // Return a relationship this reletionship is derived from.''' String prel = derivedFrom(defs); - if(prel != null) { - return new RelationshipType(prel,null,customDef); + if (prel != null) { + return new RelationshipType(prel, null, customDef); } return null; - } - - public Object getValidTargetTypes() { - return entityValue(defs,"valid_target_types"); - } - - private void _validateKeys() { - for(String key: defs.keySet()) { - boolean bFound = false; - for(int i=0; i< SECTIONS.length; i++) { - if(key.equals(SECTIONS[i])) { - bFound = true; - break; - } - } - if(!bFound) { + } + + public Object getValidTargetTypes() { + return entityValue(defs, "valid_target_types"); + } + + private void validateKeys() { + for (String key : defs.keySet()) { + boolean bFound = false; + for (String section : SECTIONS) { + if (key.equals(section)) { + bFound = true; + break; + } + } + if (!bFound) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE133", String.format( - "UnknownFieldError: Relationshiptype \"%s\" has unknown field \"%s\"",type,key))); - } + "UnknownFieldError: Relationshiptype \"%s\" has unknown field \"%s\"", type, key))); + } } - } + } } /*python diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnit.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnit.java index eeaa07c..1eaa8a0 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnit.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnit.java @@ -7,9 +7,9 @@ * 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. @@ -20,147 +20,152 @@ package org.onap.sdc.toscaparser.api.elements; -import java.util.HashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; import org.onap.sdc.toscaparser.api.utils.ValidateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.HashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public abstract class ScalarUnit { - private static Logger log = LoggerFactory.getLogger(ScalarUnit.class.getName()); + private static Logger log = LoggerFactory.getLogger(ScalarUnit.class.getName()); + + private static final String SCALAR_UNIT_SIZE = "scalar-unit.size"; + private static final String SCALAR_UNIT_FREQUENCY = "scalar-unit.frequency"; + private static final String SCALAR_UNIT_TIME = "scalar-unit.time"; - private static final String SCALAR_UNIT_SIZE = "scalar-unit.size"; - private static final String SCALAR_UNIT_FREQUENCY = "scalar-unit.frequency"; - private static final String SCALAR_UNIT_TIME = "scalar-unit.time"; - - public static final String SCALAR_UNIT_TYPES[] = { + public static final String[] SCALAR_UNIT_TYPES = { SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME - }; - - private Object value; - protected HashMap<String,Object> SCALAR_UNIT_DICT; - protected String SCALAR_UNIT_DEFAULT; - - public ScalarUnit(Object _value) { - value = _value; - SCALAR_UNIT_DICT = new HashMap<>(); - SCALAR_UNIT_DEFAULT = ""; - } - - - private String _checkUnitInScalarStandardUnits(String inputUnit) { + }; + + private Object value; + private HashMap<String, Object> scalarUnitDict; + private String scalarUnitDefault; + + public ScalarUnit(Object value) { + this.value = value; + scalarUnitDict = new HashMap<>(); + scalarUnitDefault = ""; + } + + void putToScalarUnitDict(String key, Object value) { + scalarUnitDict.put(key, value); + } + + void setScalarUnitDefault(String scalarUnitDefault) { + this.scalarUnitDefault = scalarUnitDefault; + } + + private String checkUnitInScalarStandardUnits(String inputUnit) { // Check whether the input unit is following specified standard - + // If unit is not following specified standard, convert it to standard // unit after displaying a warning message. - - if(SCALAR_UNIT_DICT.get(inputUnit) != null) { - return inputUnit; - } - else { - for(String key: SCALAR_UNIT_DICT.keySet()) { - if(key.toUpperCase().equals(inputUnit.toUpperCase())) { - log.debug("ScalarUnit - _checkUnitInScalarStandardUnits - \n" + - "The unit {} does not follow scalar unit standards\n" + - "using {} instead", - inputUnit, key); - return key; - } - } - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE007", String.format( - "'The unit \"%s\" is not valid. Valid units are \n%s", - inputUnit,SCALAR_UNIT_DICT.keySet().toString()))); + + if (scalarUnitDict.get(inputUnit) != null) { + return inputUnit; + } else { + for (String key : scalarUnitDict.keySet()) { + if (key.toUpperCase().equals(inputUnit.toUpperCase())) { + log.debug("ScalarUnit - checkUnitInScalarStandardUnits - \n" + + "The unit {} does not follow scalar unit standards\n" + + "using {} instead", + inputUnit, key); + return key; + } + } + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE007", String.format( + "'The unit \"%s\" is not valid. Valid units are \n%s", + inputUnit, scalarUnitDict.keySet().toString()))); return inputUnit; - } - } - - public Object validateScalarUnit() { - Pattern pattern = Pattern.compile("([0-9.]+)\\s*(\\w+)"); - Matcher matcher = pattern.matcher(value.toString()); - if(matcher.find()) { - ValidateUtils.strToNum(matcher.group(1)); - String scalarUnit = _checkUnitInScalarStandardUnits(matcher.group(2)); - value = matcher.group(1) + " " + scalarUnit; - } - else { + } + } + + public Object validateScalarUnit() { + Pattern pattern = Pattern.compile("([0-9.]+)\\s*(\\w+)"); + Matcher matcher = pattern.matcher(value.toString()); + if (matcher.find()) { + ValidateUtils.strToNum(matcher.group(1)); + String scalarUnit = checkUnitInScalarStandardUnits(matcher.group(2)); + value = matcher.group(1) + " " + scalarUnit; + } else { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE134", String.format( - "ValueError: \"%s\" is not a valid scalar-unit",value.toString()))); - } - return value; - } - - public double getNumFromScalarUnit(String unit) { - if(unit != null) { - unit = _checkUnitInScalarStandardUnits(unit); - } - else { - unit = SCALAR_UNIT_DEFAULT; - } - Pattern pattern = Pattern.compile("([0-9.]+)\\s*(\\w+)"); - Matcher matcher = pattern.matcher(value.toString()); - if(matcher.find()) { - ValidateUtils.strToNum(matcher.group(1)); - String scalarUnit = _checkUnitInScalarStandardUnits(matcher.group(2)); - value = matcher.group(1) + " " + scalarUnit; - Object on1 = ValidateUtils.strToNum(matcher.group(1)) != null ? ValidateUtils.strToNum(matcher.group(1)) : 0; - Object on2 = SCALAR_UNIT_DICT.get(matcher.group(2)) != null ? SCALAR_UNIT_DICT.get(matcher.group(2)) : 0; - Object on3 = SCALAR_UNIT_DICT.get(unit) != null ? SCALAR_UNIT_DICT.get(unit) : 0; - - Double n1 = new Double(on1.toString()); - Double n2 = new Double(on2.toString()); - Double n3 = new Double(on3.toString()); - double converted = n1 * n2 / n3; - if(Math.abs(converted - Math.round(converted)) < 0.0000000000001 ) { - converted = Math.round(converted); - } - return converted; - } - return 0l; //??? - } - - protected static HashMap<String,String> scalarunitMapping = _getScalarunitMappings(); - - private static HashMap<String,String> _getScalarunitMappings() { - HashMap<String,String> map = new HashMap<>(); - map.put(SCALAR_UNIT_FREQUENCY,"ScalarUnitFrequency"); - map.put(SCALAR_UNIT_SIZE, "ScalarUnitSize"); - map.put(SCALAR_UNIT_TIME, "ScalarUnit_Time"); - return map; - } - - public static ScalarUnit getScalarunitClass(String type,Object val) { - if(type.equals(SCALAR_UNIT_SIZE)) { - return new ScalarUnitSize(val); - } - else if(type.equals(SCALAR_UNIT_TIME)) { - return new ScalarUnitTime(val); - } - else if(type.equals(SCALAR_UNIT_FREQUENCY)) { - return new ScalarUnitFrequency(val); - } - return null; - } - - public static double getScalarunitValue(String type, Object value, String unit) { - if(type.equals(SCALAR_UNIT_SIZE)) { - return (new ScalarUnitSize(value)).getNumFromScalarUnit(unit); - } - if(type.equals(SCALAR_UNIT_TIME)) { - return (new ScalarUnitTime(value)).getNumFromScalarUnit(unit); - } - if(type.equals(SCALAR_UNIT_FREQUENCY)) { - return (new ScalarUnitFrequency(value)).getNumFromScalarUnit(unit); - } + "ValueError: \"%s\" is not a valid scalar-unit", value.toString()))); + } + return value; + } + + public double getNumFromScalarUnit(String unit) { + if (unit != null) { + unit = checkUnitInScalarStandardUnits(unit); + } else { + unit = scalarUnitDefault; + } + Pattern pattern = Pattern.compile("([0-9.]+)\\s*(\\w+)"); + Matcher matcher = pattern.matcher(value.toString()); + if (matcher.find()) { + final double minimalNum = 0.0000000000001; + + ValidateUtils.strToNum(matcher.group(1)); + String scalarUnit = checkUnitInScalarStandardUnits(matcher.group(2)); + value = matcher.group(1) + " " + scalarUnit; + Object on1 = ValidateUtils.strToNum(matcher.group(1)) != null ? ValidateUtils.strToNum(matcher.group(1)) : 0; + Object on2 = scalarUnitDict.get(matcher.group(2)) != null ? scalarUnitDict.get(matcher.group(2)) : 0; + Object on3 = scalarUnitDict.get(unit) != null ? scalarUnitDict.get(unit) : 0; + + Double n1 = new Double(on1.toString()); + Double n2 = new Double(on2.toString()); + Double n3 = new Double(on3.toString()); + double converted = n1 * n2 / n3; + + if (Math.abs(converted - Math.round(converted)) < minimalNum) { + converted = Math.round(converted); + } + return converted; + } + return 0.0; + } + + private static HashMap<String, String> scalarUnitMapping = getScalarUnitMappings(); + + private static HashMap<String, String> getScalarUnitMappings() { + HashMap<String, String> map = new HashMap<>(); + map.put(SCALAR_UNIT_FREQUENCY, "ScalarUnitFrequency"); + map.put(SCALAR_UNIT_SIZE, "ScalarUnitSize"); + map.put(SCALAR_UNIT_TIME, "ScalarUnit_Time"); + return map; + } + + public static ScalarUnit getScalarunitClass(String type, Object val) { + if (type.equals(SCALAR_UNIT_SIZE)) { + return new ScalarUnitSize(val); + } else if (type.equals(SCALAR_UNIT_TIME)) { + return new ScalarUnitTime(val); + } else if (type.equals(SCALAR_UNIT_FREQUENCY)) { + return new ScalarUnitFrequency(val); + } + return null; + } + + public static double getScalarunitValue(String type, Object value, String unit) { + if (type.equals(SCALAR_UNIT_SIZE)) { + return (new ScalarUnitSize(value)).getNumFromScalarUnit(unit); + } + if (type.equals(SCALAR_UNIT_TIME)) { + return (new ScalarUnitTime(value)).getNumFromScalarUnit(unit); + } + if (type.equals(SCALAR_UNIT_FREQUENCY)) { + return (new ScalarUnitFrequency(value)).getNumFromScalarUnit(unit); + } ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE135", String.format( - "TypeError: \"%s\" is not a valid scalar-unit type",type))); + "TypeError: \"%s\" is not a valid scalar-unit type", type))); return 0.0; - } - + } + } /*python @@ -190,10 +195,10 @@ class ScalarUnit(object): If unit is not following specified standard, convert it to standard unit after displaying a warning message. """ - if input_unit in self.SCALAR_UNIT_DICT.keys(): + if input_unit in self.scalarUnitDict.keys(): return input_unit else: - for key in self.SCALAR_UNIT_DICT.keys(): + for key in self.scalarUnitDict.keys(): if key.upper() == input_unit.upper(): log.warning(_('The unit "%(unit)s" does not follow ' 'scalar unit standards; using "%(key)s" ' @@ -203,7 +208,7 @@ class ScalarUnit(object): msg = (_('The unit "%(unit)s" is not valid. Valid units are ' '"%(valid_units)s".') % {'unit': input_unit, - 'valid_units': sorted(self.SCALAR_UNIT_DICT.keys())}) + 'valid_units': sorted(self.scalarUnitDict.keys())}) ValidationIssueCollector.appendException(ValueError(msg)) def validate_scalar_unit(self): @@ -224,14 +229,14 @@ class ScalarUnit(object): if unit: unit = self._check_unit_in_scalar_standard_units(unit) else: - unit = self.SCALAR_UNIT_DEFAULT + unit = self.scalarUnitDefault self.validate_scalar_unit() regex = re.compile('([0-9.]+)\s*(\w+)') result = regex.match(str(self.value)).groups() converted = (float(validateutils.str_to_num(result[0])) - * self.SCALAR_UNIT_DICT[result[1]] - / self.SCALAR_UNIT_DICT[unit]) + * self.scalarUnitDict[result[1]] + / self.scalarUnitDict[unit]) if converted - int(converted) < 0.0000000000001: converted = int(converted) return converted @@ -239,8 +244,8 @@ class ScalarUnit(object): class ScalarUnit_Size(ScalarUnit): - SCALAR_UNIT_DEFAULT = 'B' - SCALAR_UNIT_DICT = {'B': 1, 'kB': 1000, 'KiB': 1024, 'MB': 1000000, + scalarUnitDefault = 'B' + scalarUnitDict = {'B': 1, 'kB': 1000, 'KiB': 1024, 'MB': 1000000, 'MiB': 1048576, 'GB': 1000000000, 'GiB': 1073741824, 'TB': 1000000000000, 'TiB': 1099511627776} @@ -248,15 +253,15 @@ class ScalarUnit_Size(ScalarUnit): class ScalarUnit_Time(ScalarUnit): - SCALAR_UNIT_DEFAULT = 'ms' - SCALAR_UNIT_DICT = {'d': 86400, 'h': 3600, 'm': 60, 's': 1, + scalarUnitDefault = 'ms' + scalarUnitDict = {'d': 86400, 'h': 3600, 'm': 60, 's': 1, 'ms': 0.001, 'us': 0.000001, 'ns': 0.000000001} class ScalarUnit_Frequency(ScalarUnit): - SCALAR_UNIT_DEFAULT = 'GHz' - SCALAR_UNIT_DICT = {'Hz': 1, 'kHz': 1000, + scalarUnitDefault = 'GHz' + scalarUnitDict = {'Hz': 1, 'kHz': 1000, 'MHz': 1000000, 'GHz': 1000000000} diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitFrequency.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitFrequency.java index 59664ca..ed10da9 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitFrequency.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitFrequency.java @@ -7,9 +7,9 @@ * 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. @@ -22,13 +22,18 @@ package org.onap.sdc.toscaparser.api.elements; public class ScalarUnitFrequency extends ScalarUnit { - public ScalarUnitFrequency(Object value) { - super(value); - SCALAR_UNIT_DEFAULT = "GHz"; - SCALAR_UNIT_DICT.put("Hz",1L); - SCALAR_UNIT_DICT.put("kHz",1000L); - SCALAR_UNIT_DICT.put("MHz",1000000L); - SCALAR_UNIT_DICT.put("GHz",1000000000L); - } + private static final Long HZ = 1L; + private static final Long KHZ = 1000L; + private static final Long MHZ = 1000000L; + private static final Long GHZ = 1000000000L; + + public ScalarUnitFrequency(Object value) { + super(value); + setScalarUnitDefault("GHz"); + putToScalarUnitDict("Hz", HZ); + putToScalarUnitDict("kHz", KHZ); + putToScalarUnitDict("MHz", MHZ); + putToScalarUnitDict("GHz", GHZ); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitSize.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitSize.java index d29d8a2..78687a1 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitSize.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitSize.java @@ -7,9 +7,9 @@ * 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. @@ -20,20 +20,24 @@ package org.onap.sdc.toscaparser.api.elements; +import org.onap.sdc.toscaparser.api.elements.enums.FileSize; + public class ScalarUnitSize extends ScalarUnit { - public ScalarUnitSize(Object value) { - super(value); - - SCALAR_UNIT_DEFAULT = "B"; - SCALAR_UNIT_DICT.put("B",1L); - SCALAR_UNIT_DICT.put("kB",1000L); - SCALAR_UNIT_DICT.put("kiB",1024L); - SCALAR_UNIT_DICT.put("MB",1000000L); - SCALAR_UNIT_DICT.put("MiB",1048576L); - SCALAR_UNIT_DICT.put("GB",1000000000L); - SCALAR_UNIT_DICT.put("GiB",1073741824L); - SCALAR_UNIT_DICT.put("TB",1000000000000L); - SCALAR_UNIT_DICT.put("TiB",1099511627776L); - } + + + public ScalarUnitSize(Object value) { + super(value); + + setScalarUnitDefault("B"); + putToScalarUnitDict("B", FileSize.B); + putToScalarUnitDict("kB", FileSize.KB); + putToScalarUnitDict("MB", FileSize.MB); + putToScalarUnitDict("GB", FileSize.GB); + putToScalarUnitDict("TB", FileSize.TB); + putToScalarUnitDict("kiB", FileSize.KIB); + putToScalarUnitDict("MiB", FileSize.MIB); + putToScalarUnitDict("GiB", FileSize.GIB); + putToScalarUnitDict("TiB", FileSize.TIB); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitTime.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitTime.java index 45848af..8d2c13e 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitTime.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/ScalarUnitTime.java @@ -7,9 +7,9 @@ * 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. @@ -22,16 +22,16 @@ package org.onap.sdc.toscaparser.api.elements; public class ScalarUnitTime extends ScalarUnit { - public ScalarUnitTime(Object value) { - super(value); - SCALAR_UNIT_DEFAULT = "ms"; - SCALAR_UNIT_DICT.put("d",86400L); - SCALAR_UNIT_DICT.put("h",3600L); - SCALAR_UNIT_DICT.put("m",60L); - SCALAR_UNIT_DICT.put("s",1L); - SCALAR_UNIT_DICT.put("ms",0.001); - SCALAR_UNIT_DICT.put("us",0.000001); - SCALAR_UNIT_DICT.put("ns",0.000000001); - } + public ScalarUnitTime(Object value) { + super(value); + setScalarUnitDefault("ms"); + putToScalarUnitDict("d", 86400L); + putToScalarUnitDict("h", 3600L); + putToScalarUnitDict("m", 60L); + putToScalarUnitDict("s", 1L); + putToScalarUnitDict("ms", 0.001); + putToScalarUnitDict("us", 0.000001); + putToScalarUnitDict("ns", 0.000000001); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/StatefulEntityType.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/StatefulEntityType.java index ef9159f..b710dda 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/StatefulEntityType.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/StatefulEntityType.java @@ -7,9 +7,9 @@ * 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. @@ -20,140 +20,136 @@ package org.onap.sdc.toscaparser.api.elements; +import org.onap.sdc.toscaparser.api.UnsupportedType; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; +import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; -import org.onap.sdc.toscaparser.api.UnsupportedType; -import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; - public class StatefulEntityType extends EntityType { // Class representing TOSCA states - public static final String interfacesNodeLifecycleOperations[] = { - "create", "configure", "start", "stop", "delete"}; + public static final String[] INTERFACE_NODE_LIFECYCLE_OPERATIONS = { + "create", "configure", "start", "stop", "delete"}; - public static final String interfacesRelationshipConfigureOperations[] = { - "post_configure_source", "post_configure_target", "add_target", "remove_target"}; + public static final String[] INTERFACE_RELATIONSHIP_CONFIGURE_OPERATIONS = { + "post_configure_source", "post_configure_target", "add_target", "remove_target"}; public StatefulEntityType() { - // void constructor for subclasses that don't want super + // void constructor for subclasses that don't want super } - - @SuppressWarnings("unchecked") - public StatefulEntityType(String entityType, String prefix, LinkedHashMap<String,Object> customDef) { + + @SuppressWarnings("unchecked") + public StatefulEntityType(String entityType, String prefix, LinkedHashMap<String, Object> customDef) { String entireEntityType = entityType; - if(UnsupportedType.validateType(entireEntityType)) { + if (UnsupportedType.validateType(entireEntityType)) { defs = null; - } - else { - if(entityType.startsWith(TOSCA + ":")) { - entityType = entityType.substring(TOSCA.length()+1); + } else { + if (entityType.startsWith(TOSCA + ":")) { + entityType = entityType.substring(TOSCA.length() + 1); entireEntityType = prefix + entityType; } - if(!entityType.startsWith(TOSCA)) { + if (!entityType.startsWith(TOSCA)) { entireEntityType = prefix + entityType; } - if(TOSCA_DEF.get(entireEntityType) != null) { - defs = (LinkedHashMap<String,Object> )TOSCA_DEF.get(entireEntityType); + if (TOSCA_DEF.get(entireEntityType) != null) { + defs = (LinkedHashMap<String, Object>) TOSCA_DEF.get(entireEntityType); entityType = entireEntityType; - } - else if(customDef != null && customDef.get(entityType) != null) { - defs = (LinkedHashMap<String,Object> )customDef.get(entityType); - } - else{ + } else if (customDef != null && customDef.get(entityType) != null) { + defs = (LinkedHashMap<String, Object>) customDef.get(entityType); + } else { defs = null; - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE136", String.format( - "InvalidTypeError: \"%s\" is not a valid type",entityType))); + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE136", String.format( + "InvalidTypeError: \"%s\" is not a valid type", entityType))); } } type = entityType; - } - - @SuppressWarnings("unchecked") - public ArrayList<PropertyDef> getPropertiesDefObjects() { - // Return a list of property definition objects - ArrayList<PropertyDef> properties = new ArrayList<PropertyDef>(); - LinkedHashMap<String,Object> props = (LinkedHashMap<String,Object>)getDefinition(PROPERTIES); - if(props != null) { - for(Map.Entry<String,Object> me: props.entrySet()) { - String pdname = me.getKey(); - Object to = me.getValue(); - if(to == null || !(to instanceof LinkedHashMap)) { - String s = to == null ? "null" : to.getClass().getSimpleName(); - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE137", String.format( - "Unexpected type error: property \"%s\" has type \"%s\" (expected dict)",pdname,s))); - continue; - } - LinkedHashMap<String,Object> pdschema = (LinkedHashMap<String,Object>)to; - properties.add(new PropertyDef(pdname,null,pdschema)); - } - } - return properties; - } - - public LinkedHashMap<String,PropertyDef> getPropertiesDef() { - LinkedHashMap<String,PropertyDef> pds = new LinkedHashMap<String,PropertyDef>(); - for(PropertyDef pd: getPropertiesDefObjects()) { - pds.put(pd.getName(),pd); - } - return pds; - } - - public PropertyDef getPropertyDefValue(String name) { - // Return the property definition associated with a given name - PropertyDef pd = null; - LinkedHashMap<String,PropertyDef> propsDef = getPropertiesDef(); - if(propsDef != null) { - pd = propsDef.get(name); - } - return pd; - } - - public ArrayList<AttributeDef> getAttributesDefObjects() { - // Return a list of attribute definition objects - @SuppressWarnings("unchecked") - LinkedHashMap<String,Object> attrs = (LinkedHashMap<String,Object>)getValue(ATTRIBUTES,null,true); - ArrayList<AttributeDef> ads = new ArrayList<>(); - if(attrs != null) { - for(Map.Entry<String,Object> me: attrs.entrySet()) { - String attr = me.getKey(); - @SuppressWarnings("unchecked") - LinkedHashMap<String,Object> adschema = (LinkedHashMap<String,Object>)me.getValue(); - ads.add(new AttributeDef(attr,null,adschema)); - } - } - return ads; - } - - public LinkedHashMap<String,AttributeDef> getAttributesDef() { - // Return a dictionary of attribute definition name-object pairs - - LinkedHashMap<String,AttributeDef> ads = new LinkedHashMap<>(); - for(AttributeDef ado: getAttributesDefObjects()) { - ads.put(((AttributeDef)ado).getName(),ado); - } - return ads; - } - - public AttributeDef getAttributeDefValue(String name) { - // Return the attribute definition associated with a given name - AttributeDef ad = null; - LinkedHashMap<String,AttributeDef> attrsDef = getAttributesDef(); - if(attrsDef != null) { - ad = attrsDef.get(name); - } - return ad; - } - - public String getType() { - return type; - } - } + } + + @SuppressWarnings("unchecked") + public ArrayList<PropertyDef> getPropertiesDefObjects() { + // Return a list of property definition objects + ArrayList<PropertyDef> properties = new ArrayList<PropertyDef>(); + LinkedHashMap<String, Object> props = (LinkedHashMap<String, Object>) getDefinition(PROPERTIES); + if (props != null) { + for (Map.Entry<String, Object> me : props.entrySet()) { + String pdname = me.getKey(); + Object to = me.getValue(); + if (to == null || !(to instanceof LinkedHashMap)) { + String s = to == null ? "null" : to.getClass().getSimpleName(); + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE137", String.format( + "Unexpected type error: property \"%s\" has type \"%s\" (expected dict)", pdname, s))); + continue; + } + LinkedHashMap<String, Object> pdschema = (LinkedHashMap<String, Object>) to; + properties.add(new PropertyDef(pdname, null, pdschema)); + } + } + return properties; + } + + public LinkedHashMap<String, PropertyDef> getPropertiesDef() { + LinkedHashMap<String, PropertyDef> pds = new LinkedHashMap<String, PropertyDef>(); + for (PropertyDef pd : getPropertiesDefObjects()) { + pds.put(pd.getName(), pd); + } + return pds; + } + + public PropertyDef getPropertyDefValue(String name) { + // Return the property definition associated with a given name + PropertyDef pd = null; + LinkedHashMap<String, PropertyDef> propsDef = getPropertiesDef(); + if (propsDef != null) { + pd = propsDef.get(name); + } + return pd; + } + + public ArrayList<AttributeDef> getAttributesDefObjects() { + // Return a list of attribute definition objects + @SuppressWarnings("unchecked") + LinkedHashMap<String, Object> attrs = (LinkedHashMap<String, Object>) getValue(ATTRIBUTES, null, true); + ArrayList<AttributeDef> ads = new ArrayList<>(); + if (attrs != null) { + for (Map.Entry<String, Object> me : attrs.entrySet()) { + String attr = me.getKey(); + @SuppressWarnings("unchecked") + LinkedHashMap<String, Object> adschema = (LinkedHashMap<String, Object>) me.getValue(); + ads.add(new AttributeDef(attr, null, adschema)); + } + } + return ads; + } + + public LinkedHashMap<String, AttributeDef> getAttributesDef() { + // Return a dictionary of attribute definition name-object pairs + + LinkedHashMap<String, AttributeDef> ads = new LinkedHashMap<>(); + for (AttributeDef ado : getAttributesDefObjects()) { + ads.put(((AttributeDef) ado).getName(), ado); + } + return ads; + } + + public AttributeDef getAttributeDefValue(String name) { + // Return the attribute definition associated with a given name + AttributeDef ad = null; + LinkedHashMap<String, AttributeDef> attrsDef = getAttributesDef(); + if (attrsDef != null) { + ad = attrsDef.get(name); + } + return ad; + } + + public String getType() { + return type; + } +} /*python diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/TypeValidation.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/TypeValidation.java index 9321064..18dd5ca 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/TypeValidation.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/TypeValidation.java @@ -7,9 +7,9 @@ * 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. @@ -30,25 +30,25 @@ import org.onap.sdc.toscaparser.api.extensions.ExtTools; public class TypeValidation { - private static final String DEFINITION_VERSION = "tosca_definitions_version"; - private static final String DESCRIPTION = "description"; - private static final String IMPORTS = "imports"; - private static final String DSL_DEFINITIONS = "dsl_definitions"; - private static final String NODE_TYPES = "node_types"; - private static final String REPOSITORIES = "repositories"; - private static final String DATA_TYPES = "data_types"; - private static final String ARTIFACT_TYPES = "artifact_types"; - private static final String GROUP_TYPES = "group_types"; - private static final String RELATIONSHIP_TYPES = "relationship_types"; - private static final String CAPABILITY_TYPES = "capability_types"; - private static final String INTERFACE_TYPES = "interface_types"; - private static final String POLICY_TYPES = "policy_types"; - private static final String TOPOLOGY_TEMPLATE = "topology_template"; - //Pavel - private static final String METADATA = "metadata"; - - private String ALLOWED_TYPE_SECTIONS[] = { - DEFINITION_VERSION, DESCRIPTION, IMPORTS, + private static final String DEFINITION_VERSION = "tosca_definitions_version"; + private static final String DESCRIPTION = "description"; + private static final String IMPORTS = "imports"; + private static final String DSL_DEFINITIONS = "dsl_definitions"; + private static final String NODE_TYPES = "node_types"; + private static final String REPOSITORIES = "repositories"; + private static final String DATA_TYPES = "data_types"; + private static final String ARTIFACT_TYPES = "artifact_types"; + private static final String GROUP_TYPES = "group_types"; + private static final String RELATIONSHIP_TYPES = "relationship_types"; + private static final String CAPABILITY_TYPES = "capability_types"; + private static final String INTERFACE_TYPES = "interface_types"; + private static final String POLICY_TYPES = "policy_types"; + private static final String TOPOLOGY_TEMPLATE = "topology_template"; + //Pavel + private static final String METADATA = "metadata"; + + private String ALLOWED_TYPE_SECTIONS[] = { + DEFINITION_VERSION, DESCRIPTION, IMPORTS, DSL_DEFINITIONS, NODE_TYPES, REPOSITORIES, DATA_TYPES, ARTIFACT_TYPES, GROUP_TYPES, RELATIONSHIP_TYPES, CAPABILITY_TYPES, @@ -57,65 +57,65 @@ public class TypeValidation { }; private static ArrayList<String> VALID_TEMPLATE_VERSIONS = _getVTV(); - + private static ArrayList<String> _getVTV() { - ArrayList<String> vtv = new ArrayList<>(); - vtv.add("tosca_simple_yaml_1_0"); - vtv.add("tosca_simple_yaml_1_1"); - ExtTools exttools = new ExtTools(); + ArrayList<String> vtv = new ArrayList<>(); + vtv.add("tosca_simple_yaml_1_0"); + vtv.add("tosca_simple_yaml_1_1"); + ExtTools exttools = new ExtTools(); vtv.addAll(exttools.getVersions()); return vtv; } - + //private LinkedHashMap<String,Object> customTypes; private Object importDef; //private String version; - - public TypeValidation(LinkedHashMap<String,Object> _customTypes, - Object _importDef) { + + public TypeValidation(LinkedHashMap<String, Object> _customTypes, + Object _importDef) { importDef = _importDef; _validateTypeKeys(_customTypes); } - - private void _validateTypeKeys(LinkedHashMap<String,Object> customTypes) { - - String sVersion = (String)customTypes.get(DEFINITION_VERSION); - if(sVersion != null) { - _validateTypeVersion(sVersion); + + private void _validateTypeKeys(LinkedHashMap<String, Object> customTypes) { + + String sVersion = (String) customTypes.get(DEFINITION_VERSION); + if (sVersion != null) { + _validateTypeVersion(sVersion); //version = sVersion; } - for(String name: customTypes.keySet()) { - boolean bFound = false; - for(String ats: ALLOWED_TYPE_SECTIONS) { - if(name.equals(ats)) { - bFound = true; - break; - } - } - if(!bFound) { + for (String name : customTypes.keySet()) { + boolean bFound = false; + for (String ats : ALLOWED_TYPE_SECTIONS) { + if (name.equals(ats)) { + bFound = true; + break; + } + } + if (!bFound) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE138", String.format( - "UnknownFieldError: Template \"%s\" contains unknown field \"%s\"", - importDef.toString(),name))); - } + "UnknownFieldError: Template \"%s\" contains unknown field \"%s\"", + importDef.toString(), name))); + } } } - + private void _validateTypeVersion(String sVersion) { - boolean bFound = false; - String allowed = ""; - for(String atv: VALID_TEMPLATE_VERSIONS) { - allowed += "\"" + atv + "\" "; - if(sVersion.equals(atv)) { - bFound = true; - break; - } - } - if(!bFound) { + boolean bFound = false; + String allowed = ""; + for (String atv : VALID_TEMPLATE_VERSIONS) { + allowed += "\"" + atv + "\" "; + if (sVersion.equals(atv)) { + bFound = true; + break; + } + } + if (!bFound) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE139", String.format( - "InvalidTemplateVersion: version \"%s\" in \"%s\" is not supported\n" + - "Allowed versions: [%s]", - sVersion,importDef.toString(),allowed))); - } + "InvalidTemplateVersion: version \"%s\" in \"%s\" is not supported\n" + + "Allowed versions: [%s]", + sVersion, importDef.toString(), allowed))); + } } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Constraint.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Constraint.java index 82f6718..dd77659 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Constraint.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Constraint.java @@ -7,9 +7,9 @@ * 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. @@ -20,175 +20,221 @@ package org.onap.sdc.toscaparser.api.elements.constraints; -import java.util.ArrayList; -import java.util.LinkedHashMap; - import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; import org.onap.sdc.toscaparser.api.elements.ScalarUnit; import org.onap.sdc.toscaparser.api.functions.Function; import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + public abstract class Constraint { - - // Parent class for constraints for a Property or Input - - protected static final String EQUAL = "equal"; - protected static final String GREATER_THAN = "greater_than"; - protected static final String GREATER_OR_EQUAL = "greater_or_equal"; - protected static final String LESS_THAN = "less_than"; - protected static final String LESS_OR_EQUAL = "less_or_equal"; - protected static final String IN_RANGE = "in_range"; - protected static final String VALID_VALUES = "valid_values"; - protected static final String LENGTH = "length"; - protected static final String MIN_LENGTH = "min_length"; - protected static final String MAX_LENGTH = "max_length"; - protected static final String PATTERN = "pattern"; - - protected static final String CONSTRAINTS[] = { - EQUAL, GREATER_THAN,GREATER_OR_EQUAL, LESS_THAN, LESS_OR_EQUAL, - IN_RANGE, VALID_VALUES, LENGTH, MIN_LENGTH, MAX_LENGTH, PATTERN}; - - @SuppressWarnings("unchecked") - public static Constraint factory(String constraintClass,String propname,String proptype,Object constraint) { - - // a factory for the different Constraint classes - // replaces Python's __new__() usage - - if(!(constraint instanceof LinkedHashMap) || - ((LinkedHashMap<String,Object>)constraint).size() != 1) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE101", - "InvalidSchemaError: Invalid constraint schema " + constraint.toString())); - } - - if(constraintClass.equals(EQUAL)) { - return new Equal(propname,proptype,constraint); - } - else if(constraintClass.equals(GREATER_THAN)) { - return new GreaterThan(propname,proptype,constraint); - } - else if(constraintClass.equals(GREATER_OR_EQUAL)) { - return new GreaterOrEqual(propname,proptype,constraint); - } - else if(constraintClass.equals(LESS_THAN)) { - return new LessThan(propname,proptype,constraint); - } - else if(constraintClass.equals(LESS_OR_EQUAL)) { - return new LessOrEqual(propname,proptype,constraint); - } - else if(constraintClass.equals(IN_RANGE)) { - return new InRange(propname,proptype,constraint); - } - else if(constraintClass.equals(VALID_VALUES)) { - return new ValidValues(propname,proptype,constraint); - } - else if(constraintClass.equals(LENGTH)) { - return new Length(propname,proptype,constraint); - } - else if(constraintClass.equals(MIN_LENGTH)) { - return new MinLength(propname,proptype,constraint); - } - else if(constraintClass.equals(MAX_LENGTH)) { - return new MaxLength(propname,proptype,constraint); - } - else if(constraintClass.equals(PATTERN)) { - return new Pattern(propname,proptype,constraint); + + // Parent class for constraints for a Property or Input + + protected static final String EQUAL = "equal"; + protected static final String GREATER_THAN = "greater_than"; + protected static final String GREATER_OR_EQUAL = "greater_or_equal"; + protected static final String LESS_THAN = "less_than"; + protected static final String LESS_OR_EQUAL = "less_or_equal"; + protected static final String IN_RANGE = "in_range"; + protected static final String VALID_VALUES = "valid_values"; + protected static final String LENGTH = "length"; + protected static final String MIN_LENGTH = "min_length"; + protected static final String MAX_LENGTH = "max_length"; + protected static final String PATTERN = "pattern"; + + protected static final String[] CONSTRAINTS = { + EQUAL, GREATER_THAN, GREATER_OR_EQUAL, LESS_THAN, LESS_OR_EQUAL, + IN_RANGE, VALID_VALUES, LENGTH, MIN_LENGTH, MAX_LENGTH, PATTERN}; + + @SuppressWarnings("unchecked") + public static Constraint factory(String constraintClass, String propname, String proptype, Object constraint) { + + // a factory for the different Constraint classes + // replaces Python's __new__() usage + + if (!(constraint instanceof LinkedHashMap) + || ((LinkedHashMap<String, Object>) constraint).size() != 1) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE101", + "InvalidSchemaError: Invalid constraint schema " + constraint.toString())); } - else { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE102", String.format( - "InvalidSchemaError: Invalid property \"%s\"",constraintClass))); - return null; + + switch (constraintClass) { + case EQUAL: + return new Equal(propname, proptype, constraint); + case GREATER_THAN: + return new GreaterThan(propname, proptype, constraint); + case GREATER_OR_EQUAL: + return new GreaterOrEqual(propname, proptype, constraint); + case LESS_THAN: + return new LessThan(propname, proptype, constraint); + case LESS_OR_EQUAL: + return new LessOrEqual(propname, proptype, constraint); + case IN_RANGE: + return new InRange(propname, proptype, constraint); + case VALID_VALUES: + return new ValidValues(propname, proptype, constraint); + case LENGTH: + return new Length(propname, proptype, constraint); + case MIN_LENGTH: + return new MinLength(propname, proptype, constraint); + case MAX_LENGTH: + return new MaxLength(propname, proptype, constraint); + case PATTERN: + return new Pattern(propname, proptype, constraint); + default: + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE102", String.format( + "InvalidSchemaError: Invalid property \"%s\"", constraintClass))); + return null; } - } - - protected String constraintKey = "TBD"; - protected ArrayList<String> validTypes = new ArrayList<>(); - protected ArrayList<String> validPropTypes = new ArrayList<>(); - - protected String propertyName; - protected String propertyType; - protected Object constraintValue; - protected Object constraintValueMsg; - protected Object valueMsg; - - @SuppressWarnings("unchecked") - public Constraint(String propname,String proptype,Object constraint) { - - _setValues(); - + } + + private String constraintKey = "TBD"; + protected ArrayList<String> validTypes = new ArrayList<>(); + protected ArrayList<String> validPropTypes = new ArrayList<>(); + + protected String propertyName; + private String propertyType; + protected Object constraintValue; + protected Object constraintValueMsg; + protected Object valueMsg; + + @SuppressWarnings("unchecked") + public Constraint(String propname, String proptype, Object constraint) { + + setValues(); + propertyName = propname; propertyType = proptype; - constraintValue = ((LinkedHashMap<String,Object>)constraint).get(constraintKey); + constraintValue = ((LinkedHashMap<String, Object>) constraint).get(constraintKey); constraintValueMsg = constraintValue; boolean bFound = false; - for(String s: ScalarUnit.SCALAR_UNIT_TYPES) { - if(s.equals(propertyType)) { - bFound = true; - break; - } + for (String s : ScalarUnit.SCALAR_UNIT_TYPES) { + if (s.equals(propertyType)) { + bFound = true; + break; + } } - if(bFound) { + if (bFound) { constraintValue = _getScalarUnitConstraintValue(); } // check if constraint is valid for property type bFound = false; - for(String s: validPropTypes) { - if(s.equals(propertyType)) { - bFound = true; - break; - } + for (String s : validPropTypes) { + if (s.equals(propertyType)) { + bFound = true; + break; + } } - if(!bFound) { + if (!bFound) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE103", String.format( - "InvalidSchemaError: Property \"%s\" is not valid for data type \"%s\"", - constraintKey,propertyType))); + "InvalidSchemaError: Property \"%s\" is not valid for data type \"%s\"", + constraintKey, propertyType))); } - } - - @SuppressWarnings("unchecked") - private Object _getScalarUnitConstraintValue() { - // code differs from Python because of class creation - if(constraintValue instanceof ArrayList) { - ArrayList<Object> ret = new ArrayList<>(); - for(Object v: (ArrayList<Object>)constraintValue) { - ScalarUnit su = ScalarUnit.getScalarunitClass(propertyType,v); - ret.add(su.getNumFromScalarUnit(null)); - } - return ret; - } - else { - ScalarUnit su = ScalarUnit.getScalarunitClass(propertyType,constraintValue); - return su.getNumFromScalarUnit(null); - } - } - - public void validate(Object value) { - if (Function.isFunction(value)){ - //skipping constraints check for functions - return; - } - - valueMsg = value; + } + + public ArrayList<String> getValidTypes() { + return validTypes; + } + + public void addValidTypes(List<String> validTypes) { + this.validTypes.addAll(validTypes); + } + + public ArrayList<String> getValidPropTypes() { + return validPropTypes; + } + + public String getPropertyType() { + return propertyType; + } + + public Object getConstraintValue() { + return constraintValue; + } + + public Object getConstraintValueMsg() { + return constraintValueMsg; + } + + public Object getValueMsg() { + return valueMsg; + } + + public void setConstraintKey(String constraintKey) { + this.constraintKey = constraintKey; + } + + public void setValidTypes(ArrayList<String> validTypes) { + this.validTypes = validTypes; + } + + public void setValidPropTypes(ArrayList<String> validPropTypes) { + this.validPropTypes = validPropTypes; + } + + public void setPropertyType(String propertyType) { + this.propertyType = propertyType; + } + + public void setConstraintValue(Object constraintValue) { + this.constraintValue = constraintValue; + } + + public void setConstraintValueMsg(Object constraintValueMsg) { + this.constraintValueMsg = constraintValueMsg; + } + + public void setValueMsg(Object valueMsg) { + this.valueMsg = valueMsg; + } + + @SuppressWarnings("unchecked") + private Object _getScalarUnitConstraintValue() { + // code differs from Python because of class creation + if (constraintValue instanceof ArrayList) { + ArrayList<Object> ret = new ArrayList<>(); + for (Object v : (ArrayList<Object>) constraintValue) { + ScalarUnit su = ScalarUnit.getScalarunitClass(propertyType, v); + ret.add(su.getNumFromScalarUnit(null)); + } + return ret; + } else { + ScalarUnit su = ScalarUnit.getScalarunitClass(propertyType, constraintValue); + return su.getNumFromScalarUnit(null); + } + } + + public void validate(Object value) { + if (Function.isFunction(value)) { + //skipping constraints check for functions + return; + } + + valueMsg = value; boolean bFound = false; - for(String s: ScalarUnit.SCALAR_UNIT_TYPES) { - if(s.equals(propertyType)) { - bFound = true; - break; - } + for (String s : ScalarUnit.SCALAR_UNIT_TYPES) { + if (s.equals(propertyType)) { + bFound = true; + break; + } } - if(bFound) { - value = ScalarUnit.getScalarunitValue(propertyType,value,null); + if (bFound) { + value = ScalarUnit.getScalarunitValue(propertyType, value, null); } - if(!_isValid(value)) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE008", "ValidationError: " + _errMsg(value))); + if (!isValid(value)) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE008", "ValidationError: " + errMsg(value))); } - } + } + + protected abstract boolean isValid(Object value); + + protected abstract void setValues(); - protected abstract boolean _isValid(Object value); - - protected abstract void _setValues(); + protected abstract String errMsg(Object value); - protected abstract String _errMsg(Object value); - } /*python diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Equal.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Equal.java index 16e379a..f480099 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Equal.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Equal.java @@ -7,9 +7,9 @@ * 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. @@ -20,36 +20,32 @@ package org.onap.sdc.toscaparser.api.elements.constraints; +import java.util.Arrays; + public class Equal extends Constraint { - protected void _setValues() { - - constraintKey = EQUAL; - - for(String s: Schema.PROPERTY_TYPES) { - validPropTypes.add(s); - } - - } - - public Equal(String name,String type,Object c) { - super(name,type,c); - - } - - protected boolean _isValid(Object val) { - // equality of objects is tricky so we're comparing - // the toString() representation - if(val.toString().equals(constraintValue.toString())) { - return true; - } - return false; - } - - protected String _errMsg(Object value) { - return String.format("The value \"%s\" of property \"%s\" is not equal to \"%s\"", - valueMsg,propertyName,constraintValueMsg); - } + protected void setValues() { + + setConstraintKey(EQUAL); + validPropTypes.addAll(Arrays.asList(Schema.PROPERTY_TYPES)); + + } + + public Equal(String name, String type, Object c) { + super(name, type, c); + + } + + protected boolean isValid(Object val) { + // equality of objects is tricky so we're comparing + // the toString() representation + return val.toString().equals(constraintValue.toString()); + } + + protected String errMsg(Object value) { + return String.format("The value \"%s\" of property \"%s\" is not equal to \"%s\"", + valueMsg, propertyName, constraintValueMsg); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/GreaterOrEqual.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/GreaterOrEqual.java index 4d6b1cf..0cb8f36 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/GreaterOrEqual.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/GreaterOrEqual.java @@ -7,9 +7,9 @@ * 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. @@ -21,73 +21,69 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; - -import java.util.Date; - import org.onap.sdc.toscaparser.api.functions.Function; import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.Arrays; +import java.util.Date; + public class GreaterOrEqual extends Constraint { - // Constraint class for "greater_or_equal" - - // Constrains a property or parameter to a value greater than or equal - // to ('>=') the value declared. - - protected void _setValues() { - - constraintKey = GREATER_OR_EQUAL; - - validTypes.add("Integer"); - validTypes.add("Double"); - validTypes.add("Float"); - // timestamps are loaded as Date objects - validTypes.add("Date"); - //validTypes.add("datetime.date"); - //validTypes.add("datetime.time"); - //validTypes.add("datetime.datetime"); - - validPropTypes.add(Schema.INTEGER); - validPropTypes.add(Schema.FLOAT); - validPropTypes.add(Schema.TIMESTAMP); - validPropTypes.add(Schema.SCALAR_UNIT_SIZE); - validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); - validPropTypes.add(Schema.SCALAR_UNIT_TIME); - - } - - public GreaterOrEqual(String name,String type,Object c) { - super(name,type,c); - - if(!validTypes.contains(constraintValue.getClass().getSimpleName())) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE104", "InvalidSchemaError: The property \"greater_or_equal\" expects comparable values")); - } - } - - - - @Override - protected boolean _isValid(Object value) { - if(Function.isFunction(value)) { - return true; - } - - // timestamps - if(value instanceof Date) { - if(constraintValue instanceof Date) { - return !((Date)value).before((Date)constraintValue); - } - return false; - } - // all others - Double n1 = new Double(value.toString()); - Double n2 = new Double(constraintValue.toString()); - return n1 >= n2; - } - - protected String _errMsg(Object value) { - return String.format("The value \"%s\" of property \"%s\" must be greater or equal to \"%s\"", - valueMsg,propertyName,constraintValueMsg); - } + // Constraint class for "greater_or_equal" + + // Constrains a property or parameter to a value greater than or equal + // to ('>=') the value declared. + + protected void setValues() { + + setConstraintKey(GREATER_OR_EQUAL); + + // timestamps are loaded as Date objects + addValidTypes(Arrays.asList("Integer", "Double", "Float", "Date")); + //validTypes.add("datetime.date"); + //validTypes.add("datetime.time"); + //validTypes.add("datetime.datetime"); + + validPropTypes.add(Schema.INTEGER); + validPropTypes.add(Schema.FLOAT); + validPropTypes.add(Schema.TIMESTAMP); + validPropTypes.add(Schema.SCALAR_UNIT_SIZE); + validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); + validPropTypes.add(Schema.SCALAR_UNIT_TIME); + + } + + public GreaterOrEqual(String name, String type, Object c) { + super(name, type, c); + + if (!validTypes.contains(constraintValue.getClass().getSimpleName())) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE104", "InvalidSchemaError: The property \"greater_or_equal\" expects comparable values")); + } + } + + + @Override + protected boolean isValid(Object value) { + if (Function.isFunction(value)) { + return true; + } + + // timestamps + if (value instanceof Date) { + if (constraintValue instanceof Date) { + return !((Date) value).before((Date) constraintValue); + } + return false; + } + // all others + Double n1 = new Double(value.toString()); + Double n2 = new Double(constraintValue.toString()); + return n1 >= n2; + } + + protected String errMsg(Object value) { + return String.format("The value \"%s\" of property \"%s\" must be greater or equal to \"%s\"", + valueMsg, propertyName, constraintValueMsg); + } } /*python diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/GreaterThan.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/GreaterThan.java index c716821..b501907 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/GreaterThan.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/GreaterThan.java @@ -7,9 +7,9 @@ * 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. @@ -21,65 +21,62 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; +import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.Arrays; import java.util.Date; -import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; - public class GreaterThan extends Constraint { - @Override - protected void _setValues() { - - constraintKey = GREATER_THAN; - - validTypes.add("Integer"); - validTypes.add("Double"); - validTypes.add("Float"); - // timestamps are loaded as Date objects - validTypes.add("Date"); - //validTypes.add("datetime.date"); - //validTypes.add("datetime.time"); - //validTypes.add("datetime.datetime"); - - - validPropTypes.add(Schema.INTEGER); - validPropTypes.add(Schema.FLOAT); - validPropTypes.add(Schema.TIMESTAMP); - validPropTypes.add(Schema.SCALAR_UNIT_SIZE); - validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); - validPropTypes.add(Schema.SCALAR_UNIT_TIME); - - } - - public GreaterThan(String name,String type,Object c) { - super(name,type,c); - - if(!validTypes.contains(constraintValue.getClass().getSimpleName())) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE105", "InvalidSchemaError: The property \"greater_than\" expects comparable values")); - } - } - - @Override - protected boolean _isValid(Object value) { - - // timestamps - if(value instanceof Date) { - if(constraintValue instanceof Date) { - return ((Date)value).after((Date)constraintValue); - } - return false; - } - - Double n1 = new Double(value.toString()); - Double n2 = new Double(constraintValue.toString()); - return n1 > n2; - } - - protected String _errMsg(Object value) { - return String.format("The value \"%s\" of property \"%s\" must be greater than \"%s\"", - valueMsg,propertyName,constraintValueMsg); - } + @Override + protected void setValues() { + + setConstraintKey(GREATER_THAN); + + // timestamps are loaded as Date objects + addValidTypes(Arrays.asList("Integer", "Double", "Float", "Date")); + //validTypes.add("datetime.date"); + //validTypes.add("datetime.time"); + //validTypes.add("datetime.datetime"); + + + validPropTypes.add(Schema.INTEGER); + validPropTypes.add(Schema.FLOAT); + validPropTypes.add(Schema.TIMESTAMP); + validPropTypes.add(Schema.SCALAR_UNIT_SIZE); + validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); + validPropTypes.add(Schema.SCALAR_UNIT_TIME); + + } + + public GreaterThan(String name, String type, Object c) { + super(name, type, c); + + if (!validTypes.contains(constraintValue.getClass().getSimpleName())) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE105", "InvalidSchemaError: The property \"greater_than\" expects comparable values")); + } + } + + @Override + protected boolean isValid(Object value) { + + // timestamps + if (value instanceof Date) { + if (constraintValue instanceof Date) { + return ((Date) value).after((Date) constraintValue); + } + return false; + } + + Double n1 = new Double(value.toString()); + Double n2 = new Double(constraintValue.toString()); + return n1 > n2; + } + + protected String errMsg(Object value) { + return String.format("The value \"%s\" of property \"%s\" must be greater than \"%s\"", + valueMsg, propertyName, constraintValueMsg); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/InRange.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/InRange.java index 32719fa..4edf021 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/InRange.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/InRange.java @@ -7,9 +7,9 @@ * 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. @@ -23,6 +23,7 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.Arrays; import java.util.Date; import java.util.ArrayList; @@ -34,95 +35,89 @@ public class InRange extends Constraint { //the two values declared. private static final String UNBOUNDED = "UNBOUNDED"; - - private Object min,max; - - protected void _setValues() { - - constraintKey = IN_RANGE; - - validTypes.add("Integer"); - validTypes.add("Double"); - validTypes.add("Float"); - validTypes.add("String"); - // timestamps are loaded as Date objects - validTypes.add("Date"); - //validTypes.add("datetime.date"); - //validTypes.add("datetime.time"); - //validTypes.add("datetime.datetime"); - - validPropTypes.add(Schema.INTEGER); - validPropTypes.add(Schema.FLOAT); - validPropTypes.add(Schema.TIMESTAMP); - validPropTypes.add(Schema.SCALAR_UNIT_SIZE); - validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); - validPropTypes.add(Schema.SCALAR_UNIT_TIME); - validPropTypes.add(Schema.RANGE); - - } - - @SuppressWarnings("unchecked") - public InRange(String name,String type,Object c) { - super(name,type,c); - - if(!(constraintValue instanceof ArrayList) || ((ArrayList<Object>)constraintValue).size() != 2) { + + private Object min, max; + + protected void setValues() { + + setConstraintKey(IN_RANGE); + + // timestamps are loaded as Date objects + addValidTypes(Arrays.asList("Integer", "Double", "Float", "String", "Date")); + //validTypes.add("datetime.date"); + //validTypes.add("datetime.time"); + //validTypes.add("datetime.datetime"); + + validPropTypes.add(Schema.INTEGER); + validPropTypes.add(Schema.FLOAT); + validPropTypes.add(Schema.TIMESTAMP); + validPropTypes.add(Schema.SCALAR_UNIT_SIZE); + validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); + validPropTypes.add(Schema.SCALAR_UNIT_TIME); + validPropTypes.add(Schema.RANGE); + + } + + @SuppressWarnings("unchecked") + public InRange(String name, String type, Object c) { + super(name, type, c); + + if (!(constraintValue instanceof ArrayList) || ((ArrayList<Object>) constraintValue).size() != 2) { ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE106", "InvalidSchemaError: The property \"in_range\" expects a list")); - - } - ArrayList<Object> alcv = (ArrayList<Object>)constraintValue; + } + + ArrayList<Object> alcv = (ArrayList<Object>) constraintValue; String msg = "The property \"in_range\" expects comparable values"; - for(Object vo: alcv) { - if(!validTypes.contains(vo.getClass().getSimpleName())) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE107", "InvalidSchemaError: " + msg)); - } + for (Object vo : alcv) { + if (!validTypes.contains(vo.getClass().getSimpleName())) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE107", "InvalidSchemaError: " + msg)); + } // The only string we allow for range is the special value 'UNBOUNDED' - if((vo instanceof String) && !((String)vo).equals(UNBOUNDED)) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE108", "InvalidSchemaError: " + msg)); + if ((vo instanceof String) && !((String) vo).equals(UNBOUNDED)) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE108", "InvalidSchemaError: " + msg)); } } min = alcv.get(0); max = alcv.get(1); - - } - - @Override - protected boolean _isValid(Object value) { - - // timestamps - if(value instanceof Date) { - if(min instanceof Date && max instanceof Date) { - return !((Date)value).before((Date)min) && - !((Date)value).after((Date)max); - } - return false; - } - - Double dvalue = new Double(value.toString()); - if(!(min instanceof String)) { - if(dvalue < new Double(min.toString())) { - return false; + + } + + @Override + protected boolean isValid(Object value) { + + // timestamps + if (value instanceof Date) { + if (min instanceof Date && max instanceof Date) { + return !((Date) value).before((Date) min) + && !((Date) value).after((Date) max); } - } - else if(!((String)min).equals(UNBOUNDED)) { return false; } - if(!(max instanceof String)) { - if(dvalue > new Double(max.toString())) { + + Double dvalue = new Double(value.toString()); + if (!(min instanceof String)) { + if (dvalue < new Double(min.toString())) { return false; } + } else if (!((String) min).equals(UNBOUNDED)) { + return false; } - else if(!((String)max).equals(UNBOUNDED)) { + if (!(max instanceof String)) { + if (dvalue > new Double(max.toString())) { + return false; + } + } else if (!((String) max).equals(UNBOUNDED)) { return false; } return true; - } + } - @Override - protected String _errMsg(Object value) { + @Override + protected String errMsg(Object value) { return String.format("The value \"%s\" of property \"%s\" is out of range \"(min:%s, max:%s)\"", - valueMsg,propertyName,min.toString(),max.toString()); - } + valueMsg, propertyName, min.toString(), max.toString()); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Length.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Length.java index 1abdcfd..7988cb8 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Length.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Length.java @@ -7,9 +7,9 @@ * 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. @@ -23,44 +23,45 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.Collections; + public class Length extends Constraint { - // Constraint class for "length" - - // Constrains the property or parameter to a value of a given length. + // Constraint class for "length" - @Override - protected void _setValues() { + // Constrains the property or parameter to a value of a given length. - constraintKey = LENGTH; + @Override + protected void setValues() { - validTypes.add("Integer"); - - validPropTypes.add(Schema.STRING); - - } - - public Length(String name,String type,Object c) { - super(name,type,c); - - if(!validTypes.contains(constraintValue.getClass().getSimpleName())) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE109", "InvalidSchemaError: The property \"length\" expects an integer")); - } - } - - @Override - protected boolean _isValid(Object value) { - if(value instanceof String && constraintValue instanceof Integer && - ((String)value).length() == (Integer)constraintValue) { - return true; - } - return false; - } + setConstraintKey(LENGTH); + addValidTypes(Collections.singletonList("Integer")); + + validPropTypes.add(Schema.STRING); + + } + + public Length(String name, String type, Object c) { + super(name, type, c); + + if (!validTypes.contains(constraintValue.getClass().getSimpleName())) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE109", "InvalidSchemaError: The property \"length\" expects an integer")); + } + } + + @Override + protected boolean isValid(Object value) { + if (value instanceof String && constraintValue instanceof Integer && + ((String) value).length() == (Integer) constraintValue) { + return true; + } + return false; + } - @Override - protected String _errMsg(Object value) { - return String.format("Length of value \"%s\" of property \"%s\" must be equal to \"%s\"", - value.toString(),propertyName,constraintValue.toString()); - } + @Override + protected String errMsg(Object value) { + return String.format("Length of value \"%s\" of property \"%s\" must be equal to \"%s\"", + value.toString(), propertyName, constraintValue.toString()); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/LessOrEqual.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/LessOrEqual.java index 9f1cd65..37a4afc 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/LessOrEqual.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/LessOrEqual.java @@ -7,9 +7,9 @@ * 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. @@ -21,68 +21,65 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; +import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.Arrays; import java.util.Date; -import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; - public class LessOrEqual extends Constraint { - // Constraint class for "less_or_equal" - - // Constrains a property or parameter to a value less than or equal - // to ('<=') the value declared. - - protected void _setValues() { - - constraintKey = LESS_OR_EQUAL; - - validTypes.add("Integer"); - validTypes.add("Double"); - validTypes.add("Float"); - // timestamps are loaded as Date objects - validTypes.add("Date"); - //validTypes.add("datetime.date"); - //validTypes.add("datetime.time"); - //validTypes.add("datetime.datetime"); - - validPropTypes.add(Schema.INTEGER); - validPropTypes.add(Schema.FLOAT); - validPropTypes.add(Schema.TIMESTAMP); - validPropTypes.add(Schema.SCALAR_UNIT_SIZE); - validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); - validPropTypes.add(Schema.SCALAR_UNIT_TIME); - - } - - public LessOrEqual(String name,String type,Object c) { - super(name,type,c); - - if(!validTypes.contains(constraintValue.getClass().getSimpleName())) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE110", "InvalidSchemaError: The property \"less_or_equal\" expects comparable values")); - } - } - - @Override - protected boolean _isValid(Object value) { - - // timestamps - if(value instanceof Date) { - if(constraintValue instanceof Date) { - return !((Date)value).after((Date)constraintValue); - } - return false; - } - - Double n1 = new Double(value.toString()); - Double n2 = new Double(constraintValue.toString()); - return n1 <= n2; - } - - @Override - protected String _errMsg(Object value) { - return String.format("The value \"%s\" of property \"%s\" must be less or equal to \"%s\"", - valueMsg,propertyName,constraintValueMsg); - } + // Constraint class for "less_or_equal" + + // Constrains a property or parameter to a value less than or equal + // to ('<=') the value declared. + + protected void setValues() { + + setConstraintKey(LESS_OR_EQUAL); + + // timestamps are loaded as Date objects + addValidTypes(Arrays.asList("Integer", "Double", "Float", "Date")); + //validTypes.add("datetime.date"); + //validTypes.add("datetime.time"); + //validTypes.add("datetime.datetime"); + + validPropTypes.add(Schema.INTEGER); + validPropTypes.add(Schema.FLOAT); + validPropTypes.add(Schema.TIMESTAMP); + validPropTypes.add(Schema.SCALAR_UNIT_SIZE); + validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); + validPropTypes.add(Schema.SCALAR_UNIT_TIME); + + } + + public LessOrEqual(String name, String type, Object c) { + super(name, type, c); + + if (!validTypes.contains(constraintValue.getClass().getSimpleName())) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE110", "InvalidSchemaError: The property \"less_or_equal\" expects comparable values")); + } + } + + @Override + protected boolean isValid(Object value) { + + // timestamps + if (value instanceof Date) { + if (constraintValue instanceof Date) { + return !((Date) value).after((Date) constraintValue); + } + return false; + } + + Double n1 = new Double(value.toString()); + Double n2 = new Double(constraintValue.toString()); + return n1 <= n2; + } + + @Override + protected String errMsg(Object value) { + return String.format("The value \"%s\" of property \"%s\" must be less or equal to \"%s\"", + valueMsg, propertyName, constraintValueMsg); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/LessThan.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/LessThan.java index b893fea..952861d 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/LessThan.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/LessThan.java @@ -7,9 +7,9 @@ * 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. @@ -23,63 +23,60 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.Arrays; import java.util.Date; public class LessThan extends Constraint { - @Override - protected void _setValues() { - - constraintKey = LESS_THAN; - - validTypes.add("Integer"); - validTypes.add("Double"); - validTypes.add("Float"); - // timestamps are loaded as Date objects - validTypes.add("Date"); - //validTypes.add("datetime.date"); - //validTypes.add("datetime.time"); - //validTypes.add("datetime.datetime"); - - - validPropTypes.add(Schema.INTEGER); - validPropTypes.add(Schema.FLOAT); - validPropTypes.add(Schema.TIMESTAMP); - validPropTypes.add(Schema.SCALAR_UNIT_SIZE); - validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); - validPropTypes.add(Schema.SCALAR_UNIT_TIME); - - } - - public LessThan(String name,String type,Object c) { - super(name,type,c); - - if(!validTypes.contains(constraintValue.getClass().getSimpleName())) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE111", "InvalidSchemaError: The property \"less_than\" expects comparable values")); - } - } - - @Override - protected boolean _isValid(Object value) { - - // timestamps - if(value instanceof Date) { - if(constraintValue instanceof Date) { - return ((Date)value).before((Date)constraintValue); - } - return false; - } - - Double n1 = new Double(value.toString()); - Double n2 = new Double(constraintValue.toString()); - return n1 < n2; - } - - @Override - protected String _errMsg(Object value) { - return String.format("The value \"%s\" of property \"%s\" must be less than \"%s\"", - valueMsg,propertyName,constraintValueMsg); - } + @Override + protected void setValues() { + + setConstraintKey(LESS_THAN); + // timestamps are loaded as Date objects + addValidTypes(Arrays.asList("Integer", "Double", "Float", "Date")); + //validTypes.add("datetime.date"); + //validTypes.add("datetime.time"); + //validTypes.add("datetime.datetime"); + + + validPropTypes.add(Schema.INTEGER); + validPropTypes.add(Schema.FLOAT); + validPropTypes.add(Schema.TIMESTAMP); + validPropTypes.add(Schema.SCALAR_UNIT_SIZE); + validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY); + validPropTypes.add(Schema.SCALAR_UNIT_TIME); + + } + + public LessThan(String name, String type, Object c) { + super(name, type, c); + + if (!validTypes.contains(constraintValue.getClass().getSimpleName())) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE111", "InvalidSchemaError: The property \"less_than\" expects comparable values")); + } + } + + @Override + protected boolean isValid(Object value) { + + // timestamps + if (value instanceof Date) { + if (constraintValue instanceof Date) { + return ((Date) value).before((Date) constraintValue); + } + return false; + } + + Double n1 = new Double(value.toString()); + Double n2 = new Double(constraintValue.toString()); + return n1 < n2; + } + + @Override + protected String errMsg(Object value) { + return String.format("The value \"%s\" of property \"%s\" must be less than \"%s\"", + valueMsg, propertyName, constraintValueMsg); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/MaxLength.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/MaxLength.java index 2cb20eb..9068b65 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/MaxLength.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/MaxLength.java @@ -7,9 +7,9 @@ * 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. @@ -21,55 +21,54 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; +import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.Collections; import java.util.LinkedHashMap; -import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; - public class MaxLength extends Constraint { - // Constraint class for "min_length" - - // Constrains the property or parameter to a value of a maximum length. - - @Override - protected void _setValues() { - - constraintKey = MAX_LENGTH; - - validTypes.add("Integer"); - - validPropTypes.add(Schema.STRING); - validPropTypes.add(Schema.MAP); - - } - - public MaxLength(String name,String type,Object c) { - super(name,type,c); - - if(!validTypes.contains(constraintValue.getClass().getSimpleName())) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE112", "InvalidSchemaError: The property \"max_length\" expects an integer")); - } - } - - @SuppressWarnings("unchecked") - @Override - protected boolean _isValid(Object value) { - if(value instanceof String && constraintValue instanceof Integer && - ((String)value).length() <= (Integer)constraintValue) { - return true; - } - else if(value instanceof LinkedHashMap && constraintValue instanceof Integer && - ((LinkedHashMap<String,Object>)value).size() <= (Integer)constraintValue) { - return true; - } - return false; - } - - @Override - protected String _errMsg(Object value) { - return String.format("Length of value \"%s\" of property \"%s\" must be no greater than \"%s\"", - value.toString(),propertyName,constraintValue.toString()); - } + // Constraint class for "min_length" + + // Constrains the property or parameter to a value of a maximum length. + + @Override + protected void setValues() { + + setConstraintKey(MAX_LENGTH); + + addValidTypes(Collections.singletonList("Integer")); + + + validPropTypes.add(Schema.STRING); + validPropTypes.add(Schema.MAP); + + } + + public MaxLength(String name, String type, Object c) { + super(name, type, c); + + if (!validTypes.contains(constraintValue.getClass().getSimpleName())) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE112", "InvalidSchemaError: The property \"max_length\" expects an integer")); + } + } + + @SuppressWarnings("unchecked") + @Override + protected boolean isValid(Object value) { + if (value instanceof String && constraintValue instanceof Integer + && ((String) value).length() <= (Integer) constraintValue) { + return true; + } else { + return value instanceof LinkedHashMap && constraintValue instanceof Integer + && ((LinkedHashMap<String, Object>) value).size() <= (Integer) constraintValue; + } + } + + @Override + protected String errMsg(Object value) { + return String.format("Length of value \"%s\" of property \"%s\" must be no greater than \"%s\"", + value.toString(), propertyName, constraintValue.toString()); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/MinLength.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/MinLength.java index e7d0a9d..eb1d870 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/MinLength.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/MinLength.java @@ -7,9 +7,9 @@ * 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. @@ -21,55 +21,53 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; +import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.Collections; import java.util.LinkedHashMap; -import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; - public class MinLength extends Constraint { - // Constraint class for "min_length" - - // Constrains the property or parameter to a value of a minimum length. - - @Override - protected void _setValues() { - - constraintKey = MIN_LENGTH; - - validTypes.add("Integer"); - - validPropTypes.add(Schema.STRING); - validPropTypes.add(Schema.MAP); - - } - - public MinLength(String name,String type,Object c) { - super(name,type,c); - - if(!validTypes.contains(constraintValue.getClass().getSimpleName())) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE113", "InvalidSchemaError: The property \"min_length\" expects an integer")); - } - } - - @SuppressWarnings("unchecked") - @Override - protected boolean _isValid(Object value) { - if(value instanceof String && constraintValue instanceof Integer && - ((String)value).length() >= (Integer)constraintValue) { - return true; - } - else if(value instanceof LinkedHashMap && constraintValue instanceof Integer && - ((LinkedHashMap<String,Object>)value).size() >= (Integer)constraintValue) { - return true; - } - return false; - } - - @Override - protected String _errMsg(Object value) { - return String.format("Length of value \"%s\" of property \"%s\" must be at least \"%s\"", - value.toString(),propertyName,constraintValue.toString()); - } + // Constraint class for "min_length" + + // Constrains the property or parameter to a value of a minimum length. + + @Override + protected void setValues() { + + setConstraintKey(MIN_LENGTH); + + addValidTypes(Collections.singletonList("Integer")); + + validPropTypes.add(Schema.STRING); + validPropTypes.add(Schema.MAP); + + } + + public MinLength(String name, String type, Object c) { + super(name, type, c); + + if (!validTypes.contains(constraintValue.getClass().getSimpleName())) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE113", "InvalidSchemaError: The property \"min_length\" expects an integer")); + } + } + + @SuppressWarnings("unchecked") + @Override + protected boolean isValid(Object value) { + if (value instanceof String && constraintValue instanceof Integer + && ((String) value).length() >= (Integer) constraintValue) { + return true; + } else { + return value instanceof LinkedHashMap && constraintValue instanceof Integer + && ((LinkedHashMap<String, Object>) value).size() >= (Integer) constraintValue; + } + } + + @Override + protected String errMsg(Object value) { + return String.format("Length of value \"%s\" of property \"%s\" must be at least \"%s\"", + value.toString(), propertyName, constraintValue.toString()); + } } @@ -77,16 +75,16 @@ public class MinLength extends Constraint { class MinLength(Constraint): """Constraint class for "min_length" - + Constrains the property or parameter to a value to a minimum length. """ - + constraint_key = Constraint.MIN_LENGTH - + valid_types = (int, ) - + valid_prop_types = (Schema.STRING, Schema.MAP) - + def __init__(self, property_name, property_type, constraint): super(MinLength, self).__init__(property_name, property_type, constraint) @@ -94,14 +92,14 @@ class MinLength(Constraint): ValidationIsshueCollector.appendException( InvalidSchemaError(message=_('The property "min_length" ' 'expects an integer.'))) - + def _is_valid(self, value): if ((isinstance(value, str) or isinstance(value, dict)) and len(value) >= self.constraint_value): return True - + return False - + def _err_msg(self, value): return (_('Length of value "%(pvalue)s" of property "%(pname)s" ' 'must be at least "%(cvalue)s".') % diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Pattern.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Pattern.java index f1b374e..913e922 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Pattern.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Pattern.java @@ -7,9 +7,9 @@ * 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. @@ -21,63 +21,62 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; +import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.PatternSyntaxException; -import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; - public class Pattern extends Constraint { - @Override - protected void _setValues() { - - constraintKey = PATTERN; - - validTypes.add("String"); - - validPropTypes.add(Schema.STRING); - - } - - - public Pattern(String name,String type,Object c) { - super(name,type,c); - - if(!validTypes.contains(constraintValue.getClass().getSimpleName())) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE114", "InvalidSchemaError: The property \"pattern\" expects a string")); - } - } - - @Override - protected boolean _isValid(Object value) { - try { - if(!(value instanceof String)) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE115", String.format("ValueError: Input value \"%s\" to \"pattern\" property \"%s\" must be a string", - value.toString(),propertyName))); - return false; - } - String strp = constraintValue.toString(); - String strm = value.toString(); - java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(strp); - Matcher matcher = pattern.matcher(strm); - if(matcher.find() && matcher.end() == strm.length()) { - return true; - } - return false; - } - catch(PatternSyntaxException pse) { - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE116", String.format("ValueError: Invalid regex \"%s\" in \"pattern\" property \"%s\"", - constraintValue.toString(),propertyName))); - return false; - } - } - - @Override - protected String _errMsg(Object value) { - return String.format("The value \"%s\" of property \"%s\" does not match the pattern \"%s\"", - value.toString(),propertyName,constraintValue.toString()); - } + @Override + protected void setValues() { + + setConstraintKey(PATTERN); + + addValidTypes(Collections.singletonList("String")); + + validPropTypes.add(Schema.STRING); + + } + + + public Pattern(String name, String type, Object c) { + super(name, type, c); + + if (!validTypes.contains(constraintValue.getClass().getSimpleName())) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE114", "InvalidSchemaError: The property \"pattern\" expects a string")); + } + } + + @Override + protected boolean isValid(Object value) { + try { + if (!(value instanceof String)) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE115", String.format("ValueError: Input value \"%s\" to \"pattern\" property \"%s\" must be a string", + value.toString(), propertyName))); + return false; + } + String strp = constraintValue.toString(); + String strm = value.toString(); + java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(strp); + Matcher matcher = pattern.matcher(strm); + if (matcher.find() && matcher.end() == strm.length()) { + return true; + } + return false; + } catch (PatternSyntaxException pse) { + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE116", String.format("ValueError: Invalid regex \"%s\" in \"pattern\" property \"%s\"", + constraintValue.toString(), propertyName))); + return false; + } + } + + @Override + protected String errMsg(Object value) { + return String.format("The value \"%s\" of property \"%s\" does not match the pattern \"%s\"", + value.toString(), propertyName, constraintValue.toString()); + } } diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Schema.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Schema.java index 06a9cd0..15ec597 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Schema.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/Schema.java @@ -7,9 +7,9 @@ * 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. @@ -20,109 +20,110 @@ package org.onap.sdc.toscaparser.api.elements.constraints; +import com.google.common.collect.ImmutableMap; import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; +import org.onap.sdc.toscaparser.api.elements.enums.FileSize; import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class Schema { - private static final String TYPE = "type"; - private static final String REQUIRED = "required"; - private static final String DESCRIPTION = "description"; - private static final String DEFAULT = "default"; - private static final String CONSTRAINTS = "constraints"; - private static final String STATUS = "status"; - private static final String ENTRYSCHEMA = "entry_schema"; - private static final String KEYS[] = { - TYPE, REQUIRED, DESCRIPTION,DEFAULT, CONSTRAINTS, ENTRYSCHEMA, STATUS}; - - public static final String INTEGER = "integer"; - public static final String STRING = "string"; - public static final String BOOLEAN = "boolean"; - public static final String FLOAT = "float"; - public static final String RANGE = "range"; - public static final String NUMBER = "number"; - public static final String TIMESTAMP = "timestamp"; - public static final String LIST = "list"; - public static final String MAP = "map"; - public static final String SCALAR_UNIT_SIZE = "scalar-unit.size"; - public static final String SCALAR_UNIT_FREQUENCY = "scalar-unit.frequency"; - public static final String SCALAR_UNIT_TIME = "scalar-unit.time"; - public static final String VERSION = "version"; - public static final String PORTDEF = "PortDef"; - public static final String PORTSPEC = "PortSpec"; //??? PortSpec.SHORTNAME - public static final String JSON = "json"; - - public static final String PROPERTY_TYPES[] = { - INTEGER, STRING, BOOLEAN, FLOAT, RANGE,NUMBER, TIMESTAMP, LIST, MAP, - SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME, - VERSION, PORTDEF, PORTSPEC, JSON}; - - public static final String SIMPLE_PROPERTY_TYPES[] = { - INTEGER, STRING, BOOLEAN, FLOAT, RANGE,NUMBER, TIMESTAMP, - SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME, - VERSION}; - - @SuppressWarnings("unused") - private static final String SCALAR_UNIT_SIZE_DEFAULT = "B"; - - private static Map<String,Long> SCALAR_UNIT_SIZE_DICT = new HashMap<>(); - static { - SCALAR_UNIT_SIZE_DICT.put("B", 1L); - SCALAR_UNIT_SIZE_DICT.put("KB", 1000L); - SCALAR_UNIT_SIZE_DICT.put("KIB", 1024L); - SCALAR_UNIT_SIZE_DICT.put("MB", 1000000L); - SCALAR_UNIT_SIZE_DICT.put("MIB", 1048576L); - SCALAR_UNIT_SIZE_DICT.put("GB", 1000000000L); - SCALAR_UNIT_SIZE_DICT.put("GIB", 1073741824L); - SCALAR_UNIT_SIZE_DICT.put("TB", 1000000000000L); - SCALAR_UNIT_SIZE_DICT.put("TIB", 1099511627776L); - } - - private String name; - private LinkedHashMap<String,Object> schema; - private int _len; - private ArrayList<Constraint> constraintsList; - - - public Schema(String _name,LinkedHashMap<String,Object> _schemaDict) { - name = _name; - - if(!(_schemaDict instanceof LinkedHashMap)) { + private static final String TYPE = "type"; + private static final String REQUIRED = "required"; + private static final String DESCRIPTION = "description"; + private static final String DEFAULT = "default"; + private static final String CONSTRAINTS = "constraints"; + private static final String STATUS = "status"; + private static final String ENTRYSCHEMA = "entry_schema"; + private static final String[] KEYS = { + TYPE, REQUIRED, DESCRIPTION, DEFAULT, CONSTRAINTS, ENTRYSCHEMA, STATUS}; + + public static final String INTEGER = "integer"; + public static final String STRING = "string"; + public static final String BOOLEAN = "boolean"; + public static final String FLOAT = "float"; + public static final String RANGE = "range"; + public static final String NUMBER = "number"; + public static final String TIMESTAMP = "timestamp"; + public static final String LIST = "list"; + public static final String MAP = "map"; + public static final String SCALAR_UNIT_SIZE = "scalar-unit.size"; + public static final String SCALAR_UNIT_FREQUENCY = "scalar-unit.frequency"; + public static final String SCALAR_UNIT_TIME = "scalar-unit.time"; + public static final String VERSION = "version"; + public static final String PORTDEF = "PortDef"; + public static final String PORTSPEC = "PortSpec"; //??? PortSpec.SHORTNAME + public static final String JSON = "json"; + + public static final String[] PROPERTY_TYPES = { + INTEGER, STRING, BOOLEAN, FLOAT, RANGE, NUMBER, TIMESTAMP, LIST, MAP, + SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME, + VERSION, PORTDEF, PORTSPEC, JSON}; + + public static final String[] SIMPLE_PROPERTY_TYPES = { + INTEGER, STRING, BOOLEAN, FLOAT, RANGE, NUMBER, TIMESTAMP, + SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME, + VERSION}; + + @SuppressWarnings("unused") + private static final String SCALAR_UNIT_SIZE_DEFAULT = "B"; + + private static Map<String, Long> scalarUnitSizeDict = ImmutableMap.<String, Long>builder() + .put("B", FileSize.B) + .put("KB", FileSize.KB) + .put("MB", FileSize.MB) + .put("GB", FileSize.GB) + .put("TB", FileSize.TB) + .put("KIB", FileSize.KIB) + .put("MIB", FileSize.MIB) + .put("GIB", FileSize.GIB) + .put("TIB", FileSize.TIB) + .build(); + + + private String name; + private LinkedHashMap<String, Object> schema; + private int len; + private ArrayList<Constraint> constraintsList; + + + public Schema(String name, LinkedHashMap<String, Object> schemaDict) { + this.name = name; + + if (!(schemaDict instanceof LinkedHashMap)) { //msg = (_('Schema definition of "%(pname)s" must be a dict.') // % dict(pname=name)) ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE117", String.format( - "InvalidSchemaError: Schema definition of \"%s\" must be a dict",name))); + "InvalidSchemaError: Schema definition of \"%s\" must be a dict", this.name))); } - if(_schemaDict.get("type") == null) { + if (schemaDict.get("type") == null) { //msg = (_('Schema definition of "%(pname)s" must have a "type" ' // 'attribute.') % dict(pname=name)) ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE118", String.format( - "InvalidSchemaError: Schema definition of \"%s\" must have a \"type\" attribute",name))); + "InvalidSchemaError: Schema definition of \"%s\" must have a \"type\" attribute", this.name))); } - - schema = _schemaDict; - _len = 0; //??? None + + schema = schemaDict; + len = 0; //??? None constraintsList = new ArrayList<>(); - } + } public String getType() { - return (String)schema.get(TYPE); + return (String) schema.get(TYPE); } public boolean isRequired() { - return (boolean)schema.getOrDefault(REQUIRED, true); + return (boolean) schema.getOrDefault(REQUIRED, true); } public String getDescription() { - return (String)schema.getOrDefault(DESCRIPTION,""); + return (String) schema.getOrDefault(DESCRIPTION, ""); } public Object getDefault() { @@ -130,53 +131,52 @@ public class Schema { } public String getStatus() { - return (String)schema.getOrDefault(STATUS,""); + return (String) schema.getOrDefault(STATUS, ""); } public static boolean isRequestedTypeSimple(String type) { - return Arrays.stream(SIMPLE_PROPERTY_TYPES).anyMatch(t->t.equals(type)); - } + return Arrays.asList(SIMPLE_PROPERTY_TYPES).contains(type); + } @SuppressWarnings("unchecked") - public ArrayList<Constraint> getConstraints() { - if(constraintsList.size() == 0) { - Object cob = schema.get(CONSTRAINTS); - if(cob instanceof ArrayList) { - ArrayList<Object> constraintSchemata = (ArrayList<Object>)cob; - for(Object ob: constraintSchemata) { - if(ob instanceof LinkedHashMap) { - for(String cClass: ((LinkedHashMap<String,Object>)ob).keySet()) { - Constraint c = Constraint.factory(cClass,name,getType(),ob); - if(c != null) { - constraintsList.add(c); - } - else { - // error - ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE119", String.format( - "UnknownFieldError: Constraint type \"%s\" for property \"%s\" is not supported", - cClass,name))); - } - break; - } - } - } - } + public ArrayList<Constraint> getConstraints() { + if (constraintsList.size() == 0) { + Object cob = schema.get(CONSTRAINTS); + if (cob instanceof ArrayList) { + ArrayList<Object> constraintSchemata = (ArrayList<Object>) cob; + for (Object ob : constraintSchemata) { + if (ob instanceof LinkedHashMap) { + for (String cClass : ((LinkedHashMap<String, Object>) ob).keySet()) { + Constraint c = Constraint.factory(cClass, name, getType(), ob); + if (c != null) { + constraintsList.add(c); + } else { + // error + ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE119", String.format( + "UnknownFieldError: Constraint type \"%s\" for property \"%s\" is not supported", + cClass, name))); + } + break; + } + } + } + } } return constraintsList; } @SuppressWarnings("unchecked") - public LinkedHashMap<String,Object> getEntrySchema() { - return (LinkedHashMap<String,Object>)schema.get(ENTRYSCHEMA); + public LinkedHashMap<String, Object> getEntrySchema() { + return (LinkedHashMap<String, Object>) schema.get(ENTRYSCHEMA); } - + // Python intrinsic methods... // substitute for __getitem__ (aka self[key]) public Object getItem(String key) { - return schema.get(key); + return schema.get(key); } - + /* def __iter__(self): for k in self.KEYS: @@ -187,23 +187,24 @@ public class Schema { else: yield k */ - + // substitute for __len__ (aka self.len()) public int getLen() { - int len = 0; - for(String k: KEYS) { - if(schema.get(k) != null) { - len++; - } - _len = len; - } - return _len; + int len = 0; + for (String k : KEYS) { + if (schema.get(k) != null) { + len++; + } + this.len = len; + } + return this.len; } + // getter - public LinkedHashMap<String,Object> getSchema() { - return schema; + public LinkedHashMap<String, Object> getSchema() { + return schema; } - + } /*python @@ -231,7 +232,7 @@ PROPERTY_TYPES = ( ) SCALAR_UNIT_SIZE_DEFAULT = 'B' -SCALAR_UNIT_SIZE_DICT = {'B': 1, 'KB': 1000, 'KIB': 1024, 'MB': 1000000, +scalarUnitSizeDict = {'B': 1, 'KB': 1000, 'KIB': 1024, 'MB': 1000000, 'MIB': 1048576, 'GB': 1000000000, 'GIB': 1073741824, 'TB': 1000000000000, 'TIB': 1099511627776} @@ -251,7 +252,7 @@ def __init__(self, name, schema_dict): ValidationIssueCollector.appendException(InvalidSchemaError(message=msg)) self.schema = schema_dict - self._len = None + self.len = None self.constraints_list = [] @property @@ -302,7 +303,7 @@ def __iter__(self): yield k def __len__(self): - if self._len is None: - self._len = len(list(iter(self))) - return self._len + if self.len is None: + self.len = len(list(iter(self))) + return self.len */ diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/ValidValues.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/ValidValues.java index d09caae..c3a192d 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/ValidValues.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/constraints/ValidValues.java @@ -7,9 +7,9 @@ * 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. @@ -21,49 +21,44 @@ package org.onap.sdc.toscaparser.api.elements.constraints; import java.util.ArrayList; +import java.util.Collections; public class ValidValues extends Constraint { - protected void _setValues() { + protected void setValues() { + setConstraintKey(VALID_VALUES); + Collections.addAll(validPropTypes, Schema.PROPERTY_TYPES); + } + - constraintKey = VALID_VALUES; - - for(String s: Schema.PROPERTY_TYPES) { - validPropTypes.add(s); - } - - } - - - public ValidValues(String name,String type,Object c) { - super(name,type,c); - - } + public ValidValues(String name, String type, Object c) { + super(name, type, c); + } @SuppressWarnings("unchecked") - protected boolean _isValid(Object val) { - if(!(constraintValue instanceof ArrayList)) { - return false; - } - if(val instanceof ArrayList) { - boolean bAll = true; - for(Object v: (ArrayList<Object>)val) { - if(!((ArrayList<Object>)constraintValue).contains(v)) { - bAll = false; - break; - }; - } - return bAll; - } - return ((ArrayList<Object>)constraintValue).contains(val); + protected boolean isValid(Object val) { + if (!(constraintValue instanceof ArrayList)) { + return false; + } + if (val instanceof ArrayList) { + boolean bAll = true; + for (Object v : (ArrayList<Object>) val) { + if (!((ArrayList<Object>) constraintValue).contains(v)) { + bAll = false; + break; + } + } + return bAll; + } + return ((ArrayList<Object>) constraintValue).contains(val); } - protected String _errMsg(Object value) { - return String.format("The value \"%s\" of property \"%s\" is not valid. Expected a value from \"%s\"", - value.toString(),propertyName,constraintValue.toString()); + protected String errMsg(Object value) { + return String.format("The value \"%s\" of property \"%s\" is not valid. Expected a value from \"%s\"", + value.toString(), propertyName, constraintValue.toString()); } - + } /*python diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/enums/FileSize.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/enums/FileSize.java new file mode 100644 index 0000000..b07f7fa --- /dev/null +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/enums/FileSize.java @@ -0,0 +1,32 @@ +/* +============LICENSE_START======================================================= + SDC + ================================================================================ + Copyright (C) 2019 Nokia. 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.sdc.toscaparser.api.elements.enums; + +public class FileSize { + public static final long B = 1L; + public static final long KB = 1000L; + public static final long MB = 1000000L; + public static final long GB = 1000000000L; + public static final long TB = 1000000000000L; + public static final long KIB = 1000L; + public static final long MIB = 1048576L; + public static final long GIB = 1073741824L; + public static final long TIB = 1099511627776L; +} diff --git a/src/main/java/org/onap/sdc/toscaparser/api/elements/enums/ToscaElementNames.java b/src/main/java/org/onap/sdc/toscaparser/api/elements/enums/ToscaElementNames.java index 715123b..ac0d837 100644 --- a/src/main/java/org/onap/sdc/toscaparser/api/elements/enums/ToscaElementNames.java +++ b/src/main/java/org/onap/sdc/toscaparser/api/elements/enums/ToscaElementNames.java @@ -7,9 +7,9 @@ * 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. @@ -21,20 +21,20 @@ package org.onap.sdc.toscaparser.api.elements.enums; public enum ToscaElementNames { - - TYPE ("type"), - PROPERTIES ("properties"), - ANNOTATIONS ("annotations"), - SOURCE_TYPE ("source_type"); - - private String name; - - ToscaElementNames(String name){ - this.name = name; - } - public String getName() { - return name; - } - + TYPE("type"), + PROPERTIES("properties"), + ANNOTATIONS("annotations"), + SOURCE_TYPE("source_type"); + + private String name; + + ToscaElementNames(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } |