diff options
Diffstat (limited to 'catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca')
71 files changed, 3428 insertions, 3698 deletions
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java index ad226f4e57..a0ff4bc09b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java @@ -20,32 +20,8 @@ package org.openecomp.sdc.be.model.tosca; -import org.openecomp.sdc.be.model.tosca.converters.BooleanConverter; -import org.openecomp.sdc.be.model.tosca.converters.DefaultConverter; -import org.openecomp.sdc.be.model.tosca.converters.FloatConverter; -import org.openecomp.sdc.be.model.tosca.converters.IntegerConverter; -import org.openecomp.sdc.be.model.tosca.converters.JsonConverter; -import org.openecomp.sdc.be.model.tosca.converters.ListConverter; -import org.openecomp.sdc.be.model.tosca.converters.MapConverter; -import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; -import org.openecomp.sdc.be.model.tosca.converters.StringConvertor; -import org.openecomp.sdc.be.model.tosca.converters.ToscaBooleanConverter; -import org.openecomp.sdc.be.model.tosca.converters.ToscaFloatConverter; -import org.openecomp.sdc.be.model.tosca.converters.ToscaJsonValueConverter; -import org.openecomp.sdc.be.model.tosca.converters.ToscaListValueConverter; -import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter; -import org.openecomp.sdc.be.model.tosca.converters.ToscaStringConvertor; -import org.openecomp.sdc.be.model.tosca.converters.ToscaValueConverter; -import org.openecomp.sdc.be.model.tosca.converters.ToscaValueDefaultConverter; -import org.openecomp.sdc.be.model.tosca.validators.BooleanValidator; -import org.openecomp.sdc.be.model.tosca.validators.FloatValidator; -import org.openecomp.sdc.be.model.tosca.validators.IntegerValidator; -import org.openecomp.sdc.be.model.tosca.validators.JsonValidator; -import org.openecomp.sdc.be.model.tosca.validators.KeyValidator; -import org.openecomp.sdc.be.model.tosca.validators.ListValidator; -import org.openecomp.sdc.be.model.tosca.validators.MapValidator; -import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; -import org.openecomp.sdc.be.model.tosca.validators.StringValidator; +import org.openecomp.sdc.be.model.tosca.converters.*; +import org.openecomp.sdc.be.model.tosca.validators.*; /** * The primitive type that TOSCA YAML supports. @@ -54,150 +30,142 @@ import org.openecomp.sdc.be.model.tosca.validators.StringValidator; */ public enum ToscaPropertyType { - Root("tosca.datatypes.Root", null, null, null, true), + Root("tosca.datatypes.Root", null, null, null, true), - STRING("string", StringValidator.getInstance(), StringConvertor.getInstance(), ToscaStringConvertor.getInstance()), + STRING("string", StringValidator.getInstance(), StringConvertor.getInstance(), ToscaStringConvertor.getInstance()), - BOOLEAN("boolean", BooleanValidator.getInstance(), ToscaBooleanConverter.getInstance(), BooleanConverter.getInstance()), + BOOLEAN("boolean", BooleanValidator.getInstance(), ToscaBooleanConverter.getInstance(), BooleanConverter.getInstance()), - FLOAT("float", FloatValidator.getInstance(), ToscaFloatConverter.getInstance(), FloatConverter.getInstance()), + FLOAT("float", FloatValidator.getInstance(), ToscaFloatConverter.getInstance(), FloatConverter.getInstance()), - INTEGER("integer", IntegerValidator.getInstance(), DefaultConverter.getInstance(), IntegerConverter.getInstance()), - - SCALAR_UNIT("scalar-unit", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), + INTEGER("integer", IntegerValidator.getInstance(), DefaultConverter.getInstance(), IntegerConverter.getInstance()), - SCALAR_UNIT_SIZE("scalar-unit.size", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), + SCALAR_UNIT("scalar-unit", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - SCALAR_UNIT_TIME("scalar-unit.time", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), + SCALAR_UNIT_SIZE("scalar-unit.size", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - SCALAR_UNIT_FREQUENCY("scalar-unit.frequency", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), + SCALAR_UNIT_TIME("scalar-unit.time", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - RANGE("range", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), + SCALAR_UNIT_FREQUENCY("scalar-unit.frequency", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - TIMESTAMP("timestamp", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), + RANGE("range", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - MAP("map", MapValidator.getInstance(), MapConverter.getInstance(), ToscaMapValueConverter.getInstance()), + TIMESTAMP("timestamp", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - LIST("list", ListValidator.getInstance(), ListConverter.getInstance(), ToscaListValueConverter.getInstance()), + MAP("map", MapValidator.getInstance(), MapConverter.getInstance(), ToscaMapValueConverter.getInstance()), - VERSION("version", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), + LIST("list", ListValidator.getInstance(), ListConverter.getInstance(), ToscaListValueConverter.getInstance()), - KEY("key", KeyValidator.getInstance(), StringConvertor.getInstance(), ToscaValueDefaultConverter.getInstance()), + VERSION("version", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - JSON("json", JsonValidator.getInstance(), JsonConverter.getInstance(), ToscaJsonValueConverter.getInstance()); + KEY("key", KeyValidator.getInstance(), StringConvertor.getInstance(), ToscaValueDefaultConverter.getInstance()), - // CREDENTIAL("tosca.datatypes.Credential", StringValidator.getInstance(), - // DefaultConverter.getInstance()); + JSON("json", JsonValidator.getInstance(), JsonConverter.getInstance(), ToscaJsonValueConverter.getInstance()); - private String type; - private PropertyTypeValidator validator; - private PropertyValueConverter converter; - private ToscaValueConverter valueConverter; - private boolean isAbstract = false; + private String type; + private PropertyTypeValidator validator; + private PropertyValueConverter converter; + private ToscaValueConverter valueConverter; + private boolean isAbstract = false; - ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter) { - this.type = type; - this.validator = validator; - this.converter = converter; - this.valueConverter = valueConverter; - } + ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter) { + this.type = type; + this.validator = validator; + this.converter = converter; + this.valueConverter = valueConverter; + } - ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter, boolean isAbstract) { - this(type, validator, converter, valueConverter); - this.isAbstract = isAbstract; - } + ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter, boolean isAbstract) { + this(type, validator, converter, valueConverter); + this.isAbstract = isAbstract; + } - // private static final Pattern TIMESTAMP_REGEX = Pattern - // .compile("[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[0-9][0-9][0-9][0-9]-[0-9][0-9]?-[0-9][0-9]?([Tt]|[ - // \\t]+)[0-9][0-9]?:[0-9][0-9]:[0-9][0-9](\\.[0-9]*)?(([ \\t]*)Z|([ - // \\t]*)[-+][0-9][0-9]?(:[0-9][0-9])?)?"); + public String getType() { + return type; + } - public String getType() { - return type; - } + public void setType(String type) { + this.type = type; + } - public void setType(String type) { - this.type = type; - } + public PropertyTypeValidator getValidator() { + return validator; + } - public PropertyTypeValidator getValidator() { - return validator; - } + public void setValidator(PropertyTypeValidator validator) { + this.validator = validator; + } - public void setValidator(PropertyTypeValidator validator) { - this.validator = validator; - } + public PropertyValueConverter getConverter() { + return converter; + } - public PropertyValueConverter getConverter() { - return converter; - } + public void setConverter(PropertyValueConverter converter) { + this.converter = converter; + } - public void setConverter(PropertyValueConverter converter) { - this.converter = converter; - } + public boolean isAbstract() { + return isAbstract; + } - public boolean isAbstract() { - return isAbstract; - } + public void setAbstract(boolean isAbstract) { + this.isAbstract = isAbstract; + } - public void setAbstract(boolean isAbstract) { - this.isAbstract = isAbstract; - } + public ToscaValueConverter getValueConverter() { + return valueConverter; + } - public ToscaValueConverter getValueConverter() { - return valueConverter; - } + public void setValueConverter(ToscaValueConverter valueConverter) { + this.valueConverter = valueConverter; + } - public void setValueConverter(ToscaValueConverter valueConverter) { - this.valueConverter = valueConverter; - } + public static ToscaPropertyType isValidType(String typeName) { + if (typeName == null) { + return null; + } - public static ToscaPropertyType isValidType(String typeName) { - if (typeName == null) { - return null; - } + for (ToscaPropertyType type : ToscaPropertyType.values()) { + if (type.getType().equals(typeName)) { + return type; + } + } + return null; + } - for (ToscaPropertyType type : ToscaPropertyType.values()) { - if (type.getType().equals(typeName)) { - return type; - } - } - return null; - } + public static boolean isScalarType(String dataTypeName) { - public static boolean isScalarType(String dataTypeName) { + ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); - ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); + return isPrimitiveToscaType != null && !isPrimitiveToscaType.isAbstract(); - return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == false; + } - } - - public static boolean isPrimitiveType(String dataTypeName) { - - if (ToscaPropertyType.MAP.getType().equals(dataTypeName) || ToscaPropertyType.LIST.getType().equals(dataTypeName)){ - return false; - } - if(isScalarType(dataTypeName)){ - return true; - } - return false; - } - - public static ToscaPropertyType getTypeIfScalar(String dataTypeName) { - - ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); - - if (isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == false) { - return isPrimitiveToscaType; - } else { - return null; - } - - } - - @Override - public String toString() { - return name().toLowerCase(); - } + public static boolean isPrimitiveType(String dataTypeName) { + + if (ToscaPropertyType.MAP.getType().equals(dataTypeName) || ToscaPropertyType.LIST.getType().equals(dataTypeName)){ + return false; + } + if(isScalarType(dataTypeName)){ + return true; + } + return false; + } + + public static ToscaPropertyType getTypeIfScalar(String dataTypeName) { + + ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); + + if (isPrimitiveToscaType != null && !isPrimitiveToscaType.isAbstract()) { + return isPrimitiveToscaType; + } else { + return null; + } + + } + + @Override + public String toString() { + return name().toLowerCase(); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java index 88642f8240..92c564cad6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java @@ -30,91 +30,75 @@ import java.util.Locale; * @author mkv */ public enum ToscaType { - STRING, INTEGER, FLOAT, BOOLEAN, TIMESTAMP, VERSION; + STRING, INTEGER, FLOAT, BOOLEAN, TIMESTAMP, VERSION; - // private static final Pattern TIMESTAMP_REGEX = Pattern - // .compile("[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[0-9][0-9][0-9][0-9]-[0-9][0-9]?-[0-9][0-9]?([Tt]|[ - // \\t]+)[0-9][0-9]?:[0-9][0-9]:[0-9][0-9](\\.[0-9]*)?(([ \\t]*)Z|([ - // \\t]*)[-+][0-9][0-9]?(:[0-9][0-9])?)?"); + public boolean isValidValue(String value) { + switch (this) { + case BOOLEAN: + return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"); + case FLOAT: + return isFloat(value); + case INTEGER: + return isInteger(value); + case STRING: + return true; + case TIMESTAMP: + try { + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US).parse(value); + return true; + } catch (ParseException e) { + return false; + } + case VERSION: + return VersionUtil.isValid(value); + default: + return false; + } + } - public static ToscaType fromYamlTypeName(String typeName) { - if (typeName == null) { - return null; - } - try { - return ToscaType.valueOf(typeName.toUpperCase()); - } catch (IllegalArgumentException e) { - return null; - } - } + private boolean isFloat(String value) { + try { + Float.valueOf(value); + } catch (NumberFormatException e) { + return false; + } + return true; + } - public boolean isValidValue(String value) { - switch (this) { - case BOOLEAN: - return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"); - case FLOAT: - return isFloat(value); - case INTEGER: - return isInteger(value); - case STRING: - return true; - case TIMESTAMP: - try { - DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US).parse(value); - return true; - } catch (ParseException e) { - return false; - } - case VERSION: - return VersionUtil.isValid(value); - default: - return false; - } - } + private boolean isInteger(String value) { + try { + Long.valueOf(value); + } catch (NumberFormatException e) { + return false; + } + return true; + } - private boolean isFloat(String value) { - try { - Float.valueOf(value); - } catch (NumberFormatException e) { - return false; - } - return true; - } + public Object convert(String value) { + switch (this) { + case STRING: + return value; + case BOOLEAN: + return Boolean.valueOf(value); + case FLOAT: + return Double.valueOf(value); + case INTEGER: + return Long.valueOf(value); + case TIMESTAMP: + try { + return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US).parse(value); + } catch (ParseException e) { + throw new IllegalArgumentException("Value must be a valid timestamp", e); + } + case VERSION: + return VersionUtil.parseVersion(value); + default: + return null; + } + } - private boolean isInteger(String value) { - try { - Long.valueOf(value); - } catch (NumberFormatException e) { - return false; - } - return true; - } - - public Object convert(String value) { - switch (this) { - case STRING: - return value; - case BOOLEAN: - return Boolean.valueOf(value); - case FLOAT: - return Double.valueOf(value); - case INTEGER: - return Long.valueOf(value); - case TIMESTAMP: - try { - return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US).parse(value); - } catch (ParseException e) { - throw new IllegalArgumentException("Value must be a valid timestamp", e); - } - case VERSION: - return VersionUtil.parseVersion(value); - default: - return null; - } - } - - @Override - public String toString() { - return name().toLowerCase(); - } + @Override + public String toString() { + return name().toLowerCase(); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java index 91d806edd9..41b7a2e342 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java @@ -20,75 +20,75 @@ package org.openecomp.sdc.be.model.tosca; -import java.util.regex.Pattern; - import org.openecomp.sdc.be.model.tosca.version.ApplicationVersionException; import org.openecomp.sdc.be.model.tosca.version.Version; +import java.util.regex.Pattern; + public final class VersionUtil { - /** Utility class should not have public constructor. */ - private VersionUtil() { - } + /** Utility class should not have public constructor. */ + private VersionUtil() { + } - /** - * The version must begin with a bloc of numbers, and then it can have one - * or more bloc of numbers separated by '.' and then it can have alpha - * numeric bloc separated by '.' or '-' - */ - public static final Pattern VERSION_PATTERN = Pattern.compile("\\d+(?:\\.\\d+)*(?:[\\.-]\\p{Alnum}+)*"); - private static final String SNAPSHOT_IDENTIFIER = "SNAPSHOT"; + /** + * The version must begin with a bloc of numbers, and then it can have one + * or more bloc of numbers separated by '.' and then it can have alpha + * numeric bloc separated by '.' or '-' + */ + public static final Pattern VERSION_PATTERN = Pattern.compile("\\d+(?:\\.\\d+)*(?:[\\.-]\\p{Alnum}+)*"); + private static final String SNAPSHOT_IDENTIFIER = "SNAPSHOT"; - /** - * Check if a version is a SNAPSHOT (development) version. - * - * @param version - * The actual version string. - * @return True if the version is a SNAPSHOT version, false if not (RELEASE - * version). - */ - public static boolean isSnapshot(String version) { - return version.toUpperCase().contains(SNAPSHOT_IDENTIFIER); - } + /** + * Check if a version is a SNAPSHOT (development) version. + * + * @param version + * The actual version string. + * @return True if the version is a SNAPSHOT version, false if not (RELEASE + * version). + */ + public static boolean isSnapshot(String version) { + return version.toUpperCase().contains(SNAPSHOT_IDENTIFIER); + } - /** - * Check if a version is valid - * - * @param version - * version string to parse - * @return true if it's following the defined version pattern - */ - public static boolean isValid(String version) { - return VERSION_PATTERN.matcher(version).matches(); - } + /** + * Check if a version is valid + * + * @param version + * version string to parse + * @return true if it's following the defined version pattern + */ + public static boolean isValid(String version) { + return VERSION_PATTERN.matcher(version).matches(); + } - /** - * Parse the version's text to produce a comparable version object - * - * @param version - * version text to parse - * @return a comparable version object - * @throws ApplicationVersionException - * if the version text is not following the defined version - * pattern - */ - public static Version parseVersion(String version) { - if (!isValid(version)) { - throw new ApplicationVersionException( - "This version is not valid [" + version + "] as it does not match [" + VERSION_PATTERN + "]"); - } else { - return new Version(version); - } - } + /** + * Parse the version's text to produce a comparable version object + * + * @param version + * version text to parse + * @return a comparable version object + * @throws ApplicationVersionException + * if the version text is not following the defined version + * pattern + */ + public static Version parseVersion(String version) { + if (!isValid(version)) { + throw new ApplicationVersionException( + "This version is not valid [" + version + "] as it does not match [" + VERSION_PATTERN + "]"); + } else { + return new Version(version); + } + } - /** - * Compare 2 versions - * - * @param versionLeft - * @param versionRight - * @return - */ - public static int compare(String versionLeft, String versionRight) { - return parseVersion(versionLeft).compareTo(parseVersion(versionRight)); - } + /** + * Compare 2 versions + * + * @param versionLeft + * @param versionRight + * @return + */ + public static int compare(String versionLeft, String versionRight) { + return parseVersion(versionLeft).compareTo(parseVersion(versionRight)); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java index 7b46692253..1611356cc1 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java @@ -20,53 +20,46 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; @SuppressWarnings("rawtypes") -public abstract class AbstractComparablePropertyConstraint extends AbstractPropertyConstraint implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 2002627754053326321L; +public abstract class AbstractComparablePropertyConstraint extends AbstractPropertyConstraint { - private Comparable comparable; + private Comparable comparable; - protected Comparable getComparable() { - return comparable; - } + protected Comparable getComparable() { + return comparable; + } - protected void initialize(String rawTextValue, ToscaType propertyType) - throws ConstraintValueDoNotMatchPropertyTypeException { - // Perform verification that the property type is supported for - // comparison - ConstraintUtil.checkComparableType(propertyType); - // Check if the text value is valid for the property type - if (propertyType.isValidValue(rawTextValue)) { - // Convert the raw text value to a comparable value - comparable = ConstraintUtil.convertToComparable(propertyType, rawTextValue); - } else { - // Invalid value throw exception - throw new ConstraintValueDoNotMatchPropertyTypeException( - "The value [" + rawTextValue + "] is not valid for the type [" + propertyType + "]"); - } - } + protected void initialize(String rawTextValue, ToscaType propertyType) + throws ConstraintValueDoNotMatchPropertyTypeException { + // Perform verification that the property type is supported for + // comparison + ConstraintUtil.checkComparableType(propertyType); + // Check if the text value is valid for the property type + if (propertyType.isValidValue(rawTextValue)) { + // Convert the raw text value to a comparable value + comparable = ConstraintUtil.convertToComparable(propertyType, rawTextValue); + } else { + // Invalid value throw exception + throw new ConstraintValueDoNotMatchPropertyTypeException( + "The value [" + rawTextValue + "] is not valid for the type [" + propertyType + "]"); + } + } - protected abstract void doValidate(Object propertyValue) throws ConstraintViolationException; + protected abstract void doValidate(Object propertyValue) throws ConstraintViolationException; - @Override - public void validate(Object propertyValue) throws ConstraintViolationException { - if (propertyValue == null) { - throw new ConstraintViolationException("Value to check is null"); - } - if (!(comparable.getClass().isAssignableFrom(propertyValue.getClass()))) { - throw new ConstraintViolationException("Value to check is not comparable to reference type, value type [" - + propertyValue.getClass() + "], reference type [" + comparable.getClass() + "]"); - } - doValidate(propertyValue); - } + @Override + public void validate(Object propertyValue) throws ConstraintViolationException { + if (propertyValue == null) { + throw new ConstraintViolationException("Value to check is null"); + } + if (!(comparable.getClass().isAssignableFrom(propertyValue.getClass()))) { + throw new ConstraintViolationException("Value to check is not comparable to reference type, value type [" + + propertyValue.getClass() + "], reference type [" + comparable.getClass() + "]"); + } + doValidate(propertyValue); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java index 950a7fa9b9..fc96373d62 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java @@ -20,27 +20,20 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; import org.openecomp.sdc.be.model.tosca.version.ApplicationVersionException; -public abstract class AbstractPropertyConstraint implements PropertyConstraint, Serializable { - - /** - * - */ - private static final long serialVersionUID = 4459522275459723374L; +public abstract class AbstractPropertyConstraint implements PropertyConstraint { - @Override - public void validate(ToscaType toscaType, String propertyTextValue) throws ConstraintViolationException { - try { - validate(toscaType.convert(propertyTextValue)); - } catch (IllegalArgumentException | ApplicationVersionException e) { - throw new ConstraintViolationException( - "String value [" + propertyTextValue + "] is not valid for type [" + toscaType + "]", e); - } - } + @Override + public void validate(ToscaType toscaType, String propertyTextValue) throws ConstraintViolationException { + try { + validate(toscaType.convert(propertyTextValue)); + } catch (IllegalArgumentException | ApplicationVersionException e) { + throw new ConstraintViolationException( + "String value [" + propertyTextValue + "] is not valid for type [" + toscaType + "]", e); + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java index 142caa2017..8f54c68484 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java @@ -20,34 +20,27 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -public abstract class AbstractStringPropertyConstraint extends AbstractPropertyConstraint implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 6857605164938136232L; - - protected abstract void doValidate(String propertyValue) throws ConstraintViolationException; - - @Override - public void validate(Object propertyValue) throws ConstraintViolationException { - if (propertyValue == null) { - throw new ConstraintViolationException("Value to validate is null"); - } - if (!(propertyValue instanceof String)) { - throw new ConstraintViolationException("This constraint can only be applied on String value"); - } - doValidate((String) propertyValue); - } - - @Override - public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { - ConstraintUtil.checkStringType(propertyType); - } +public abstract class AbstractStringPropertyConstraint extends AbstractPropertyConstraint { + + protected abstract void doValidate(String propertyValue) throws ConstraintViolationException; + + @Override + public void validate(Object propertyValue) throws ConstraintViolationException { + if (propertyValue == null) { + throw new ConstraintViolationException("Value to validate is null"); + } + if (!(propertyValue instanceof String)) { + throw new ConstraintViolationException("This constraint can only be applied on String value"); + } + doValidate((String) propertyValue); + } + + @Override + public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + ConstraintUtil.checkStringType(propertyType); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java index 5f19d15293..c78afd8b4a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java @@ -25,36 +25,36 @@ import java.util.List; public enum ConstraintType { - IN_RANGE("inRange"), + IN_RANGE("inRange"), - GREATER_THAN("greaterThan", "greater_than"), + GREATER_THAN("greaterThan", "greater_than"), - GREATER_OR_EQUAL("greaterOrEqual", "greater_or_equal"), + GREATER_OR_EQUAL("greaterOrEqual", "greater_or_equal"), - LESS_OR_EQUAL("lessOrEqual", "less_or_equal"), + LESS_OR_EQUAL("lessOrEqual", "less_or_equal"), - MIN_LENGTH("minLength", "min_length"), + MIN_LENGTH("minLength", "min_length"), - VALID_VALUES("validValues", "valid_values"), + VALID_VALUES("validValues", "valid_values"), - LESS_THAN("lessThan", "less_than"); + LESS_THAN("lessThan", "less_than"); - List<String> types; + List<String> types; - private ConstraintType(String... types) { - this.types = Arrays.asList(types); - } + private ConstraintType(String... types) { + this.types = Arrays.asList(types); + } - public List<String> getTypes() { - return types; - } + public List<String> getTypes() { + return types; + } - public static ConstraintType getByType(String type) { - for (ConstraintType inst : ConstraintType.values()) { - if (inst.getTypes().contains(type)) { - return inst; - } - } - return null; - } + public static ConstraintType getByType(String type) { + for (ConstraintType inst : ConstraintType.values()) { + if (inst.getTypes().contains(type)) { + return inst; + } + } + return null; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java index 79ac5caf25..3c1f0ab711 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java @@ -20,126 +20,126 @@ package org.openecomp.sdc.be.model.tosca.constraints; +import org.openecomp.sdc.be.model.tosca.ToscaType; +import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; + import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; -import org.openecomp.sdc.be.model.tosca.ToscaType; -import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; - /** * Utility class to validate constraints types. */ public final class ConstraintUtil { - private ConstraintUtil() { - } + private ConstraintUtil() { + } - /** - * Validates that the {@link ToscaType} specified is a - * {@link ToscaType#STRING}. - * - * @param propertyType - * The property tosca type. - * @throws ConstraintValueDoNotMatchPropertyTypeException - * In case the type is not {@link ToscaType#STRING}. - */ - public static void checkStringType(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { - if (!ToscaType.STRING.equals(propertyType)) { - throw new ConstraintValueDoNotMatchPropertyTypeException( - "Invalid property type <" + propertyType.toString() + ">"); - } - } + /** + * Validates that the {@link ToscaType} specified is a + * {@link ToscaType#STRING}. + * + * @param propertyType + * The property tosca type. + * @throws ConstraintValueDoNotMatchPropertyTypeException + * In case the type is not {@link ToscaType#STRING}. + */ + public static void checkStringType(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + if (!ToscaType.STRING.equals(propertyType)) { + throw new ConstraintValueDoNotMatchPropertyTypeException( + "Invalid property type <" + propertyType.toString() + ">"); + } + } - /** - * Verify that the given tosca type is supported for comparison - * - * @param propertyType - * the tosca type to check - * @throws ConstraintValueDoNotMatchPropertyTypeException - * if the property type cannot be compared - */ - public static void checkComparableType(ToscaType propertyType) - throws ConstraintValueDoNotMatchPropertyTypeException { - // The validity of the value is already assured by us with our - // ToscaType.convert() method - // here we just want to check that the constraint is not used on - // unsupported type as boolean - switch (propertyType) { - case FLOAT: - case INTEGER: - case TIMESTAMP: - case VERSION: - break; - case STRING: - case BOOLEAN: - throw new ConstraintValueDoNotMatchPropertyTypeException( - "Constraint is invalid for property type <" + propertyType.toString() + ">"); - default: - throw new ConstraintValueDoNotMatchPropertyTypeException( - "Invalid property type <" + propertyType.toString() + ">"); - } - } + /** + * Verify that the given tosca type is supported for comparison + * + * @param propertyType + * the tosca type to check + * @throws ConstraintValueDoNotMatchPropertyTypeException + * if the property type cannot be compared + */ + public static void checkComparableType(ToscaType propertyType) + throws ConstraintValueDoNotMatchPropertyTypeException { + // The validity of the value is already assured by us with our + // ToscaType.convert() method + // here we just want to check that the constraint is not used on + // unsupported type as boolean + switch (propertyType) { + case FLOAT: + case INTEGER: + case TIMESTAMP: + case VERSION: + break; + case STRING: + case BOOLEAN: + throw new ConstraintValueDoNotMatchPropertyTypeException( + "Constraint is invalid for property type <" + propertyType.toString() + ">"); + default: + throw new ConstraintValueDoNotMatchPropertyTypeException( + "Invalid property type <" + propertyType.toString() + ">"); + } + } - /** - * Convert a string value following its type throw exception if it cannot be - * converted to a comparable - * - * @param propertyType - * the type of the property - * @param value - * the value to convert - * @return the converted comparable - * @throws ConstraintValueDoNotMatchPropertyTypeException - * if the converted value is not a comparable - */ - @SuppressWarnings("rawtypes") - public static Comparable convertToComparable(ToscaType propertyType, String value) - throws ConstraintValueDoNotMatchPropertyTypeException { - Object comparableObj = propertyType.convert(value); - if (!(comparableObj instanceof Comparable)) { - throw new IllegalArgumentException( - "Try to convert a value of a type which is not comparable [" + propertyType + "] to Comparable"); - } else { - return (Comparable) comparableObj; - } - } + /** + * Convert a string value following its type throw exception if it cannot be + * converted to a comparable + * + * @param propertyType + * the type of the property + * @param value + * the value to convert + * @return the converted comparable + * @throws ConstraintValueDoNotMatchPropertyTypeException + * if the converted value is not a comparable + */ + @SuppressWarnings("rawtypes") + public static Comparable convertToComparable(ToscaType propertyType, String value) + throws ConstraintValueDoNotMatchPropertyTypeException { + Object comparableObj = propertyType.convert(value); + if (!(comparableObj instanceof Comparable)) { + throw new IllegalArgumentException( + "Try to convert a value of a type which is not comparable [" + propertyType + "] to Comparable"); + } else { + return (Comparable) comparableObj; + } + } - public static class ConstraintInformation { - public ConstraintInformation(String name, Object reference, String value, String type) { + public static class ConstraintInformation { + public ConstraintInformation(String name, Object reference, String value, String type) { - this.name = name; - this.reference = reference; - this.value = value; - this.type = type; + this.name = name; + this.reference = reference; + this.value = value; + this.type = type; - } + } - private String name; - private Object reference; - private String value; - private String type; - } + private String name; + private Object reference; + private String value; + private String type; + } - public static ConstraintInformation getConstraintInformation(Object constraint) throws IntrospectionException { - PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(constraint.getClass()) - .getPropertyDescriptors(); - PropertyDescriptor firstDescriptor = null; - for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { - if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) { - firstDescriptor = propertyDescriptor; - break; - } - } - if (firstDescriptor == null) { - throw new IntrospectionException("Cannot find constraint name"); - } - try { - return new ConstraintInformation(firstDescriptor.getName(), - firstDescriptor.getReadMethod().invoke(constraint), null, null); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new IntrospectionException("Cannot retrieve constraint reference " + e.getMessage()); - } - } + public static ConstraintInformation getConstraintInformation(Object constraint) throws IntrospectionException { + PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(constraint.getClass()) + .getPropertyDescriptors(); + PropertyDescriptor firstDescriptor = null; + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) { + firstDescriptor = propertyDescriptor; + break; + } + } + if (firstDescriptor == null) { + throw new IntrospectionException("Cannot find constraint name"); + } + try { + return new ConstraintInformation(firstDescriptor.getName(), + firstDescriptor.getReadMethod().invoke(constraint), null, null); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new IntrospectionException("Cannot retrieve constraint reference " + e.getMessage()); + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java index 530dcb0cc6..7ae64e0ccf 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java @@ -20,58 +20,50 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - -import javax.validation.constraints.NotNull; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -//import com.fasterxml.jackson.annotation.JsonIgnore; +import javax.validation.constraints.NotNull; -public class EqualConstraint extends AbstractPropertyConstraint implements Serializable { - /** - * - */ - private static final long serialVersionUID = -1596093341744641483L; +public class EqualConstraint extends AbstractPropertyConstraint { - @NotNull - private String equal; + @NotNull + private String equal; - // @JsonIgnore - private Object typed; + // @JsonIgnore + private Object typed; - public EqualConstraint(String equal) { - super(); - this.equal = equal; - } + public EqualConstraint(String equal) { + super(); + this.equal = equal; + } - @Override - public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { - if (propertyType.isValidValue(equal)) { - typed = propertyType.convert(equal); - } else { - throw new ConstraintValueDoNotMatchPropertyTypeException("equal constraint has invalid value <" + equal - + "> property type is <" + propertyType.toString() + ">"); - } - } + @Override + public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + if (propertyType.isValidValue(equal)) { + typed = propertyType.convert(equal); + } else { + throw new ConstraintValueDoNotMatchPropertyTypeException("equal constraint has invalid value <" + equal + + "> property type is <" + propertyType.toString() + ">"); + } + } - @Override - public void validate(Object propertyValue) throws ConstraintViolationException { - if (propertyValue == null) { - if (typed != null) { - fail(null); - } - } else if (typed == null) { - fail(propertyValue); - } else if (!typed.equals(propertyValue)) { - fail(propertyValue); - } - } + @Override + public void validate(Object propertyValue) throws ConstraintViolationException { + if (propertyValue == null) { + if (typed != null) { + fail(null); + } + } else if (typed == null) { + fail(propertyValue); + } else if (!typed.equals(propertyValue)) { + fail(propertyValue); + } + } - private void fail(Object propertyValue) throws ConstraintViolationException { - throw new ConstraintViolationException("Equal constraint violation, the reference is <" + equal - + "> but the value to compare is <" + propertyValue + ">"); - } + private void fail(Object propertyValue) throws ConstraintViolationException { + throw new ConstraintViolationException("Equal constraint violation, the reference is <" + equal + + "> but the value to compare is <" + propertyValue + ">"); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java index 4f2c3ad9ca..63d7ed8872 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java @@ -20,37 +20,30 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - -import javax.validation.constraints.NotNull; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -public class GreaterOrEqualConstraint extends AbstractComparablePropertyConstraint implements Serializable { - /** - * - */ - private static final long serialVersionUID = -5937851077034490609L; - - @NotNull - private String greaterOrEqual; - - public GreaterOrEqualConstraint(String greaterOrEqual) { - super(); - this.greaterOrEqual = greaterOrEqual; - } - - @Override - public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { - initialize(greaterOrEqual, propertyType); - } - - @Override - protected void doValidate(Object propertyValue) throws ConstraintViolationException { - if (getComparable().compareTo(propertyValue) > 0) { - throw new ConstraintViolationException(propertyValue + " <= " + greaterOrEqual); - } - } +import javax.validation.constraints.NotNull; + +public class GreaterOrEqualConstraint extends AbstractComparablePropertyConstraint { + + @NotNull + private String greaterOrEqual; + + public GreaterOrEqualConstraint(String greaterOrEqual) { + this.greaterOrEqual = greaterOrEqual; + } + + @Override + public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + initialize(greaterOrEqual, propertyType); + } + + @Override + protected void doValidate(Object propertyValue) throws ConstraintViolationException { + if (getComparable().compareTo(propertyValue) > 0) { + throw new ConstraintViolationException(propertyValue + " <= " + greaterOrEqual); + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java index aea2a201ab..b599a16a10 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java @@ -20,47 +20,39 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - -import javax.validation.constraints.NotNull; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -public class GreaterThanConstraint extends AbstractComparablePropertyConstraint implements Serializable { +import javax.validation.constraints.NotNull; - /** - * - */ - private static final long serialVersionUID = 405723215512121896L; +public class GreaterThanConstraint extends AbstractComparablePropertyConstraint { - public GreaterThanConstraint(String greaterThan) { - super(); - this.greaterThan = greaterThan; - } + public GreaterThanConstraint(String greaterThan) { + this.greaterThan = greaterThan; + } - @NotNull - private String greaterThan; + @NotNull + private String greaterThan; - @Override - public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { - initialize(greaterThan, propertyType); - } + @Override + public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + initialize(greaterThan, propertyType); + } - @Override - protected void doValidate(Object propertyValue) throws ConstraintViolationException { - if (getComparable().compareTo(propertyValue) >= 0) { - throw new ConstraintViolationException(propertyValue + " < " + greaterThan); - } - } + @Override + protected void doValidate(Object propertyValue) throws ConstraintViolationException { + if (getComparable().compareTo(propertyValue) >= 0) { + throw new ConstraintViolationException(propertyValue + " < " + greaterThan); + } + } - public String getGreaterThan() { - return greaterThan; - } + public String getGreaterThan() { + return greaterThan; + } - public void setGreaterThan(String greaterThan) { - this.greaterThan = greaterThan; - } + public void setGreaterThan(String greaterThan) { + this.greaterThan = greaterThan; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java index e8821c2c21..19a2fe4230 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java @@ -20,111 +20,95 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; -import java.util.List; - -import javax.validation.constraints.NotNull; - +import com.google.common.collect.Lists; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -//import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.collect.Lists; - -public class InRangeConstraint extends AbstractPropertyConstraint implements Serializable { - - /** - * - */ - private static final long serialVersionUID = -8038401707152824493L; - - private List<String> inRange; - - private Comparable min; - private Comparable max; - - public InRangeConstraint(List<String> inRange) { - super(); - this.inRange = inRange; - } - - public InRangeConstraint() { - super(); - } - - @Override - public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { - // Perform verification that the property type is supported for - // comparison - ConstraintUtil.checkComparableType(propertyType); - if (inRange == null || inRange.size() != 2) { - throw new ConstraintValueDoNotMatchPropertyTypeException("In range constraint must have two elements."); - } - String minRawText = inRange.get(0); - String maxRawText = inRange.get(1); - if (!propertyType.isValidValue(minRawText)) { - throw new ConstraintValueDoNotMatchPropertyTypeException("Invalid min value for in range constraint [" - + minRawText + "] as it does not follow the property type [" + propertyType + "]"); - } - if (!propertyType.isValidValue(maxRawText)) { - throw new ConstraintValueDoNotMatchPropertyTypeException("Invalid max value for in range constraint [" - + maxRawText + "] as it does not follow the property type [" + propertyType + "]"); - } - min = ConstraintUtil.convertToComparable(propertyType, minRawText); - max = ConstraintUtil.convertToComparable(propertyType, maxRawText); - } - - @Override - public void validate(Object propertyValue) throws ConstraintViolationException { - if (propertyValue == null) { - throw new ConstraintViolationException("Value to check is null"); - } - if (!(min.getClass().isAssignableFrom(propertyValue.getClass()))) { - throw new ConstraintViolationException("Value to check is not comparable to range type, value type [" - + propertyValue.getClass() + "], range type [" + min.getClass() + "]"); - } - if (min.compareTo(propertyValue) > 0 || max.compareTo(propertyValue) < 0) { - throw new ConstraintViolationException("The value [" + propertyValue + "] is out of range " + inRange); - } - } - - // @JsonProperty - @NotNull - public String getRangeMinValue() { - if (inRange != null) { - return inRange.get(0); - } else { - return null; - } - } - - // @JsonProperty - public void setRangeMinValue(String minValue) { - if (inRange == null) { - inRange = Lists.newArrayList(minValue, ""); - } else { - inRange.set(0, minValue); - } - } - - // @JsonProperty - @NotNull - public String getRangeMaxValue() { - if (inRange != null) { - return inRange.get(1); - } else { - return null; - } - } +import javax.validation.constraints.NotNull; +import java.util.List; - // @JsonProperty - public void setRangeMaxValue(String maxValue) { - if (inRange == null) { - inRange = Lists.newArrayList("", maxValue); - } else { - inRange.set(1, maxValue); - } - } +public class InRangeConstraint extends AbstractPropertyConstraint { + + private List<String> inRange; + + private Comparable min; + private Comparable max; + + public InRangeConstraint(List<String> inRange) { + this.inRange = inRange; + } + + public InRangeConstraint() { } + + @Override + public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + // Perform verification that the property type is supported for + // comparison + ConstraintUtil.checkComparableType(propertyType); + if (inRange == null || inRange.size() != 2) { + throw new ConstraintValueDoNotMatchPropertyTypeException("In range constraint must have two elements."); + } + String minRawText = inRange.get(0); + String maxRawText = inRange.get(1); + if (!propertyType.isValidValue(minRawText)) { + throw new ConstraintValueDoNotMatchPropertyTypeException("Invalid min value for in range constraint [" + + minRawText + "] as it does not follow the property type [" + propertyType + "]"); + } + if (!propertyType.isValidValue(maxRawText)) { + throw new ConstraintValueDoNotMatchPropertyTypeException("Invalid max value for in range constraint [" + + maxRawText + "] as it does not follow the property type [" + propertyType + "]"); + } + min = ConstraintUtil.convertToComparable(propertyType, minRawText); + max = ConstraintUtil.convertToComparable(propertyType, maxRawText); + } + + @Override + public void validate(Object propertyValue) throws ConstraintViolationException { + if (propertyValue == null) { + throw new ConstraintViolationException("Value to check is null"); + } + if (!(min.getClass().isAssignableFrom(propertyValue.getClass()))) { + throw new ConstraintViolationException("Value to check is not comparable to range type, value type [" + + propertyValue.getClass() + "], range type [" + min.getClass() + "]"); + } + if (min.compareTo(propertyValue) > 0 || max.compareTo(propertyValue) < 0) { + throw new ConstraintViolationException("The value [" + propertyValue + "] is out of range " + inRange); + } + } + + @NotNull + public String getRangeMinValue() { + if (inRange != null) { + return inRange.get(0); + } else { + return null; + } + } + + public void setRangeMinValue(String minValue) { + if (inRange == null) { + inRange = Lists.newArrayList(minValue, ""); + } else { + inRange.set(0, minValue); + } + } + + @NotNull + public String getRangeMaxValue() { + if (inRange != null) { + return inRange.get(1); + } else { + return null; + } + } + + public void setRangeMaxValue(String maxValue) { + if (inRange == null) { + inRange = Lists.newArrayList("", maxValue); + } else { + inRange.set(1, maxValue); + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java index 2ba0071f2f..c07ac7e2e3 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java @@ -20,35 +20,28 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - -import javax.validation.constraints.NotNull; - import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -public class LengthConstraint extends AbstractStringPropertyConstraint implements Serializable { +import javax.validation.constraints.NotNull; - /** - * - */ - private static final long serialVersionUID = 6249912030281791233L; +public class LengthConstraint extends AbstractStringPropertyConstraint { - @NotNull - private Integer length; + @NotNull + private Integer length; - @Override - protected void doValidate(String propertyValue) throws ConstraintViolationException { - if (propertyValue.length() != length) { - throw new ConstraintViolationException("The length of the value is not equals to [" + length + "]"); - } - } + @Override + protected void doValidate(String propertyValue) throws ConstraintViolationException { + if (propertyValue.length() != length) { + throw new ConstraintViolationException("The length of the value is not equals to [" + length + "]"); + } + } - public Integer getLength() { - return length; - } + public Integer getLength() { + return length; + } - public void setLength(Integer length) { - this.length = length; - } + public void setLength(Integer length) { + this.length = length; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java index 1491fe327d..7d61dd31df 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java @@ -20,51 +20,39 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - -import javax.validation.constraints.NotNull; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -//import alien4cloud.json.deserializer.TextDeserializer; -//import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -public class LessOrEqualConstraint extends AbstractComparablePropertyConstraint implements Serializable { +import javax.validation.constraints.NotNull; - /** - * - */ - private static final long serialVersionUID = -4907864317687138678L; +public class LessOrEqualConstraint extends AbstractComparablePropertyConstraint { - // @JsonDeserialize(using = TextDeserializer.class) - @NotNull - private String lessOrEqual; + @NotNull + private String lessOrEqual; - public LessOrEqualConstraint(String lessOrEqual) { - super(); - this.lessOrEqual = lessOrEqual; - } + public LessOrEqualConstraint(String lessOrEqual) { + this.lessOrEqual = lessOrEqual; + } - @Override - public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { - initialize(lessOrEqual, propertyType); - } + @Override + public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + initialize(lessOrEqual, propertyType); + } - @Override - protected void doValidate(Object propertyValue) throws ConstraintViolationException { - if (getComparable().compareTo(propertyValue) < 0) { - throw new ConstraintViolationException(propertyValue + " >= " + lessOrEqual); - } - } + @Override + protected void doValidate(Object propertyValue) throws ConstraintViolationException { + if (getComparable().compareTo(propertyValue) < 0) { + throw new ConstraintViolationException(propertyValue + " >= " + lessOrEqual); + } + } - public String getLessOrEqual() { - return lessOrEqual; - } + public String getLessOrEqual() { + return lessOrEqual; + } - public void setLessOrEqual(String lessOrEqual) { - this.lessOrEqual = lessOrEqual; - } + public void setLessOrEqual(String lessOrEqual) { + this.lessOrEqual = lessOrEqual; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java index 2fc43febbf..e2db77b45a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java @@ -20,39 +20,31 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - -import javax.validation.constraints.NotNull; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -public class LessThanConstraint extends AbstractComparablePropertyConstraint implements Serializable { +import javax.validation.constraints.NotNull; - /** - * - */ - private static final long serialVersionUID = 2267623014703859501L; +public class LessThanConstraint extends AbstractComparablePropertyConstraint { - @NotNull - private String lessThan; + @NotNull + private String lessThan; - public LessThanConstraint(String lessThan) { - super(); - this.lessThan = lessThan; - } + public LessThanConstraint(String lessThan) { + this.lessThan = lessThan; + } - @Override - public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { - initialize(lessThan, propertyType); - } + @Override + public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + initialize(lessThan, propertyType); + } - @Override - protected void doValidate(Object propertyValue) throws ConstraintViolationException { - if (getComparable().compareTo(propertyValue) <= 0) { - throw new ConstraintViolationException(propertyValue + " > " + lessThan); - } - } + @Override + protected void doValidate(Object propertyValue) throws ConstraintViolationException { + if (getComparable().compareTo(propertyValue) <= 0) { + throw new ConstraintViolationException(propertyValue + " > " + lessThan); + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java index b6a80afced..8b7ce49cbc 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java @@ -20,42 +20,35 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - -import javax.validation.constraints.NotNull; - import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -public class MaxLengthConstraint extends AbstractStringPropertyConstraint implements Serializable { +import javax.validation.constraints.NotNull; - /** - * - */ - private static final long serialVersionUID = 6377603705670201256L; +public class MaxLengthConstraint extends AbstractStringPropertyConstraint { - @NotNull - private Integer maxLength; + @NotNull + private Integer maxLength; - public MaxLengthConstraint(Integer maxLength) { - this.maxLength = maxLength; - } + public MaxLengthConstraint(Integer maxLength) { + this.maxLength = maxLength; + } - public MaxLengthConstraint() { - super(); - } + public MaxLengthConstraint() { + super(); + } - @Override - protected void doValidate(String propertyValue) throws ConstraintViolationException { - if (propertyValue.length() > maxLength) { - throw new ConstraintViolationException("The length of the value is greater than [" + maxLength + "]"); - } - } + @Override + protected void doValidate(String propertyValue) throws ConstraintViolationException { + if (propertyValue.length() > maxLength) { + throw new ConstraintViolationException("The length of the value is greater than [" + maxLength + "]"); + } + } - public Integer getMaxLength() { - return maxLength; - } + public Integer getMaxLength() { + return maxLength; + } - public void setMaxLength(Integer maxLength) { - this.maxLength = maxLength; - } + public void setMaxLength(Integer maxLength) { + this.maxLength = maxLength; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java index f92e5fbb2c..bc51f4fa5a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java @@ -20,43 +20,36 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; - -import javax.validation.constraints.NotNull; - import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -public class MinLengthConstraint extends AbstractStringPropertyConstraint implements Serializable { +import javax.validation.constraints.NotNull; - /** - * - */ - private static final long serialVersionUID = 32422424680811240L; +public class MinLengthConstraint extends AbstractStringPropertyConstraint { - @NotNull - private Integer minLength; + @NotNull + private Integer minLength; - public MinLengthConstraint(Integer minLength) { - this.minLength = minLength; - } + public MinLengthConstraint(Integer minLength) { + this.minLength = minLength; + } - public MinLengthConstraint() { - super(); - } + public MinLengthConstraint() { + super(); + } - @Override - protected void doValidate(String propertyValue) throws ConstraintViolationException { - if (propertyValue.length() < minLength) { - throw new ConstraintViolationException("The length of the value is less than [" + minLength + "]"); - } - } + @Override + protected void doValidate(String propertyValue) throws ConstraintViolationException { + if (propertyValue.length() < minLength) { + throw new ConstraintViolationException("The length of the value is less than [" + minLength + "]"); + } + } - public Integer getMinLength() { - return minLength; - } + public Integer getMinLength() { + return minLength; + } - public void setMinLength(Integer minLength) { - this.minLength = minLength; - } + public void setMinLength(Integer minLength) { + this.minLength = minLength; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java index c85c1601e4..db26c33440 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java @@ -20,37 +20,27 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; -import java.util.regex.Pattern; - -import javax.validation.constraints.NotNull; - import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -//import com.fasterxml.jackson.annotation.JsonIgnore; - -public class PatternConstraint extends AbstractStringPropertyConstraint implements Serializable { +import javax.validation.constraints.NotNull; +import java.util.regex.Pattern; - /** - * - */ - private static final long serialVersionUID = 8708185294968697107L; +public class PatternConstraint extends AbstractStringPropertyConstraint { - @NotNull - private String pattern; + @NotNull + private String pattern; - // @JsonIgnore - private Pattern compiledPattern; + private Pattern compiledPattern; - public void setPattern(String pattern) { - this.pattern = pattern; - this.compiledPattern = Pattern.compile(this.pattern); - } + public void setPattern(String pattern) { + this.pattern = pattern; + this.compiledPattern = Pattern.compile(this.pattern); + } - @Override - protected void doValidate(String propertyValue) throws ConstraintViolationException { - if (!compiledPattern.matcher(propertyValue).matches()) { - throw new ConstraintViolationException("The value do not match pattern " + pattern); - } - } + @Override + protected void doValidate(String propertyValue) throws ConstraintViolationException { + if (!compiledPattern.matcher(propertyValue).matches()) { + throw new ConstraintViolationException("The value do not match pattern " + pattern); + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java index 738f5150e3..0b35a9be8e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java @@ -20,73 +20,61 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.io.Serializable; -import java.util.List; -import java.util.Set; - -import javax.validation.constraints.NotNull; - +import com.google.common.collect.Sets; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; -//import com.fasterxml.jackson.annotation.JsonIgnore; -import com.google.common.collect.Sets; - -public class ValidValuesConstraint extends AbstractPropertyConstraint implements Serializable { +import javax.validation.constraints.NotNull; +import java.util.List; +import java.util.Set; - /** - * - */ - private static final long serialVersionUID = 5906087180079892853L; +public class ValidValuesConstraint extends AbstractPropertyConstraint { - @NotNull - private List<String> validValues; - // @JsonIgnore - private Set<Object> validValuesTyped; + @NotNull + private List<String> validValues; + private Set<Object> validValuesTyped; - public ValidValuesConstraint(List<String> validValues) { - super(); - this.validValues = validValues; - } + public ValidValuesConstraint(List<String> validValues) { + this.validValues = validValues; + } - public ValidValuesConstraint() { - super(); - } + public ValidValuesConstraint() { + } - @Override - public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { - validValuesTyped = Sets.newHashSet(); - if (validValues == null) { - throw new ConstraintValueDoNotMatchPropertyTypeException( - "validValues constraint has invalid value <> property type is <" + propertyType.toString() + ">"); - } - for (String value : validValues) { - if (!propertyType.isValidValue(value)) { - throw new ConstraintValueDoNotMatchPropertyTypeException("validValues constraint has invalid value <" - + value + "> property type is <" + propertyType.toString() + ">"); - } else { - validValuesTyped.add(propertyType.convert(value)); - } - } - } + @Override + public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + validValuesTyped = Sets.newHashSet(); + if (validValues == null) { + throw new ConstraintValueDoNotMatchPropertyTypeException( + "validValues constraint has invalid value <> property type is <" + propertyType.toString() + ">"); + } + for (String value : validValues) { + if (!propertyType.isValidValue(value)) { + throw new ConstraintValueDoNotMatchPropertyTypeException("validValues constraint has invalid value <" + + value + "> property type is <" + propertyType.toString() + ">"); + } else { + validValuesTyped.add(propertyType.convert(value)); + } + } + } - @Override - public void validate(Object propertyValue) throws ConstraintViolationException { - if (propertyValue == null) { - throw new ConstraintViolationException("Value to validate is null"); - } - if (!validValuesTyped.contains(propertyValue)) { - throw new ConstraintViolationException("The value is not in the list of valid values"); - } - } + @Override + public void validate(Object propertyValue) throws ConstraintViolationException { + if (propertyValue == null) { + throw new ConstraintViolationException("Value to validate is null"); + } + if (!validValuesTyped.contains(propertyValue)) { + throw new ConstraintViolationException("The value is not in the list of valid values"); + } + } - public List<String> getValidValues() { - return validValues; - } + public List<String> getValidValues() { + return validValues; + } - public void setValidValues(List<String> validValues) { - this.validValues = validValues; - } + public void setValidValues(List<String> validValues) { + this.validValues = validValues; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java index c4237e9bcb..a29bb01074 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java @@ -30,21 +30,19 @@ import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInf */ public class ConstraintFunctionalException extends FunctionalException { - private static final long serialVersionUID = 1L; + protected final transient ConstraintInformation constraintInformation; - protected ConstraintInformation constraintInformation; + public ConstraintFunctionalException(String message, Throwable cause) { + this(message, cause, null); + } - public ConstraintFunctionalException(String message, Throwable cause) { - super(message, cause); - } + public ConstraintFunctionalException(String message) { + this(message, null, null); + } - public ConstraintFunctionalException(String message) { - super(message); - } - - public ConstraintFunctionalException(String message, Throwable cause, ConstraintInformation constraintInformation) { - super(message, cause); - this.constraintInformation = constraintInformation; - } + public ConstraintFunctionalException(String message, Throwable cause, ConstraintInformation constraintInformation) { + super(message, cause); + this.constraintInformation = constraintInformation; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java index 338e4aa51a..5c97a477c6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java @@ -30,20 +30,16 @@ import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInf */ public class ConstraintRequiredParameterException extends ConstraintFunctionalException { - private static final long serialVersionUID = 1L; + public ConstraintRequiredParameterException(String message) { + super(message); + } - public ConstraintRequiredParameterException(String message) { - super(message); - } + public ConstraintRequiredParameterException(String message, Throwable cause) { + super(message, cause); + } - public ConstraintRequiredParameterException(String message, Throwable cause) { - super(message, cause); - } - - public ConstraintRequiredParameterException(String message, Throwable cause, - ConstraintInformation constraintInformation) { - super(message, cause); - this.constraintInformation = constraintInformation; - } + public ConstraintRequiredParameterException(String message, Throwable cause, ConstraintInformation constraintInformation) { + super(message, cause, constraintInformation); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java index 3816ac61dd..f669e8429b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java @@ -28,14 +28,11 @@ package org.openecomp.sdc.be.model.tosca.constraints.exception; */ public class ConstraintTechnicalException extends Exception { - private static final long serialVersionUID = 5829360730980521567L; - - public ConstraintTechnicalException(String message, Throwable cause) { - super(message, cause); - } - - public ConstraintTechnicalException(String message) { - super(message); - } + public ConstraintTechnicalException(String message, Throwable cause) { + super(message, cause); + } + public ConstraintTechnicalException(String message) { + super(message); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java index 10d4e44fe2..4adefb96de 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java @@ -30,19 +30,15 @@ import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInf */ public class ConstraintValueDoNotMatchPropertyTypeException extends ConstraintFunctionalException { - private static final long serialVersionUID = 4342613849660957651L; + public ConstraintValueDoNotMatchPropertyTypeException(String message) { + super(message); + } - public ConstraintValueDoNotMatchPropertyTypeException(String message) { - super(message); - } + public ConstraintValueDoNotMatchPropertyTypeException(String message, Throwable cause) { + super(message, cause); + } - public ConstraintValueDoNotMatchPropertyTypeException(String message, Throwable cause) { - super(message, cause); - } - - public ConstraintValueDoNotMatchPropertyTypeException(String message, Throwable cause, - ConstraintInformation constraintInformation) { - super(message, cause); - this.constraintInformation = constraintInformation; - } + public ConstraintValueDoNotMatchPropertyTypeException(String message, Throwable cause, ConstraintInformation constraintInformation) { + super(message, cause, constraintInformation); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java index 29db0aa1af..3101b7b521 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java @@ -30,19 +30,16 @@ import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInf */ public class ConstraintViolationException extends ConstraintFunctionalException { - private static final long serialVersionUID = 1L; + public ConstraintViolationException(String message) { + super(message); + } - public ConstraintViolationException(String message) { - super(message); - } + public ConstraintViolationException(String message, Throwable cause) { + super(message, cause); + } - public ConstraintViolationException(String message, Throwable cause) { - super(message, cause); - } - - public ConstraintViolationException(String message, Throwable cause, ConstraintInformation constraintInformation) { - super(message, cause); - this.constraintInformation = constraintInformation; - } + public ConstraintViolationException(String message, Throwable cause, ConstraintInformation constraintInformation) { + super(message, cause, constraintInformation); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java index 1454306e89..4ffc5f030b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java @@ -29,13 +29,11 @@ package org.openecomp.sdc.be.model.tosca.constraints.exception; */ public class FunctionalException extends Exception { - private static final long serialVersionUID = 6712845685798792493L; + public FunctionalException(String message, Throwable cause) { + super(message, cause); + } - public FunctionalException(String message, Throwable cause) { - super(message, cause); - } - - public FunctionalException(String message) { - super(message); - } + public FunctionalException(String message) { + super(message); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java index 2b231d98e3..f4d920bea2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java @@ -28,13 +28,11 @@ package org.openecomp.sdc.be.model.tosca.constraints.exception; */ public class InvalidPropertyConstraintImplementationException extends ConstraintTechnicalException { - private static final long serialVersionUID = 2797550944328544706L; + public InvalidPropertyConstraintImplementationException(String message, Throwable cause) { + super(message, cause); + } - public InvalidPropertyConstraintImplementationException(String message, Throwable cause) { - super(message, cause); - } - - public InvalidPropertyConstraintImplementationException(String message) { - super(message); - } + public InvalidPropertyConstraintImplementationException(String message) { + super(message); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java index 1bddeea69b..5d369a08a4 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java @@ -28,13 +28,11 @@ package org.openecomp.sdc.be.model.tosca.constraints.exception; */ public abstract class TechnicalException extends RuntimeException { - private static final long serialVersionUID = -9152473183025390161L; + public TechnicalException(String message, Throwable cause) { + super(message, cause); + } - public TechnicalException(String message, Throwable cause) { - super(message, cause); - } - - public TechnicalException(String message) { - super(message); - } + public TechnicalException(String message) { + super(message); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java index f721efb3c9..9ff43926a4 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java @@ -20,23 +20,23 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class BooleanConverter implements ToscaValueConverter { - private static BooleanConverter booleanConverter = new BooleanConverter(); + private static BooleanConverter booleanConverter = new BooleanConverter(); - public static BooleanConverter getInstance() { - return booleanConverter; - } + public static BooleanConverter getInstance() { + return booleanConverter; + } - private BooleanConverter() { + private BooleanConverter() { - } + } - @Override - public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - return Boolean.valueOf(value); - } + @Override + public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + return Boolean.valueOf(value); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java index 32929beb5f..f3b842e0cf 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java @@ -1,19 +1,18 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.io.StringReader; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.common.util.JsonUtils; - import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.common.util.JsonUtils; + +import java.io.StringReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class DataTypePropertyConverter { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java index c190298b52..11c0340a91 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java @@ -20,24 +20,24 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class DefaultConverter implements PropertyValueConverter { - private static DefaultConverter defaultConverter = new DefaultConverter(); + private static DefaultConverter defaultConverter = new DefaultConverter(); - public static DefaultConverter getInstance() { - return defaultConverter; - } + public static DefaultConverter getInstance() { + return defaultConverter; + } - private DefaultConverter() { + private DefaultConverter() { - } + } - @Override - public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - return value; - } + @Override + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + return value; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java index d3edd9b8bf..2d2ac72ca5 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java @@ -20,23 +20,23 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class FloatConverter implements ToscaValueConverter { - private static FloatConverter floatConverter = new FloatConverter(); + private static FloatConverter floatConverter = new FloatConverter(); - public static FloatConverter getInstance() { - return floatConverter; - } + public static FloatConverter getInstance() { + return floatConverter; + } - private FloatConverter() { + private FloatConverter() { - } + } - @Override - public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - return Double.parseDouble(value); - } + @Override + public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + return Double.parseDouble(value); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java index 52fa9bfa81..77f49319bd 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java @@ -20,35 +20,35 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class HeatBooleanConverter implements PropertyValueConverter { - private static HeatBooleanConverter booleanConverter = new HeatBooleanConverter(); + private static HeatBooleanConverter booleanConverter = new HeatBooleanConverter(); - public static HeatBooleanConverter getInstance() { - return booleanConverter; - } + public static HeatBooleanConverter getInstance() { + return booleanConverter; + } - private HeatBooleanConverter() { + private HeatBooleanConverter() { - } + } - @Override - public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + @Override + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (value == null || value.isEmpty()) { - return null; - } + if (value == null || value.isEmpty()) { + return null; + } - if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("t") || value.equalsIgnoreCase("on") - || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("y") || value.equalsIgnoreCase("1")) { - return "true"; - } else { - return "false"; - } - } + if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("t") || value.equalsIgnoreCase("on") + || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("y") || value.equalsIgnoreCase("1")) { + return "true"; + } else { + return "false"; + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java index 30c21c8c1c..04c2a7dd1f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java @@ -20,33 +20,33 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.common.util.ValidationUtils; +import java.util.Map; + public class HeatCommaDelimitedListConverter implements PropertyValueConverter { - private static HeatCommaDelimitedListConverter stringConverter = new HeatCommaDelimitedListConverter(); + private static HeatCommaDelimitedListConverter stringConverter = new HeatCommaDelimitedListConverter(); - public static HeatCommaDelimitedListConverter getInstance() { - return stringConverter; - } + public static HeatCommaDelimitedListConverter getInstance() { + return stringConverter; + } - private HeatCommaDelimitedListConverter() { + private HeatCommaDelimitedListConverter() { - } + } - @Override - public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { - String coverted = null; - if(original != null){ - coverted = ValidationUtils.removeNoneUtf8Chars(original); - coverted = ValidationUtils.removeHtmlTagsOnly(coverted); - coverted = ValidationUtils.normaliseWhitespace(coverted); - coverted = ValidationUtils.stripOctets(coverted); - } - return coverted; - } + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + String coverted = null; + if(original != null){ + coverted = ValidationUtils.removeNoneUtf8Chars(original); + coverted = ValidationUtils.removeHtmlTagsOnly(coverted); + coverted = ValidationUtils.normaliseWhitespace(coverted); + coverted = ValidationUtils.stripOctets(coverted); + } + return coverted; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java index 9922c0f05d..90618ced45 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java @@ -20,34 +20,34 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.common.util.ValidationUtils; +import java.util.Map; + public class HeatJsonConverter implements PropertyValueConverter { - private static HeatJsonConverter jsonConverter = new HeatJsonConverter(); + private static HeatJsonConverter jsonConverter = new HeatJsonConverter(); - public static HeatJsonConverter getInstance() { - return jsonConverter; - } + public static HeatJsonConverter getInstance() { + return jsonConverter; + } - private HeatJsonConverter() { + private HeatJsonConverter() { - } + } - @Override - public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (original == null) { - return null; - } - String converted = ValidationUtils.removeNoneUtf8Chars(original); - converted = ValidationUtils.removeHtmlTagsOnly(converted); - converted = ValidationUtils.normaliseWhitespace(converted); - converted = ValidationUtils.stripOctets(converted); - // As opposed to string converter, keeping the " and ' symbols - return converted; - } + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if (original == null) { + return null; + } + String converted = ValidationUtils.removeNoneUtf8Chars(original); + converted = ValidationUtils.removeHtmlTagsOnly(converted); + converted = ValidationUtils.normaliseWhitespace(converted); + converted = ValidationUtils.stripOctets(converted); + // As opposed to string converter, keeping the " and ' symbols + return converted; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java index 8798b544bc..187793ee0b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java @@ -20,31 +20,31 @@ package org.openecomp.sdc.be.model.tosca.converters; +import org.openecomp.sdc.be.model.DataTypeDefinition; + import java.math.BigDecimal; import java.util.Map; -import org.openecomp.sdc.be.model.DataTypeDefinition; - public class HeatNumberConverter implements PropertyValueConverter { - private static HeatNumberConverter numberConverter = new HeatNumberConverter(); + private static HeatNumberConverter numberConverter = new HeatNumberConverter(); - public static HeatNumberConverter getInstance() { - return numberConverter; - } + public static HeatNumberConverter getInstance() { + return numberConverter; + } - private HeatNumberConverter() { + private HeatNumberConverter() { - } + } - @Override - public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (original == null || original.isEmpty()) { - return null; - } + if (original == null || original.isEmpty()) { + return null; + } - return new BigDecimal(original).toPlainString(); - } + return new BigDecimal(original).toPlainString(); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java index 3f2b6eabf7..3bc379c7f9 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java @@ -20,33 +20,33 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.common.util.ValidationUtils; +import java.util.Map; + public class HeatStringConverter implements PropertyValueConverter { - private static HeatStringConverter stringConverter = new HeatStringConverter(); + private static HeatStringConverter stringConverter = new HeatStringConverter(); - public static HeatStringConverter getInstance() { - return stringConverter; - } + public static HeatStringConverter getInstance() { + return stringConverter; + } - private HeatStringConverter() { + private HeatStringConverter() { - } + } - @Override - public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { - String coverted = null; - if(original != null){ - coverted = ValidationUtils.removeNoneUtf8Chars(original); - coverted = ValidationUtils.normaliseWhitespace(coverted); - coverted = ValidationUtils.stripOctets(coverted); - coverted = ValidationUtils.removeHtmlTagsOnly(coverted); - } - return coverted; - } + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + String coverted = null; + if(original != null){ + coverted = ValidationUtils.removeNoneUtf8Chars(original); + coverted = ValidationUtils.normaliseWhitespace(coverted); + coverted = ValidationUtils.stripOctets(coverted); + coverted = ValidationUtils.removeHtmlTagsOnly(coverted); + } + return coverted; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java index 30fbf69b80..f5e0a61358 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java @@ -20,28 +20,28 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class IntegerConverter implements ToscaValueConverter { - private static IntegerConverter integerConverter = new IntegerConverter(); + private static IntegerConverter integerConverter = new IntegerConverter(); - public static IntegerConverter getInstance() { - return integerConverter; - } + public static IntegerConverter getInstance() { + return integerConverter; + } - private IntegerConverter() { + private IntegerConverter() { - } + } - @Override - public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if ( value == null || value.isEmpty() ){ - return null; - } - return Integer.parseInt(value); - } + @Override + public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if ( value == null || value.isEmpty() ){ + return null; + } + return Integer.parseInt(value); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java index 3472b6448c..db2004aab4 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java @@ -20,42 +20,41 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.io.StringReader; -import java.util.Map; - -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.common.util.GsonFactory; - import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.util.GsonFactory; + +import java.io.StringReader; +import java.util.Map; public class JsonConverter implements PropertyValueConverter { - private static JsonConverter jsonConverter = new JsonConverter(); + private static JsonConverter jsonConverter = new JsonConverter(); - private static JsonParser jsonParser = new JsonParser(); + private static JsonParser jsonParser = new JsonParser(); - private static Gson gson = GsonFactory.getGson(); + private static Gson gson = GsonFactory.getGson(); - public static JsonConverter getInstance() { - return jsonConverter; - } + public static JsonConverter getInstance() { + return jsonConverter; + } - private JsonConverter() { + private JsonConverter() { - } + } - @Override - public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - StringReader reader = new StringReader(value); - JsonReader jsonReader = new JsonReader(reader); - jsonReader.setLenient(true); - JsonElement jsonElement = jsonParser.parse(jsonReader); - if (jsonElement.isJsonPrimitive()) { - return value; - } - return gson.toJson(jsonElement); - } + @Override + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + StringReader reader = new StringReader(value); + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + JsonElement jsonElement = jsonParser.parse(jsonReader); + if (jsonElement.isJsonPrimitive()) { + return value; + } + return gson.toJson(jsonElement); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java index 4f6de9b80c..00783404e7 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java @@ -20,200 +20,191 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - +import com.google.gson.*; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; import org.openecomp.sdc.be.model.tosca.validators.ListValidator; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.GsonFactory; import org.openecomp.sdc.common.util.JsonUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; -import com.google.gson.JsonParser; - -import fj.data.Either; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; public class ListConverter implements PropertyValueConverter { - private static ListConverter listConverter = new ListConverter(); - private static Gson gson = GsonFactory.getGson(); - private static Logger log = LoggerFactory.getLogger(ListValidator.class.getName()); - - DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - - private static JsonParser jsonParser = new JsonParser(); - - public static ListConverter getInstance() { - return listConverter; - } - - @Override - public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - Either<String, Boolean> convertWithErrorResult = this.convertWithErrorResult(value, innerType, dataTypes); - if (convertWithErrorResult.isRight()) { - return null; - } - - return convertWithErrorResult.left().value(); - } - - public Either<String, Boolean> convertWithErrorResult(String value, String innerType, - Map<String, DataTypeDefinition> dataTypes) { - if (value == null || innerType == null) { - return Either.left(value); - } - - PropertyValueConverter innerConverter; - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); - - if (innerToscaType != null) { - PropertyValueConverter innerConverter1; - switch (innerToscaType) { - case STRING: - innerConverter1 = ToscaPropertyType.STRING.getConverter(); - break; - case INTEGER: - innerConverter1 = ToscaPropertyType.INTEGER.getConverter(); - break; - case FLOAT: - innerConverter1 = ToscaPropertyType.FLOAT.getConverter(); - break; - case BOOLEAN: - innerConverter1 = ToscaPropertyType.BOOLEAN.getConverter(); - break; - case JSON: - innerConverter1 = ToscaPropertyType.JSON.getConverter(); - break; - default: - log.debug("inner Tosca Type is unknown"); - return Either.left(value); - } - innerConverter = innerConverter1; - } else { - log.debug("inner Tosca Type {} ia a complex data type.", innerType); - - Either<String, Boolean> validateComplexInnerType = convertComplexInnerType(value, innerType, dataTypes); - - return validateComplexInnerType; - } - - try { - ArrayList<String> newList = new ArrayList<String>(); - - JsonArray jo = (JsonArray) jsonParser.parse(value); - if(ToscaPropertyType.JSON == innerToscaType) - return Either.left(value); - int size = jo.size(); - for (int i = 0; i < size; i++) { - JsonElement currentValue = jo.get(i); - String element = JsonUtils.toString(currentValue); - - if (element == null || element.isEmpty()) { - continue; - } - element = innerConverter.convert(element, null, dataTypes); - newList.add(element); - } - - switch (innerToscaType) { - case STRING: - value = gson.toJson(newList); - break; - case INTEGER: - List<BigInteger> intList = new ArrayList<BigInteger>(); - - for (String str : newList) { - int base = 10; - if (str.contains("0x")) { - str = str.replaceFirst("0x", ""); - base = 16; - } - if (str.contains("0o")) { - str = str.replaceFirst("0o", ""); - base = 8; - } - intList.add(new BigInteger(str, base)); - } - value = gson.toJson(intList); - break; - case FLOAT: - value = "["; - for (String str : newList) { - value += str + ","; - } - value = value.substring(0, value.length() - 1); - value += "]"; - break; - case BOOLEAN: - List<Boolean> boolList = new ArrayList<Boolean>(); - for (String str : newList) { - boolList.add(Boolean.valueOf(str)); - } - value = gson.toJson(boolList); - break; - default: - value = gson.toJson(newList); - log.debug("inner Tosca Type unknown : {}", innerToscaType); - } - - } catch (JsonParseException e) { - log.debug("Failed to parse json : {}", value, e); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); - return Either.right(false); - } - - return Either.left(value); - } - - private Either<String, Boolean> convertComplexInnerType(String value, String innerType, - Map<String, DataTypeDefinition> allDataTypes) { - - DataTypeDefinition dataTypeDefinition = allDataTypes.get(innerType); - if (dataTypeDefinition == null) { - log.debug("Cannot find data type {}", innerType); - return Either.right(false); - } - - List<JsonElement> newList = new ArrayList<>(); - - try { - - JsonArray jo = (JsonArray) jsonParser.parse(value); - int size = jo.size(); - for (int i = 0; i < size; i++) { - JsonElement currentValue = jo.get(i); - - if (currentValue != null) { - - String element = JsonUtils.toString(currentValue); - - ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter - .validateAndUpdate(element, dataTypeDefinition, allDataTypes); - if (validateAndUpdate.right.booleanValue() == false) { - log.debug("Cannot parse value {} from type {} in list position {}",currentValue,innerType,i); - return Either.right(false); - } - JsonElement newValue = validateAndUpdate.left; - newList.add(newValue); - } - } - } catch (Exception e) { - log.debug("Failed to parse the value {} of list parameter.", value); - return Either.right(false); - } - value = gson.toJson(newList); - return Either.left(value); - } + private static ListConverter listConverter = new ListConverter(); + private static Gson gson = GsonFactory.getGson(); + private static final Logger log = Logger.getLogger(ListValidator.class.getName()); + + DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + + private static JsonParser jsonParser = new JsonParser(); + + public static ListConverter getInstance() { + return listConverter; + } + + @Override + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + Either<String, Boolean> convertWithErrorResult = this.convertWithErrorResult(value, innerType, dataTypes); + if (convertWithErrorResult.isRight()) { + return null; + } + + return convertWithErrorResult.left().value(); + } + + public Either<String, Boolean> convertWithErrorResult(String value, String innerType, + Map<String, DataTypeDefinition> dataTypes) { + if (value == null || innerType == null) { + return Either.left(value); + } + + PropertyValueConverter innerConverter; + ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); + + if (innerToscaType != null) { + PropertyValueConverter innerConverter1; + switch (innerToscaType) { + case STRING: + innerConverter1 = ToscaPropertyType.STRING.getConverter(); + break; + case INTEGER: + innerConverter1 = ToscaPropertyType.INTEGER.getConverter(); + break; + case FLOAT: + innerConverter1 = ToscaPropertyType.FLOAT.getConverter(); + break; + case BOOLEAN: + innerConverter1 = ToscaPropertyType.BOOLEAN.getConverter(); + break; + case JSON: + innerConverter1 = ToscaPropertyType.JSON.getConverter(); + break; + default: + log.debug("inner Tosca Type is unknown"); + return Either.left(value); + } + innerConverter = innerConverter1; + } else { + log.debug("inner Tosca Type {} ia a complex data type.", innerType); + + return convertComplexInnerType(value, innerType, dataTypes); + } + + try { + ArrayList<String> newList = new ArrayList<>(); + + JsonArray jo = (JsonArray) jsonParser.parse(value); + if(ToscaPropertyType.JSON == innerToscaType) + return Either.left(value); + int size = jo.size(); + for (int i = 0; i < size; i++) { + JsonElement currentValue = jo.get(i); + String element = JsonUtils.toString(currentValue); + + if (element == null || element.isEmpty()) { + continue; + } + element = innerConverter.convert(element, null, dataTypes); + newList.add(element); + } + + switch (innerToscaType) { + case STRING: + value = gson.toJson(newList); + break; + case INTEGER: + List<BigInteger> intList = new ArrayList<>(); + + for (String str : newList) { + int base = 10; + if (str.contains("0x")) { + str = str.replaceFirst("0x", ""); + base = 16; + } + if (str.contains("0o")) { + str = str.replaceFirst("0o", ""); + base = 8; + } + intList.add(new BigInteger(str, base)); + } + value = gson.toJson(intList); + break; + case FLOAT: + value = "["; + for (String str : newList) { + value += str + ","; + } + value = value.substring(0, value.length() - 1); + value += "]"; + break; + case BOOLEAN: + List<Boolean> boolList = new ArrayList<>(); + for (String str : newList) { + boolList.add(Boolean.valueOf(str)); + } + value = gson.toJson(boolList); + break; + default: + value = gson.toJson(newList); + log.debug("inner Tosca Type unknown : {}", innerToscaType); + } + + } catch (JsonParseException e) { + log.debug("Failed to parse json : {}", value, e); + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); + return Either.right(false); + } + + return Either.left(value); + } + + private Either<String, Boolean> convertComplexInnerType(String value, String innerType, + Map<String, DataTypeDefinition> allDataTypes) { + + DataTypeDefinition dataTypeDefinition = allDataTypes.get(innerType); + if (dataTypeDefinition == null) { + log.debug("Cannot find data type {}", innerType); + return Either.right(false); + } + + List<JsonElement> newList = new ArrayList<>(); + + try { + + JsonArray jo = (JsonArray) jsonParser.parse(value); + int size = jo.size(); + for (int i = 0; i < size; i++) { + JsonElement currentValue = jo.get(i); + + if (currentValue != null) { + + String element = JsonUtils.toString(currentValue); + + ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter + .validateAndUpdate(element, dataTypeDefinition, allDataTypes); + if (!validateAndUpdate.right.booleanValue()) { + log.debug("Cannot parse value {} from type {} in list position {}",currentValue,innerType,i); + return Either.right(false); + } + JsonElement newValue = validateAndUpdate.left; + newList.add(newValue); + } + } + } catch (Exception e) { + log.debug("Failed to parse the value {} of list parameter.", value); + return Either.right(false); + } + value = gson.toJson(newList); + return Either.left(value); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java index f33be29327..6e799dac83 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java @@ -20,29 +20,29 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class LowerCaseConverter implements PropertyValueConverter { - private static LowerCaseConverter booleanConverter = new LowerCaseConverter(); + private static LowerCaseConverter booleanConverter = new LowerCaseConverter(); - public static LowerCaseConverter getInstance() { - return booleanConverter; - } + public static LowerCaseConverter getInstance() { + return booleanConverter; + } - private LowerCaseConverter() { + private LowerCaseConverter() { - } + } - @Override - public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + @Override + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (value == null) { - return null; - } - return value.toLowerCase(); - } + if (value == null) { + return null; + } + return value.toLowerCase(); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java index 30b895f0d2..f53d95ceaf 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java @@ -20,230 +20,221 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - +import com.google.gson.*; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; import org.openecomp.sdc.be.model.tosca.validators.ListValidator; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.GsonFactory; import org.openecomp.sdc.common.util.JsonUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonParser; - -import fj.data.Either; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; public class MapConverter implements PropertyValueConverter { - private static MapConverter mapConverter = new MapConverter(); - private static Gson gson = GsonFactory.getGson(); - private static Logger log = LoggerFactory.getLogger(ListValidator.class.getName()); - - DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - - private static JsonParser jsonParser = new JsonParser(); - - public static MapConverter getInstance() { - return mapConverter; - } - - public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - - Either<String, Boolean> convertWithErrorResult = this.convertWithErrorResult(value, innerType, dataTypes); - if (convertWithErrorResult.isRight()) { - return null; - } - - return convertWithErrorResult.left().value(); - } - - public Either<String, Boolean> convertWithErrorResult(String value, String innerType, - Map<String, DataTypeDefinition> dataTypes) { - - if (value == null || value == "" || innerType == null) { - return Either.left(value); - } - - PropertyValueConverter innerConverter; - PropertyValueConverter keyConverter = ToscaPropertyType.STRING.getConverter(); - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); - - if (innerToscaType != null) { - switch (innerToscaType) { - case STRING: - innerConverter = ToscaPropertyType.STRING.getConverter(); - break; - case INTEGER: - innerConverter = ToscaPropertyType.INTEGER.getConverter(); - break; - case FLOAT: - innerConverter = ToscaPropertyType.FLOAT.getConverter(); - break; - case BOOLEAN: - innerConverter = ToscaPropertyType.BOOLEAN.getConverter(); - break; - case JSON: - innerConverter = ToscaPropertyType.JSON.getConverter(); - break; - default: - log.debug("inner Tosca Type is unknown"); - return Either.left(value); - } - - } else { - - log.debug("inner Tosca Type {} ia a complex data type.", innerType); - - Either<String, Boolean> validateComplexInnerType = convertComplexInnerType(value, innerType, keyConverter, - dataTypes); - - return validateComplexInnerType; - - } - - try { - Map<String, String> newMap = new HashMap<String, String>(); - - JsonElement jsonObject = jsonParser.parse(value); - JsonObject asJsonObject = jsonObject.getAsJsonObject(); - Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); - for (Entry<String, JsonElement> entry : entrySet) { - String key = entry.getKey(); - JsonElement jsonValue = entry.getValue(); - - key = keyConverter.convert(entry.getKey(), null, dataTypes); - - String element = JsonUtils.toString(jsonValue); - - String val = innerConverter.convert(element, null, dataTypes); - newMap.put(key, val); - } - - String objVal; - switch (innerToscaType) { - case STRING: - value = gson.toJson(newMap); - break; - case INTEGER: - String key = null; - Map<String, Integer> intMap = new HashMap<String, Integer>(); - for (Map.Entry<String, String> entry : newMap.entrySet()) { - objVal = entry.getValue(); - key = entry.getKey(); - if (objVal != null) { - intMap.put(key, Integer.valueOf(objVal.toString())); - } else { - intMap.put(key, null); - } - - } - value = gson.toJson(intMap); - break; - case FLOAT: - value = "{"; - for (Map.Entry<String, String> entry : newMap.entrySet()) { - objVal = entry.getValue(); - if (objVal == null) { - objVal = "null"; - } - key = entry.getKey(); - value += "\"" + key + "\":" + objVal.toString() + ","; - } - value = value.substring(0, value.length() - 1); - value += "}"; - break; - case BOOLEAN: - Map<String, Boolean> boolMap = new HashMap<String, Boolean>(); - for (Map.Entry<String, String> entry : newMap.entrySet()) { - objVal = entry.getValue(); - key = entry.getKey(); - if (objVal != null) { - boolMap.put(key, Boolean.valueOf(objVal.toString())); - } else { - boolMap.put(key, null); - } - } - value = gson.toJson(boolMap); - break; - default: - value = gson.toJson(newMap); - log.debug("inner Tosca Type unknown : {}", innerToscaType); - } - } catch (JsonParseException e) { - log.debug("Failed to parse json : {}", value, e); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Converter"); - return Either.right(false); - } - - return Either.left(value); - - } - - /** - * convert the json value of map when the inner type is a complex data type - * - * @param value - * @param innerType - * @param keyConverter - * @param allDataTypes - * @return - */ - private Either<String, Boolean> convertComplexInnerType(String value, String innerType, - PropertyValueConverter keyConverter, Map<String, DataTypeDefinition> allDataTypes) { - - DataTypeDefinition dataTypeDefinition = allDataTypes.get(innerType); - if (dataTypeDefinition == null) { - log.debug("Cannot find data type {}", innerType); - return Either.right(false); - } - - Map<String, JsonElement> newMap = new HashMap<String, JsonElement>(); - - try { - - JsonElement jsonObject = jsonParser.parse(value); - JsonObject asJsonObject = jsonObject.getAsJsonObject(); - Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); - for (Entry<String, JsonElement> entry : entrySet) { - String currentKey = keyConverter.convert(entry.getKey(), null, allDataTypes); - - JsonElement currentValue = entry.getValue(); - - if (currentValue != null) { - - String element = JsonUtils.toString(currentValue); - - ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter - .validateAndUpdate(element, dataTypeDefinition, allDataTypes); - if (validateAndUpdate.right.booleanValue() == false) { - log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey); - return Either.right(false); - } - JsonElement newValue = validateAndUpdate.left; - newMap.put(currentKey, newValue); - } else { - newMap.put(currentKey, null); - } - } - - } catch (Exception e) { - log.debug("Cannot parse value {} of map from inner type {}", value, innerType); - return Either.right(false); - } - - value = gson.toJson(newMap); - return Either.left(value); - } + private static MapConverter mapConverter = new MapConverter(); + private static Gson gson = GsonFactory.getGson(); + private static final Logger log = Logger.getLogger(ListValidator.class.getName()); + + DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + + private static JsonParser jsonParser = new JsonParser(); + + public static MapConverter getInstance() { + return mapConverter; + } + + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + + Either<String, Boolean> convertWithErrorResult = this.convertWithErrorResult(value, innerType, dataTypes); + if (convertWithErrorResult.isRight()) { + return null; + } + + return convertWithErrorResult.left().value(); + } + + public Either<String, Boolean> convertWithErrorResult(String value, String innerType, + Map<String, DataTypeDefinition> dataTypes) { + + if (value == null || value == "" || innerType == null) { + return Either.left(value); + } + + PropertyValueConverter innerConverter; + PropertyValueConverter keyConverter = ToscaPropertyType.STRING.getConverter(); + ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); + + if (innerToscaType != null) { + switch (innerToscaType) { + case STRING: + innerConverter = ToscaPropertyType.STRING.getConverter(); + break; + case INTEGER: + innerConverter = ToscaPropertyType.INTEGER.getConverter(); + break; + case FLOAT: + innerConverter = ToscaPropertyType.FLOAT.getConverter(); + break; + case BOOLEAN: + innerConverter = ToscaPropertyType.BOOLEAN.getConverter(); + break; + case JSON: + innerConverter = ToscaPropertyType.JSON.getConverter(); + break; + default: + log.debug("inner Tosca Type is unknown"); + return Either.left(value); + } + + } else { + + log.debug("inner Tosca Type {} ia a complex data type.", innerType); + + return convertComplexInnerType(value, innerType, keyConverter, + dataTypes); + + } + + try { + Map<String, String> newMap = new HashMap<>(); + + JsonElement jsonObject = jsonParser.parse(value); + JsonObject asJsonObject = jsonObject.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); + for (Entry<String, JsonElement> entry : entrySet) { + String key = entry.getKey(); + JsonElement jsonValue = entry.getValue(); + + key = keyConverter.convert(entry.getKey(), null, dataTypes); + + String element = JsonUtils.toString(jsonValue); + + String val = innerConverter.convert(element, null, dataTypes); + newMap.put(key, val); + } + + String objVal; + switch (innerToscaType) { + case STRING: + value = gson.toJson(newMap); + break; + case INTEGER: + String key = null; + Map<String, Integer> intMap = new HashMap<>(); + for (Map.Entry<String, String> entry : newMap.entrySet()) { + objVal = entry.getValue(); + key = entry.getKey(); + if (objVal != null) { + intMap.put(key, Integer.valueOf(objVal.toString())); + } else { + intMap.put(key, null); + } + + } + value = gson.toJson(intMap); + break; + case FLOAT: + value = "{"; + for (Map.Entry<String, String> entry : newMap.entrySet()) { + objVal = entry.getValue(); + if (objVal == null) { + objVal = "null"; + } + key = entry.getKey(); + value += "\"" + key + "\":" + objVal.toString() + ","; + } + value = value.substring(0, value.length() - 1); + value += "}"; + break; + case BOOLEAN: + Map<String, Boolean> boolMap = new HashMap<>(); + for (Map.Entry<String, String> entry : newMap.entrySet()) { + objVal = entry.getValue(); + key = entry.getKey(); + if (objVal != null) { + boolMap.put(key, Boolean.valueOf(objVal.toString())); + } else { + boolMap.put(key, null); + } + } + value = gson.toJson(boolMap); + break; + default: + value = gson.toJson(newMap); + log.debug("inner Tosca Type unknown : {}", innerToscaType); + } + } catch (JsonParseException e) { + log.debug("Failed to parse json : {}", value, e); + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Converter"); + return Either.right(false); + } + + return Either.left(value); + + } + + /** + * convert the json value of map when the inner type is a complex data type + * + * @param value + * @param innerType + * @param keyConverter + * @param allDataTypes + * @return + */ + private Either<String, Boolean> convertComplexInnerType(String value, String innerType, + PropertyValueConverter keyConverter, Map<String, DataTypeDefinition> allDataTypes) { + + DataTypeDefinition dataTypeDefinition = allDataTypes.get(innerType); + if (dataTypeDefinition == null) { + log.debug("Cannot find data type {}", innerType); + return Either.right(false); + } + + Map<String, JsonElement> newMap = new HashMap<>(); + + try { + + JsonElement jsonObject = jsonParser.parse(value); + JsonObject asJsonObject = jsonObject.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); + for (Entry<String, JsonElement> entry : entrySet) { + String currentKey = keyConverter.convert(entry.getKey(), null, allDataTypes); + + JsonElement currentValue = entry.getValue(); + + if (currentValue != null) { + + String element = JsonUtils.toString(currentValue); + + ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter + .validateAndUpdate(element, dataTypeDefinition, allDataTypes); + if (!validateAndUpdate.right.booleanValue()) { + log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey); + return Either.right(false); + } + JsonElement newValue = validateAndUpdate.left; + newMap.put(currentKey, newValue); + } else { + newMap.put(currentKey, null); + } + } + + } catch (Exception e) { + log.debug("Cannot parse value {} of map from inner type {}", value, innerType); + return Either.right(false); + } + + value = gson.toJson(newMap); + return Either.left(value); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java index 254785fe8a..b60b0a5ec8 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java @@ -20,12 +20,12 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public interface PropertyValueConverter { - String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes); + String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java index f5a7ff632e..ae5340720c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java @@ -20,36 +20,36 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.common.util.ValidationUtils; +import java.util.Map; + public class StringConvertor implements PropertyValueConverter { - private static StringConvertor stringConverter = new StringConvertor(); + private static StringConvertor stringConverter = new StringConvertor(); - public static StringConvertor getInstance() { - return stringConverter; - } + public static StringConvertor getInstance() { + return stringConverter; + } - private StringConvertor() { + private StringConvertor() { - } + } - @Override - public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (original == null) { - return null; - } - String coverted = ValidationUtils.removeNoneUtf8Chars(original); + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if (original == null) { + return null; + } + String coverted = ValidationUtils.removeNoneUtf8Chars(original); - // coverted = ValidationUtils.convertHtmlTagsToEntities(coverted); - coverted = ValidationUtils.normaliseWhitespace(coverted); - coverted = ValidationUtils.stripOctets(coverted); - coverted = ValidationUtils.removeHtmlTagsOnly(coverted); + // coverted = ValidationUtils.convertHtmlTagsToEntities(coverted); + coverted = ValidationUtils.normaliseWhitespace(coverted); + coverted = ValidationUtils.stripOctets(coverted); + coverted = ValidationUtils.removeHtmlTagsOnly(coverted); - return coverted; - } + return coverted; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java index 977415b909..346f637306 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java @@ -20,35 +20,35 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class ToscaBooleanConverter implements PropertyValueConverter { - private static ToscaBooleanConverter booleanConverter = new ToscaBooleanConverter(); + private static ToscaBooleanConverter booleanConverter = new ToscaBooleanConverter(); - public static ToscaBooleanConverter getInstance() { - return booleanConverter; - } + public static ToscaBooleanConverter getInstance() { + return booleanConverter; + } - private ToscaBooleanConverter() { + private ToscaBooleanConverter() { - } + } - @Override - public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + @Override + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (value == null) { - return null; - } + if (value == null) { + return null; + } - if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("yes") - || value.equalsIgnoreCase("y")) { - return "true"; - } else { - return "false"; - } - } + if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("yes") + || value.equalsIgnoreCase("y")) { + return "true"; + } else { + return "false"; + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java index 4aadaa0910..941535a09d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java @@ -1,8 +1,7 @@ package org.openecomp.sdc.be.model.tosca.converters; -import org.openecomp.sdc.be.model.tosca.ToscaFunctions; - import com.google.gson.JsonObject; +import org.openecomp.sdc.be.model.tosca.ToscaFunctions; public class ToscaConverterUtils { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java index ba765c92a0..417beea5fe 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java @@ -20,12 +20,12 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.math.BigDecimal; -import java.util.Map; - import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.math.BigDecimal; +import java.util.Map; + public class ToscaFloatConverter implements PropertyValueConverter { private static ToscaFloatConverter numberConverter = new ToscaFloatConverter(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java index d70088e044..0ce446d3c4 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java @@ -20,37 +20,36 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.io.StringReader; -import java.util.Map; - -import org.openecomp.sdc.be.model.DataTypeDefinition; - import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; +import org.openecomp.sdc.be.model.DataTypeDefinition; + +import java.io.StringReader; +import java.util.Map; public class ToscaJsonValueConverter extends ToscaValueBaseConverter implements ToscaValueConverter { - private static ToscaJsonValueConverter toscaJsonConverter = new ToscaJsonValueConverter(); + private static ToscaJsonValueConverter toscaJsonConverter = new ToscaJsonValueConverter(); - public static ToscaJsonValueConverter getInstance() { - return toscaJsonConverter; - } + public static ToscaJsonValueConverter getInstance() { + return toscaJsonConverter; + } - private ToscaJsonValueConverter() { + private ToscaJsonValueConverter() { - } + } - JsonParser jsonParser = new JsonParser(); + JsonParser jsonParser = new JsonParser(); - @Override - public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - StringReader reader = new StringReader(value); - JsonReader jsonReader = new JsonReader(reader); - jsonReader.setLenient(true); - JsonElement jsonElement = jsonParser.parse(jsonReader); - if (jsonElement.isJsonPrimitive()) { - return value; - } - return handleComplexJsonValue(jsonElement); - } + @Override + public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + StringReader reader = new StringReader(value); + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + JsonElement jsonElement = jsonParser.parse(jsonReader); + if (jsonElement.isJsonPrimitive()) { + return value; + } + return handleComplexJsonValue(jsonElement); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java index f3189ee968..8eb4c1099b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java @@ -20,6 +20,14 @@ package org.openecomp.sdc.be.model.tosca.converters; +import com.google.gson.*; +import com.google.gson.stream.JsonReader; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.common.log.wrappers.Logger; + import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; @@ -27,151 +35,136 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; -import com.google.gson.stream.JsonReader; - public class ToscaListValueConverter extends ToscaValueBaseConverter implements ToscaValueConverter { - private static ToscaListValueConverter listConverter = new ToscaListValueConverter(); - private JsonParser jsonParser = new JsonParser(); - private static Logger log = LoggerFactory.getLogger(ToscaListValueConverter.class.getName()); - - public static ToscaListValueConverter getInstance() { - return listConverter; - } - - private ToscaListValueConverter() { - - } - - @Override - public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (value == null) { - return null; - } - try { - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); - ToscaValueConverter innerConverter = null; - boolean isScalar = true; - if (innerToscaType != null) { - innerConverter = innerToscaType.getValueConverter(); - } else { - DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); - - if (dataTypeDefinition != null) { - ToscaPropertyType toscaPropertyType = null; - if ((toscaPropertyType = isScalarType(dataTypeDefinition)) != null) { - innerConverter = toscaPropertyType.getValueConverter(); - } else { - isScalar = false; - innerConverter = ToscaMapValueConverter.getInstance(); - } - } else { - log.debug("inner Tosca Type is null"); - return value; - } - } - JsonElement jsonElement = null; - try { - StringReader reader = new StringReader(value); - JsonReader jsonReader = new JsonReader(reader); - jsonReader.setLenient(true); - - jsonElement = jsonParser.parse(jsonReader); - } catch (JsonSyntaxException e) { - log.debug("convertToToscaValue failed to parse json value :", e); - return null; - } - if (jsonElement == null || true == jsonElement.isJsonNull()) { - log.debug("convertToToscaValue json element is null"); - return null; - } - if (jsonElement.isJsonArray() == false) { - // get_input all array like get_input: qrouter_names - return handleComplexJsonValue(jsonElement); - } - JsonArray asJsonArray = jsonElement.getAsJsonArray(); - - ArrayList<Object> toscaList = new ArrayList<Object>(); - final boolean isScalarF = isScalar; - final ToscaValueConverter innerConverterFinal = innerConverter; - asJsonArray.forEach(e -> { - Object convertedValue = null; - if (isScalarF) { - if (e.isJsonPrimitive()) { - String jsonAsString = e.getAsString(); - log.debug("try to convert scalar value {}", jsonAsString); - convertedValue = innerConverterFinal.convertToToscaValue(jsonAsString, innerType, - dataTypes); - } else { - convertedValue = handleComplexJsonValue(e); - } - - } else { - JsonObject asJsonObject = e.getAsJsonObject(); - Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); - - DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); - Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); - Map<String, Object> toscaObjectPresentation = new HashMap<>(); - - for (Entry<String, JsonElement> entry : entrySet) { - String propName = entry.getKey(); - - JsonElement elementValue = entry.getValue(); - PropertyDefinition propertyDefinition = allProperties.get(propName); - if (propertyDefinition == null) { - log.debug("The property {} was not found under data type {}",propName,dataTypeDefinition.getName()); - continue; - // return null; - } - String type = propertyDefinition.getType(); - ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); - Object convValue; - if (propertyType != null) { - if (elementValue.isJsonPrimitive()) { - ToscaValueConverter valueConverter = propertyType.getValueConverter(); - convValue = valueConverter.convertToToscaValue(elementValue.getAsString(), type, - dataTypes); - } else { - if (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(propertyType)) { - ToscaValueConverter valueConverter = propertyType.getValueConverter(); - String json = gson.toJson(elementValue); - String innerTypeRecursive = propertyDefinition.getSchema().getProperty().getType(); - convValue = valueConverter.convertToToscaValue(json, innerTypeRecursive, dataTypes); - } else { - convValue = handleComplexJsonValue(elementValue); - } - } - } else { - String json = gson.toJson(elementValue); - convValue = convertToToscaValue(json, type, dataTypes); - } - toscaObjectPresentation.put(propName, convValue); - } - convertedValue = toscaObjectPresentation; - } - toscaList.add(convertedValue); - }); - return toscaList; - } catch ( - - JsonParseException e) { - log.debug("Failed to parse json : {}", value, e); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); - return null; - } - } + private static ToscaListValueConverter listConverter = new ToscaListValueConverter(); + private JsonParser jsonParser = new JsonParser(); + private static final Logger log = Logger.getLogger(ToscaListValueConverter.class.getName()); + + public static ToscaListValueConverter getInstance() { + return listConverter; + } + + private ToscaListValueConverter() { + + } + + @Override + public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if (value == null) { + return null; + } + try { + ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); + ToscaValueConverter innerConverter = null; + boolean isScalar = true; + if (innerToscaType != null) { + innerConverter = innerToscaType.getValueConverter(); + } else { + DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); + + if (dataTypeDefinition != null) { + ToscaPropertyType toscaPropertyType = null; + if ((toscaPropertyType = isScalarType(dataTypeDefinition)) != null) { + innerConverter = toscaPropertyType.getValueConverter(); + } else { + isScalar = false; + innerConverter = ToscaMapValueConverter.getInstance(); + } + } else { + log.debug("inner Tosca Type is null"); + return value; + } + } + JsonElement jsonElement = null; + try { + StringReader reader = new StringReader(value); + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + + jsonElement = jsonParser.parse(jsonReader); + } catch (JsonSyntaxException e) { + log.debug("convertToToscaValue failed to parse json value :", e); + return null; + } + if (jsonElement == null || jsonElement.isJsonNull()) { + log.debug("convertToToscaValue json element is null"); + return null; + } + if (!jsonElement.isJsonArray()) { + // get_input all array like get_input: qrouter_names + return handleComplexJsonValue(jsonElement); + } + JsonArray asJsonArray = jsonElement.getAsJsonArray(); + + ArrayList<Object> toscaList = new ArrayList<>(); + final boolean isScalarF = isScalar; + final ToscaValueConverter innerConverterFinal = innerConverter; + asJsonArray.forEach(e -> { + Object convertedValue = null; + if (isScalarF) { + if (e.isJsonPrimitive()) { + String jsonAsString = e.getAsString(); + log.debug("try to convert scalar value {}", jsonAsString); + convertedValue = innerConverterFinal.convertToToscaValue(jsonAsString, innerType, + dataTypes); + } else { + convertedValue = handleComplexJsonValue(e); + } + + } else { + JsonObject asJsonObject = e.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); + + DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); + Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); + Map<String, Object> toscaObjectPresentation = new HashMap<>(); + + for (Entry<String, JsonElement> entry : entrySet) { + String propName = entry.getKey(); + + JsonElement elementValue = entry.getValue(); + PropertyDefinition propertyDefinition = allProperties.get(propName); + if (propertyDefinition == null) { + log.debug("The property {} was not found under data type {}",propName,dataTypeDefinition.getName()); + continue; + // return null; + } + String type = propertyDefinition.getType(); + ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); + Object convValue; + if (propertyType != null) { + if (elementValue.isJsonPrimitive()) { + ToscaValueConverter valueConverter = propertyType.getValueConverter(); + convValue = valueConverter.convertToToscaValue(elementValue.getAsString(), type, + dataTypes); + } else { + if (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(propertyType)) { + ToscaValueConverter valueConverter = propertyType.getValueConverter(); + String json = gson.toJson(elementValue); + String innerTypeRecursive = propertyDefinition.getSchema().getProperty().getType(); + convValue = valueConverter.convertToToscaValue(json, innerTypeRecursive, dataTypes); + } else { + convValue = handleComplexJsonValue(elementValue); + } + } + } else { + String json = gson.toJson(elementValue); + convValue = convertToToscaValue(json, type, dataTypes); + } + toscaObjectPresentation.put(propName, convValue); + } + convertedValue = toscaObjectPresentation; + } + toscaList.add(convertedValue); + }); + return toscaList; + } catch ( + + JsonParseException e) { + log.debug("Failed to parse json : {}", value, e); + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); + return null; + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java index 5b565bf62a..04636d87e0 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java @@ -20,233 +20,222 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - +import com.google.gson.*; +import com.google.gson.stream.JsonReader; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; -import com.google.gson.stream.JsonReader; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.io.StringReader; +import java.util.*; +import java.util.Map.Entry; public class ToscaMapValueConverter extends ToscaValueBaseConverter implements ToscaValueConverter { - private static ToscaMapValueConverter mapConverter = new ToscaMapValueConverter(); - - private JsonParser jsonParser = new JsonParser(); - private static Logger log = LoggerFactory.getLogger(ToscaMapValueConverter.class.getName()); - - public static ToscaMapValueConverter getInstance() { - return mapConverter; - } - - private ToscaMapValueConverter() { - - } - - @Override - public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (value == null) { - return value; - } - try { - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); - ToscaValueConverter innerConverter = null; - boolean isScalar = true; - List<PropertyDefinition> allPropertiesRecursive = new ArrayList<>(); - if (innerToscaType != null) { - innerConverter = innerToscaType.getValueConverter(); - } else { - - DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); - if (dataTypeDefinition != null) { - ToscaPropertyType toscaPropertyType = null; - if ((toscaPropertyType = isScalarType(dataTypeDefinition)) != null) { - innerConverter = toscaPropertyType.getValueConverter(); - } else { - isScalar = false; - allPropertiesRecursive.addAll(dataTypeDefinition.getProperties()); - DataTypeDefinition derivedFrom = dataTypeDefinition.getDerivedFrom(); - while ( !derivedFrom.getName().equals("tosca.datatypes.Root") ){ - allPropertiesRecursive.addAll(derivedFrom.getProperties()); - derivedFrom = derivedFrom.getDerivedFrom(); - } - } - } else { - log.debug("inner Tosca Type is null"); - return value; - } - - } - JsonElement jsonElement = null; - try { - StringReader reader = new StringReader(value); - JsonReader jsonReader = new JsonReader(reader); - jsonReader.setLenient(true); - - jsonElement = jsonParser.parse(jsonReader); - - } catch (JsonSyntaxException e) { - log.debug("convertToToscaValue failed to parse json value :", e); - return null; - } - if (jsonElement == null || true == jsonElement.isJsonNull()) { - log.debug("convertToToscaValue json element is null"); - return null; - } - JsonObject asJsonObject = jsonElement.getAsJsonObject(); - Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); - - Map<String, Object> toscaMap = new HashMap<>(); - final boolean isScalarF = isScalar; - final ToscaValueConverter innerConverterFinal = innerConverter; - entrySet.forEach(e -> { - convertEntry(innerType, dataTypes, allPropertiesRecursive, toscaMap, isScalarF, innerConverterFinal, e); - }); - return toscaMap; - } catch (JsonParseException e) { - log.debug("Failed to parse json : {}", value, e); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); - return null; - } - } - - private void convertEntry(String innerType, Map<String, DataTypeDefinition> dataTypes, List<PropertyDefinition> allPropertiesRecursive, Map<String, Object> toscaMap, final boolean isScalarF, final ToscaValueConverter innerConverterFinal, - Entry<String, JsonElement> e) { - log.debug("try convert element {}", e.getValue()); - boolean scalar = false; - String propType = null; - ToscaValueConverter innerConverterProp = innerConverterFinal; - if ( isScalarF ){ - scalar = isScalarF; - propType = innerType; - }else{ - for ( PropertyDefinition pd : allPropertiesRecursive ){ - if ( pd.getName().equals(e.getKey()) ){ - propType = pd.getType(); - DataTypeDefinition pdDataType = dataTypes.get(propType); - ToscaPropertyType toscaPropType = isScalarType(pdDataType); - if ( toscaPropType == null ){ - scalar = false; - }else{ - scalar = true; - propType = toscaPropType.getType(); - innerConverterProp = toscaPropType.getValueConverter(); - } - break; - } - } - } - Object convertedValue = convertDataTypeToToscaObject(propType, dataTypes, innerConverterProp, scalar, e.getValue()); - toscaMap.put(e.getKey(), convertedValue); - } - - public Object convertDataTypeToToscaObject(String innerType, Map<String, DataTypeDefinition> dataTypes, ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue) { - Object convertedValue = null; - if (isScalarF && entryValue.isJsonPrimitive()) { - log.debug("try convert scalar value {}", entryValue.getAsString()); - if (entryValue.getAsString() == null) { - convertedValue = null; - } else { - convertedValue = innerConverter.convertToToscaValue(entryValue.getAsString(), innerType, dataTypes); - } - } else { - if ( entryValue.isJsonPrimitive() ){ - return handleComplexJsonValue(entryValue); - } - - // ticket 228696523 created / DE272734 / Bug 154492 Fix - if(entryValue instanceof JsonArray) { - ArrayList<Object> toscaObjectPresentationArray = new ArrayList<>(); - JsonArray jsonArray = entryValue.getAsJsonArray(); - - for (JsonElement jsonElement : jsonArray) { - Object convertedDataTypeToToscaMap = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, jsonElement); - toscaObjectPresentationArray.add(convertedDataTypeToToscaMap); - } - convertedValue = toscaObjectPresentationArray; - } else { - convertedValue = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, entryValue); - } - } - return convertedValue; - } - - private Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes, - final boolean isScalarF, JsonElement entryValue) { - Object convertedValue; - if (entryValue.isJsonPrimitive()) { - return json2JavaPrimitive(entryValue.getAsJsonPrimitive()); - } - JsonObject asJsonObjectIn = entryValue.getAsJsonObject(); - - DataTypePropertyConverter.getInstance().mergeDataTypeDefaultValuesWithPropertyValue(asJsonObjectIn, innerType, dataTypes); - Map<String, Object> toscaObjectPresentation = new HashMap<>(); - Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet(); - - for (Entry<String, JsonElement> entry : entrySetIn) { - String propName = entry.getKey(); - - JsonElement elementValue = entry.getValue(); - Object convValue; - if (isScalarF == false) { - DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); - Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); - PropertyDefinition propertyDefinition = allProperties.get(propName); - if (propertyDefinition == null) { - log.trace("The property {} was not found under data type . Parse as map", propName); - if (elementValue.isJsonPrimitive()) { - convValue = elementValue.getAsString(); - } else { - convValue = handleComplexJsonValue(elementValue); - } - } else { - String type = propertyDefinition.getType(); - ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); - if (propertyType != null) { - if (elementValue.isJsonPrimitive()) { - ToscaValueConverter valueConverter = propertyType.getValueConverter(); - convValue = valueConverter.convertToToscaValue(elementValue.getAsString(), type, dataTypes); - } else { - if (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(propertyType)) { - ToscaValueConverter valueConverter = propertyType.getValueConverter(); - String json = gson.toJson(elementValue); - String innerTypeRecursive = propertyDefinition.getSchema().getProperty().getType(); - convValue = valueConverter.convertToToscaValue(json, innerTypeRecursive, dataTypes); - } else { - convValue = handleComplexJsonValue(elementValue); - } - } - } else { - convValue = convertToToscaValue(elementValue.toString(), type, dataTypes); - } - } - } else { - if (elementValue.isJsonPrimitive()) { - convValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive()); - } else { - convValue = handleComplexJsonValue(elementValue); - } - } - if(!isEmptyObjectValue(convValue)){ - toscaObjectPresentation.put(propName, convValue); - } - } - convertedValue = toscaObjectPresentation; - return convertedValue; - } + private static ToscaMapValueConverter mapConverter = new ToscaMapValueConverter(); + + private JsonParser jsonParser = new JsonParser(); + private static final Logger log = Logger.getLogger(ToscaMapValueConverter.class.getName()); + + public static ToscaMapValueConverter getInstance() { + return mapConverter; + } + + private ToscaMapValueConverter() { + + } + + @Override + public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if (value == null) { + return value; + } + try { + ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); + ToscaValueConverter innerConverter = null; + boolean isScalar = true; + List<PropertyDefinition> allPropertiesRecursive = new ArrayList<>(); + if (innerToscaType != null) { + innerConverter = innerToscaType.getValueConverter(); + } else { + + DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); + if (dataTypeDefinition != null) { + ToscaPropertyType toscaPropertyType = null; + if ((toscaPropertyType = isScalarType(dataTypeDefinition)) != null) { + innerConverter = toscaPropertyType.getValueConverter(); + } else { + isScalar = false; + allPropertiesRecursive.addAll(dataTypeDefinition.getProperties()); + DataTypeDefinition derivedFrom = dataTypeDefinition.getDerivedFrom(); + while ( !derivedFrom.getName().equals("tosca.datatypes.Root") ){ + allPropertiesRecursive.addAll(derivedFrom.getProperties()); + derivedFrom = derivedFrom.getDerivedFrom(); + } + } + } else { + log.debug("inner Tosca Type is null"); + return value; + } + + } + JsonElement jsonElement = null; + try { + StringReader reader = new StringReader(value); + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + + jsonElement = jsonParser.parse(jsonReader); + + } catch (JsonSyntaxException e) { + log.debug("convertToToscaValue failed to parse json value :", e); + return null; + } + if (jsonElement == null || jsonElement.isJsonNull()) { + log.debug("convertToToscaValue json element is null"); + return null; + } + JsonObject asJsonObject = jsonElement.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); + + Map<String, Object> toscaMap = new HashMap<>(); + final boolean isScalarF = isScalar; + final ToscaValueConverter innerConverterFinal = innerConverter; + entrySet.forEach(e -> { + convertEntry(innerType, dataTypes, allPropertiesRecursive, toscaMap, isScalarF, innerConverterFinal, e); + }); + return toscaMap; + } catch (JsonParseException e) { + log.debug("Failed to parse json : {}", value, e); + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); + return null; + } + } + + private void convertEntry(String innerType, Map<String, DataTypeDefinition> dataTypes, List<PropertyDefinition> allPropertiesRecursive, Map<String, Object> toscaMap, final boolean isScalarF, final ToscaValueConverter innerConverterFinal, + Entry<String, JsonElement> e) { + log.debug("try convert element {}", e.getValue()); + boolean scalar = false; + String propType = null; + ToscaValueConverter innerConverterProp = innerConverterFinal; + if ( isScalarF ){ + scalar = isScalarF; + propType = innerType; + }else{ + for ( PropertyDefinition pd : allPropertiesRecursive ){ + if ( pd.getName().equals(e.getKey()) ){ + propType = pd.getType(); + DataTypeDefinition pdDataType = dataTypes.get(propType); + ToscaPropertyType toscaPropType = isScalarType(pdDataType); + if ( toscaPropType == null ){ + scalar = false; + }else{ + scalar = true; + propType = toscaPropType.getType(); + innerConverterProp = toscaPropType.getValueConverter(); + } + break; + } + } + } + Object convertedValue = convertDataTypeToToscaObject(propType, dataTypes, innerConverterProp, scalar, e.getValue(), false); + toscaMap.put(e.getKey(), convertedValue); + } + + public Object convertDataTypeToToscaObject(String innerType, Map<String, DataTypeDefinition> dataTypes, ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue, boolean preserveEmptyValue) { + Object convertedValue = null; + if (isScalarF && entryValue.isJsonPrimitive()) { + log.debug("try convert scalar value {}", entryValue.getAsString()); + if (entryValue.getAsString() == null) { + convertedValue = null; + } else { + convertedValue = innerConverter.convertToToscaValue(entryValue.getAsString(), innerType, dataTypes); + } + } else { + if ( entryValue.isJsonPrimitive() ){ + return handleComplexJsonValue(entryValue); + } + + // ticket 228696523 created / DE272734 / Bug 154492 Fix + if(entryValue instanceof JsonArray) { + ArrayList<Object> toscaObjectPresentationArray = new ArrayList<>(); + JsonArray jsonArray = entryValue.getAsJsonArray(); + + for (JsonElement jsonElement : jsonArray) { + Object convertedDataTypeToToscaMap = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, jsonElement, preserveEmptyValue); + toscaObjectPresentationArray.add(convertedDataTypeToToscaMap); + } + convertedValue = toscaObjectPresentationArray; + } else { + convertedValue = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, entryValue, preserveEmptyValue); + } + } + return convertedValue; + } + + private Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes, + final boolean isScalarF, JsonElement entryValue, boolean preserveEmptyValue) { + Object convertedValue; + if (entryValue.isJsonPrimitive()) { + return json2JavaPrimitive(entryValue.getAsJsonPrimitive()); + } + JsonObject asJsonObjectIn = entryValue.getAsJsonObject(); + + DataTypePropertyConverter.getInstance().mergeDataTypeDefaultValuesWithPropertyValue(asJsonObjectIn, innerType, dataTypes); + Map<String, Object> toscaObjectPresentation = new HashMap<>(); + Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet(); + + for (Entry<String, JsonElement> entry : entrySetIn) { + String propName = entry.getKey(); + + JsonElement elementValue = entry.getValue(); + Object convValue; + if (!isScalarF) { + DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); + Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); + PropertyDefinition propertyDefinition = allProperties.get(propName); + if (propertyDefinition == null) { + log.trace("The property {} was not found under data type . Parse as map", propName); + if (elementValue.isJsonPrimitive()) { + convValue = elementValue.getAsString(); + } else { + convValue = handleComplexJsonValue(elementValue); + } + } else { + String type = propertyDefinition.getType(); + ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); + if (propertyType != null) { + if (elementValue.isJsonPrimitive()) { + ToscaValueConverter valueConverter = propertyType.getValueConverter(); + convValue = valueConverter.convertToToscaValue(elementValue.getAsString(), type, dataTypes); + } else { + if (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(propertyType)) { + ToscaValueConverter valueConverter = propertyType.getValueConverter(); + String json = gson.toJson(elementValue); + String innerTypeRecursive = propertyDefinition.getSchema().getProperty().getType(); + convValue = valueConverter.convertToToscaValue(json, innerTypeRecursive, dataTypes); + } else { + convValue = handleComplexJsonValue(elementValue); + } + } + } else { + convValue = convertToToscaValue(elementValue.toString(), type, dataTypes); + } + } + } else { + if (elementValue.isJsonPrimitive()) { + convValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive()); + } else { + convValue = handleComplexJsonValue(elementValue); + } + } + if(preserveEmptyValue || !isEmptyObjectValue(convValue)){ + toscaObjectPresentation.put(propName, convValue); + } + } + convertedValue = toscaObjectPresentation; + return convertedValue; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java index e228d256c2..01cf47a124 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java @@ -20,24 +20,24 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class ToscaStringConvertor implements ToscaValueConverter { - private static ToscaStringConvertor stringConverter = new ToscaStringConvertor(); + private static ToscaStringConvertor stringConverter = new ToscaStringConvertor(); - public static ToscaStringConvertor getInstance() { - return stringConverter; - } + public static ToscaStringConvertor getInstance() { + return stringConverter; + } - private ToscaStringConvertor() { + private ToscaStringConvertor() { - } + } - @Override - public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - return value; - } + @Override + public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + return value; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java index 7e2f8766ba..e57650b8a6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java @@ -20,158 +20,147 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - +import com.google.gson.*; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; +import java.util.*; +import java.util.Map.Entry; public class ToscaValueBaseConverter { - protected Gson gson = new Gson(); - private static Logger log = LoggerFactory.getLogger(ToscaValueBaseConverter.class.getName()); - - protected Map<String, PropertyDefinition> getAllProperties(DataTypeDefinition dataTypeDefinition) { - - Map<String, PropertyDefinition> allParentsProps = new HashMap<>(); - - while (dataTypeDefinition != null) { - - List<PropertyDefinition> currentParentsProps = dataTypeDefinition.getProperties(); - if (currentParentsProps != null) { - currentParentsProps.stream().forEach(p -> allParentsProps.put(p.getName(), p)); - } - - dataTypeDefinition = dataTypeDefinition.getDerivedFrom(); - } - - return allParentsProps; - } - - public ToscaPropertyType isScalarType(DataTypeDefinition dataTypeDef) { - - ToscaPropertyType result = null; - - DataTypeDefinition dataType = dataTypeDef; - - while (dataType != null) { - - String name = dataType.getName(); - ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(name); - if (typeIfScalar != null) { - result = typeIfScalar; - break; - } - - dataType = dataType.getDerivedFrom(); - } - - return result; - } - - public Object handleComplexJsonValue(JsonElement elementValue) { - Object jsonValue = null; - - Map<String, Object> value = new HashMap<String, Object>(); - if (elementValue.isJsonObject()) { - JsonObject jsonOb = elementValue.getAsJsonObject(); - Set<Entry<String, JsonElement>> entrySet = jsonOb.entrySet(); - Iterator<Entry<String, JsonElement>> iteratorEntry = entrySet.iterator(); - while (iteratorEntry.hasNext()) { - Entry<String, JsonElement> entry = iteratorEntry.next(); - if (entry.getValue().isJsonArray()) { - List<Object> array = handleJsonArray(entry.getValue()); - value.put(entry.getKey(), array); - } else { - Object object; - if (entry.getValue().isJsonPrimitive()) { - object = json2JavaPrimitive(entry.getValue().getAsJsonPrimitive()); - } else { - object = handleComplexJsonValue(entry.getValue()); - } - value.put(entry.getKey(), object); - } - } - jsonValue = value; - } else { - if (elementValue.isJsonArray()) { - jsonValue = handleJsonArray(elementValue); - } else { - if (elementValue.isJsonPrimitive()) { - jsonValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive()); - } else { - log.debug("not supported json type {} ", elementValue); - } - } - } - - return jsonValue; - } - - private List<Object> handleJsonArray(JsonElement entry) { - List<Object> array = new ArrayList<>(); - JsonArray jsonArray = entry.getAsJsonArray(); - Iterator<JsonElement> iterator = jsonArray.iterator(); - while (iterator.hasNext()) { - Object object; - JsonElement element = iterator.next(); - if (element.isJsonPrimitive()) { - object = json2JavaPrimitive(element.getAsJsonPrimitive()); - } else { - object = handleComplexJsonValue(element); - } - array.add(object); - } - return array; - } - - public Object json2JavaPrimitive(JsonPrimitive prim) { - if (prim.isBoolean()) { - return prim.getAsBoolean(); - } else if (prim.isString()) { - return prim.getAsString(); - } else if (prim.isNumber()) { - String strRepesentation = prim.getAsString(); - if (strRepesentation.contains(".")) { - return prim.getAsDouble(); - } else { - return prim.getAsInt(); - } - } else { - throw new IllegalStateException(); - } - } - - /** - * checks is received Object empty or equals null or not It is relevant only - * if received Object is instance of String, Map or List class. - * - * @param convertedValue - * @return - */ - static public boolean isEmptyObjectValue(Object convertedValue) { - if (convertedValue == null) { - return true; - } else if (convertedValue instanceof String && ((String) convertedValue).isEmpty()) { - return true; - } else if (convertedValue instanceof Map && ((Map) convertedValue).isEmpty()) { - return true; - } else if (convertedValue instanceof List && ((List) convertedValue).isEmpty()) { - return true; - } - return false; - } + protected Gson gson = new Gson(); + private static final Logger log = Logger.getLogger(ToscaValueBaseConverter.class.getName()); + + protected Map<String, PropertyDefinition> getAllProperties(DataTypeDefinition dataTypeDefinition) { + + Map<String, PropertyDefinition> allParentsProps = new HashMap<>(); + + while (dataTypeDefinition != null) { + + List<PropertyDefinition> currentParentsProps = dataTypeDefinition.getProperties(); + if (currentParentsProps != null) { + currentParentsProps.stream().forEach(p -> allParentsProps.put(p.getName(), p)); + } + + dataTypeDefinition = dataTypeDefinition.getDerivedFrom(); + } + + return allParentsProps; + } + + public ToscaPropertyType isScalarType(DataTypeDefinition dataTypeDef) { + + ToscaPropertyType result = null; + + DataTypeDefinition dataType = dataTypeDef; + + while (dataType != null) { + + String name = dataType.getName(); + ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(name); + if (typeIfScalar != null) { + result = typeIfScalar; + break; + } + + dataType = dataType.getDerivedFrom(); + } + + return result; + } + + public Object handleComplexJsonValue(JsonElement elementValue) { + Object jsonValue = null; + + Map<String, Object> value = new HashMap<>(); + if (elementValue.isJsonObject()) { + JsonObject jsonOb = elementValue.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySet = jsonOb.entrySet(); + Iterator<Entry<String, JsonElement>> iteratorEntry = entrySet.iterator(); + while (iteratorEntry.hasNext()) { + Entry<String, JsonElement> entry = iteratorEntry.next(); + if (entry.getValue().isJsonArray()) { + List<Object> array = handleJsonArray(entry.getValue()); + value.put(entry.getKey(), array); + } else { + Object object; + if (entry.getValue().isJsonPrimitive()) { + object = json2JavaPrimitive(entry.getValue().getAsJsonPrimitive()); + } else { + object = handleComplexJsonValue(entry.getValue()); + } + value.put(entry.getKey(), object); + } + } + jsonValue = value; + } else { + if (elementValue.isJsonArray()) { + jsonValue = handleJsonArray(elementValue); + } else { + if (elementValue.isJsonPrimitive()) { + jsonValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive()); + } else { + log.debug("not supported json type {} ", elementValue); + } + } + } + + return jsonValue; + } + + private List<Object> handleJsonArray(JsonElement entry) { + List<Object> array = new ArrayList<>(); + JsonArray jsonArray = entry.getAsJsonArray(); + Iterator<JsonElement> iterator = jsonArray.iterator(); + while (iterator.hasNext()) { + Object object; + JsonElement element = iterator.next(); + if (element.isJsonPrimitive()) { + object = json2JavaPrimitive(element.getAsJsonPrimitive()); + } else { + object = handleComplexJsonValue(element); + } + array.add(object); + } + return array; + } + + public Object json2JavaPrimitive(JsonPrimitive prim) { + if (prim.isBoolean()) { + return prim.getAsBoolean(); + } else if (prim.isString()) { + return prim.getAsString(); + } else if (prim.isNumber()) { + String strRepesentation = prim.getAsString(); + if (strRepesentation.contains(".")) { + return prim.getAsDouble(); + } else { + return prim.getAsInt(); + } + } else { + throw new IllegalStateException(); + } + } + + /** + * checks is received Object empty or equals null or not It is relevant only + * if received Object is instance of String, Map or List class. + * + * @param convertedValue + * @return + */ + static public boolean isEmptyObjectValue(Object convertedValue) { + if (convertedValue == null) { + return true; + } else if (convertedValue instanceof String && ((String) convertedValue).isEmpty()) { + return true; + } else if (convertedValue instanceof Map && ((Map) convertedValue).isEmpty()) { + return true; + } else if (convertedValue instanceof List && ((List) convertedValue).isEmpty()) { + return true; + } + return false; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java index 1b5d4697be..a9d3cb9544 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java @@ -20,11 +20,11 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public interface ToscaValueConverter { - Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes); + Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java index b6eb24276e..ca0724dfc0 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java @@ -20,24 +20,24 @@ package org.openecomp.sdc.be.model.tosca.converters; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class ToscaValueDefaultConverter implements ToscaValueConverter { - private static ToscaValueDefaultConverter deafultConverter = new ToscaValueDefaultConverter(); + private static ToscaValueDefaultConverter deafultConverter = new ToscaValueDefaultConverter(); - public static ToscaValueDefaultConverter getInstance() { - return deafultConverter; - } + public static ToscaValueDefaultConverter getInstance() { + return deafultConverter; + } - private ToscaValueDefaultConverter() { + private ToscaValueDefaultConverter() { - } + } - @Override - public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - return value; - } + @Override + public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + return value; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java index def0e7c391..443334db52 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java @@ -20,36 +20,36 @@ package org.openecomp.sdc.be.model.tosca.validators; +import org.openecomp.sdc.be.model.DataTypeDefinition; + import java.util.Arrays; import java.util.Map; -import org.openecomp.sdc.be.model.DataTypeDefinition; - public class BooleanValidator implements PropertyTypeValidator { - private static BooleanValidator booleanValidator = new BooleanValidator(); - private static String[] validValues = { "true", "t", "on", "yes", "y", "1", "false", "f", "off", "no", "n", "0" }; + private static BooleanValidator booleanValidator = new BooleanValidator(); + private static String[] validValues = { "true", "t", "on", "yes", "y", "1", "false", "f", "off", "no", "n", "0" }; - public static BooleanValidator getInstance() { - return booleanValidator; - } + public static BooleanValidator getInstance() { + return booleanValidator; + } - private BooleanValidator() { + private BooleanValidator() { - } + } - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - if (value == null || true == value.isEmpty()) { - return true; - } + if (value == null || value.isEmpty()) { + return true; + } - return (Arrays.stream(validValues).filter(str -> str.equalsIgnoreCase(value)).toArray().length == 1); - } + return (Arrays.stream(validValues).filter(str -> str.equalsIgnoreCase(value)).toArray().length == 1); + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, null, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, null, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java index ed58bc221b..c64e47a14a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java @@ -20,420 +20,414 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - +import com.google.gson.*; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSyntaxException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; public class DataTypeValidatorConverter { - private static DataTypeValidatorConverter dataTypeValidatorConverter = new DataTypeValidatorConverter(); + private static DataTypeValidatorConverter dataTypeValidatorConverter = new DataTypeValidatorConverter(); - public static DataTypeValidatorConverter getInstance() { - return dataTypeValidatorConverter; - } + public static DataTypeValidatorConverter getInstance() { + return dataTypeValidatorConverter; + } - private DataTypeValidatorConverter() { + private DataTypeValidatorConverter() { - } + } - private static Logger log = LoggerFactory.getLogger(DataTypeValidatorConverter.class.getName()); + private static final Logger log = Logger.getLogger(DataTypeValidatorConverter.class.getName()); - JsonParser jsonParser = new JsonParser(); + JsonParser jsonParser = new JsonParser(); - ImmutablePair<JsonElement, Boolean> falseResult = new ImmutablePair<JsonElement, Boolean>(null, false); - ImmutablePair<JsonElement, Boolean> trueEmptyResult = new ImmutablePair<JsonElement, Boolean>(null, true); + ImmutablePair<JsonElement, Boolean> falseResult = new ImmutablePair<>(null, false); + ImmutablePair<JsonElement, Boolean> trueEmptyResult = new ImmutablePair<>(null, true); - ImmutablePair<String, Boolean> trueStringEmptyResult = new ImmutablePair<String, Boolean>(null, true); - ImmutablePair<String, Boolean> falseStringEmptyResult = new ImmutablePair<String, Boolean>(null, true); + ImmutablePair<String, Boolean> trueStringEmptyResult = new ImmutablePair<>(null, true); + ImmutablePair<String, Boolean> falseStringEmptyResult = new ImmutablePair<>(null, true); - private ToscaPropertyType isDataTypeDerviedFromScalarType(DataTypeDefinition dataTypeDef) { + private ToscaPropertyType isDataTypeDerviedFromScalarType(DataTypeDefinition dataTypeDef) { - ToscaPropertyType result = null; + ToscaPropertyType result = null; - DataTypeDefinition dataType = dataTypeDef; + DataTypeDefinition dataType = dataTypeDef; - while (dataType != null) { + while (dataType != null) { - String name = dataType.getName(); - ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(name); - if (typeIfScalar != null) { - result = typeIfScalar; - break; - } + String name = dataType.getName(); + ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(name); + if (typeIfScalar != null) { + result = typeIfScalar; + break; + } - dataType = dataType.getDerivedFrom(); - } + dataType = dataType.getDerivedFrom(); + } - return result; - } + return result; + } - private ImmutablePair<JsonElement, Boolean> validateAndUpdate(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { - - Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); - - ToscaPropertyType toscaPropertyType = null; - if ((toscaPropertyType = isDataTypeDerviedFromScalarType(dataTypeDefinition)) != null) { - - PropertyTypeValidator validator = toscaPropertyType.getValidator(); - PropertyValueConverter converter = toscaPropertyType.getConverter(); - if (jsonElement == null || true == jsonElement.isJsonNull()) { - boolean valid = validator.isValid(null, null, allDataTypes); - if (!valid) { - log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName()); - return falseResult; - } - return new ImmutablePair<JsonElement, Boolean>(jsonElement, true); - - } else { - if (jsonElement.isJsonPrimitive()) { - String value = null; - if (jsonElement != null) { - if (jsonElement.toString().isEmpty()) { - value = ""; - } else { - value = jsonElement.toString(); - } - } - boolean valid = validator.isValid(value, null, null); - if (!valid) { - log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(), dataTypeDefinition.getName(), value); - return falseResult; - } - - String convertedValue = converter.convert(value, null, allDataTypes); - JsonElement element = null; - try { - element = jsonParser.parse(convertedValue); - } catch (JsonSyntaxException e) { - log.debug("Failed to parse value {} of property {} {}", convertedValue, dataTypeDefinition.getName(), e); - return falseResult; - } - - return new ImmutablePair<JsonElement, Boolean>(element, true); - - } else { - // MAP, LIST, OTHER types cannot be applied data type - // definition scalar type. We currently cannot derived from - // map/list. (cannot add the entry schema to it) - log.debug("We cannot derive from list/map. Thus, the value cannot be not primitive since the data type {} is scalar one", dataTypeDefinition.getName()); - - return falseResult; - } - } - } else { - - if (jsonElement == null || jsonElement.isJsonNull()) { - - return new ImmutablePair<JsonElement, Boolean>(jsonElement, true); - - } else { - - if (jsonElement.isJsonObject()) { - - JsonObject buildJsonObject = new JsonObject(); - - JsonObject asJsonObject = jsonElement.getAsJsonObject(); - Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); - - for (Entry<String, JsonElement> entry : entrySet) { - String propName = entry.getKey(); - - JsonElement elementValue = entry.getValue(); - - PropertyDefinition propertyDefinition = allProperties.get(propName); - if (propertyDefinition == null) { - log.debug("The property {} was not found under data type {}" ,propName, dataTypeDefinition.getName()); - return falseResult; - } - String type = propertyDefinition.getType(); - boolean isScalarType = ToscaPropertyType.isScalarType(type); - - if (isScalarType) { - ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); - if (propertyType == null) { - log.debug("cannot find the {} under default tosca property types", type); - return falseResult; - } - PropertyTypeValidator validator = propertyType.getValidator(); - String innerType = null; - if (propertyType == ToscaPropertyType.LIST || propertyType == ToscaPropertyType.MAP) { - if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() != null) { - innerType = propertyDefinition.getSchema().getProperty().getType(); - if (innerType == null) { - log.debug("Property type {} must have inner type in its declaration.", propertyType); - return falseResult; - } - } - } - - String value = null; - if (elementValue != null) { - if (elementValue.isJsonPrimitive() && elementValue.getAsString().isEmpty()) { - value = ""; - } else { - value = elementValue.toString(); - } - } - - boolean isValid = validator.isValid(value, innerType, allDataTypes); - if (false == isValid) { - log.debug("Failed to validate the value {} from type {}", value, propertyType); - return falseResult; - } - - PropertyValueConverter converter = propertyType.getConverter(); - String convertedValue = converter.convert(value, innerType, allDataTypes); - - JsonElement element = null; - if (convertedValue != null) { - if (convertedValue.isEmpty()) { - element = new JsonPrimitive(""); - } else { - try { - element = jsonParser.parse(convertedValue); - } catch (JsonSyntaxException e) { - log.debug("Failed to parse value {} of type {}", convertedValue, propertyType, e); - return falseResult; - } - } - } - buildJsonObject.add(propName, element); - - } else { - - DataTypeDefinition typeDefinition = allDataTypes.get(type); - if (typeDefinition == null) { - log.debug("The data type {} cannot be found in the given data type list.", type); - return falseResult; - } + private ImmutablePair<JsonElement, Boolean> validateAndUpdate(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { + + Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); + + ToscaPropertyType toscaPropertyType = null; + if ((toscaPropertyType = isDataTypeDerviedFromScalarType(dataTypeDefinition)) != null) { + + PropertyTypeValidator validator = toscaPropertyType.getValidator(); + PropertyValueConverter converter = toscaPropertyType.getConverter(); + if (jsonElement == null || jsonElement.isJsonNull()) { + boolean valid = validator.isValid(null, null, allDataTypes); + if (!valid) { + log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName()); + return falseResult; + } + return new ImmutablePair<>(jsonElement, true); + + } else { + if (jsonElement.isJsonPrimitive()) { + String value = null; + if (jsonElement != null) { + if (jsonElement.toString().isEmpty()) { + value = ""; + } else { + value = jsonElement.toString(); + } + } + boolean valid = validator.isValid(value, null, null); + if (!valid) { + log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(), dataTypeDefinition.getName(), value); + return falseResult; + } + + String convertedValue = converter.convert(value, null, allDataTypes); + JsonElement element = null; + try { + element = jsonParser.parse(convertedValue); + } catch (JsonSyntaxException e) { + log.debug("Failed to parse value {} of property {} {}", convertedValue, dataTypeDefinition.getName(), e); + return falseResult; + } + + return new ImmutablePair<>(element, true); + + } else { + // MAP, LIST, OTHER types cannot be applied data type + // definition scalar type. We currently cannot derived from + // map/list. (cannot add the entry schema to it) + log.debug("We cannot derive from list/map. Thus, the value cannot be not primitive since the data type {} is scalar one", dataTypeDefinition.getName()); + + return falseResult; + } + } + } else { + + if (jsonElement == null || jsonElement.isJsonNull()) { + + return new ImmutablePair<>(jsonElement, true); + + } else { + + if (jsonElement.isJsonObject()) { + + JsonObject buildJsonObject = new JsonObject(); + + JsonObject asJsonObject = jsonElement.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); + + for (Entry<String, JsonElement> entry : entrySet) { + String propName = entry.getKey(); + + JsonElement elementValue = entry.getValue(); + + PropertyDefinition propertyDefinition = allProperties.get(propName); + if (propertyDefinition == null) { + log.debug("The property {} was not found under data type {}" ,propName, dataTypeDefinition.getName()); + return falseResult; + } + String type = propertyDefinition.getType(); + boolean isScalarType = ToscaPropertyType.isScalarType(type); + + if (isScalarType) { + ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); + if (propertyType == null) { + log.debug("cannot find the {} under default tosca property types", type); + return falseResult; + } + PropertyTypeValidator validator = propertyType.getValidator(); + String innerType = null; + if (propertyType == ToscaPropertyType.LIST || propertyType == ToscaPropertyType.MAP) { + if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() != null) { + innerType = propertyDefinition.getSchema().getProperty().getType(); + if (innerType == null) { + log.debug("Property type {} must have inner type in its declaration.", propertyType); + return falseResult; + } + } + } + + String value = null; + if (elementValue != null) { + if (elementValue.isJsonPrimitive() && elementValue.getAsString().isEmpty()) { + value = ""; + } else { + value = elementValue.toString(); + } + } + + boolean isValid = validator.isValid(value, innerType, allDataTypes); + if (!isValid) { + log.debug("Failed to validate the value {} from type {}", value, propertyType); + return falseResult; + } + + PropertyValueConverter converter = propertyType.getConverter(); + String convertedValue = converter.convert(value, innerType, allDataTypes); + + JsonElement element = null; + if (convertedValue != null) { + if (convertedValue.isEmpty()) { + element = new JsonPrimitive(""); + } else { + try { + element = jsonParser.parse(convertedValue); + } catch (JsonSyntaxException e) { + log.debug("Failed to parse value {} of type {}", convertedValue, propertyType, e); + return falseResult; + } + } + } + buildJsonObject.add(propName, element); + + } else { + + DataTypeDefinition typeDefinition = allDataTypes.get(type); + if (typeDefinition == null) { + log.debug("The data type {} cannot be found in the given data type list.", type); + return falseResult; + } - ImmutablePair<JsonElement, Boolean> isValid = validateAndUpdate(elementValue, typeDefinition, allDataTypes); + ImmutablePair<JsonElement, Boolean> isValid = validateAndUpdate(elementValue, typeDefinition, allDataTypes); - if (!isValid.getRight().booleanValue()) { - log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null), typeDefinition.getName()); - return falseResult; - } - - buildJsonObject.add(propName, isValid.getLeft()); - } - - } - - return new ImmutablePair<JsonElement, Boolean>(buildJsonObject, true); - } else { - log.debug("The value {} of type {} should be json object", (jsonElement != null ? jsonElement.toString() : null), dataTypeDefinition.getName()); - return falseResult; - } - - } - } - - } - - public ImmutablePair<JsonElement, Boolean> validateAndUpdate(String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { - - ImmutablePair<JsonElement, Boolean> result = falseResult; - - if (value == null || value.isEmpty()) { - return trueEmptyResult; - } - - JsonElement jsonElement = null; - try { - jsonElement = jsonParser.parse(value); - } catch (JsonSyntaxException e) { - return falseResult; - } - - result = validateAndUpdate(jsonElement, dataTypeDefinition, allDataTypes); - - return result; - } - - private Map<String, PropertyDefinition> getAllProperties(DataTypeDefinition dataTypeDefinition) { - - Map<String, PropertyDefinition> allParentsProps = new HashMap<String, PropertyDefinition>(); - - while (dataTypeDefinition != null) { - - List<PropertyDefinition> currentParentsProps = dataTypeDefinition.getProperties(); - if (currentParentsProps != null) { - currentParentsProps.stream().forEach(p -> allParentsProps.put(p.getName(), p)); - } - - dataTypeDefinition = dataTypeDefinition.getDerivedFrom(); - } - - return allParentsProps; - } - - public boolean isValid(String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { - - boolean result = false; - - if (value == null || value.isEmpty()) { - return true; - } - - JsonElement jsonElement = null; - try { - jsonElement = jsonParser.parse(value); - } catch (JsonSyntaxException e) { - log.debug("Failed to parse the value {} from type {}", value, dataTypeDefinition, e); - return false; - } - - result = isValid(jsonElement, dataTypeDefinition, allDataTypes); - - return result; - } - - private boolean isValid(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { - - Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); - - ToscaPropertyType toscaPropertyType = null; - if ((toscaPropertyType = isDataTypeDerviedFromScalarType(dataTypeDefinition)) != null) { - - PropertyTypeValidator validator = toscaPropertyType.getValidator(); - if (jsonElement == null || true == jsonElement.isJsonNull()) { - boolean valid = validator.isValid(null, null, allDataTypes); - if (false == valid) { - log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName()); - return false; - } - - return true; - - } else { - if (true == jsonElement.isJsonPrimitive()) { - String value = null; - if (jsonElement != null) { - if (jsonElement.toString().isEmpty()) { - value = ""; - } else { - value = jsonElement.toString(); - } - } - boolean valid = validator.isValid(value, null, allDataTypes); - if (false == valid) { - log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(), dataTypeDefinition.getName(), value); - return false; - } - - return true; + if (!isValid.getRight().booleanValue()) { + log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null), typeDefinition.getName()); + return falseResult; + } + + buildJsonObject.add(propName, isValid.getLeft()); + } + + } + + return new ImmutablePair<>(buildJsonObject, true); + } else { + log.debug("The value {} of type {} should be json object", (jsonElement != null ? jsonElement.toString() : null), dataTypeDefinition.getName()); + return falseResult; + } + + } + } + + } + + public ImmutablePair<JsonElement, Boolean> validateAndUpdate(String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { + + ImmutablePair<JsonElement, Boolean> result = falseResult; + + if (value == null || value.isEmpty()) { + return trueEmptyResult; + } + + JsonElement jsonElement = null; + try { + jsonElement = jsonParser.parse(value); + } catch (JsonSyntaxException e) { + return falseResult; + } + + result = validateAndUpdate(jsonElement, dataTypeDefinition, allDataTypes); + + return result; + } + + private Map<String, PropertyDefinition> getAllProperties(DataTypeDefinition dataTypeDefinition) { + + Map<String, PropertyDefinition> allParentsProps = new HashMap<>(); + + while (dataTypeDefinition != null) { + + List<PropertyDefinition> currentParentsProps = dataTypeDefinition.getProperties(); + if (currentParentsProps != null) { + currentParentsProps.stream().forEach(p -> allParentsProps.put(p.getName(), p)); + } + + dataTypeDefinition = dataTypeDefinition.getDerivedFrom(); + } + + return allParentsProps; + } + + public boolean isValid(String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { + + boolean result = false; + + if (value == null || value.isEmpty()) { + return true; + } + + JsonElement jsonElement = null; + try { + jsonElement = jsonParser.parse(value); + } catch (JsonSyntaxException e) { + log.debug("Failed to parse the value {} from type {}", value, dataTypeDefinition, e); + return false; + } + + result = isValid(jsonElement, dataTypeDefinition, allDataTypes); + + return result; + } + + private boolean isValid(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { + + Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); + + ToscaPropertyType toscaPropertyType = null; + if ((toscaPropertyType = isDataTypeDerviedFromScalarType(dataTypeDefinition)) != null) { + + PropertyTypeValidator validator = toscaPropertyType.getValidator(); + if (jsonElement == null || jsonElement.isJsonNull()) { + boolean valid = validator.isValid(null, null, allDataTypes); + if (!valid) { + log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName()); + return false; + } + + return true; + + } else { + if (jsonElement.isJsonPrimitive()) { + String value = null; + if (jsonElement != null) { + if (jsonElement.toString().isEmpty()) { + value = ""; + } else { + value = jsonElement.toString(); + } + } + boolean valid = validator.isValid(value, null, allDataTypes); + if (!valid) { + log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(), dataTypeDefinition.getName(), value); + return false; + } + + return true; - } else { - // MAP, LIST, OTHER types cannot be applied data type - // definition scalar type. We currently cannot derived from - // map/list. (cannot add the entry schema to it) - log.debug("We cannot derive from list/map. Thus, the value cannot be not primitive since the data type {} is scalar one", dataTypeDefinition.getName()); - - return false; - } - } - } else { - - if (jsonElement == null || jsonElement.isJsonNull()) { - - return true; - - } else { - - if (jsonElement.isJsonObject()) { - - JsonObject asJsonObject = jsonElement.getAsJsonObject(); - Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); - - for (Entry<String, JsonElement> entry : entrySet) { - String propName = entry.getKey(); - - JsonElement elementValue = entry.getValue(); - - PropertyDefinition propertyDefinition = allProperties.get(propName); - if (propertyDefinition == null) { - log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName()); - return false; - } - String type = propertyDefinition.getType(); - boolean isScalarType = ToscaPropertyType.isScalarType(type); - - if (true == isScalarType) { - ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); - if (propertyType == null) { - log.debug("cannot find the {} under default tosca property types", type); - return false; - } - PropertyTypeValidator validator = propertyType.getValidator(); - String innerType = null; - if (propertyType == ToscaPropertyType.LIST || propertyType == ToscaPropertyType.MAP) { - if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() != null) { - innerType = propertyDefinition.getSchema().getProperty().getType(); - if (innerType == null) { - log.debug("Property type {} must have inner type in its declaration.", propertyType); - return false; - } - } - } - - String value = null; - if (elementValue != null) { - if (elementValue.isJsonPrimitive() && elementValue.getAsString().isEmpty()) { - value = ""; - } else { - value = elementValue.toString(); - } - } - - boolean isValid = validator.isValid(value, innerType, allDataTypes); - if (false == isValid) { - log.debug("Failed to validate the value {} from type {}", value, propertyType); - return false; - } - - } else { - - DataTypeDefinition typeDefinition = allDataTypes.get(type); - if (typeDefinition == null) { - log.debug("The data type {} cannot be found in the given data type list.", type); - return false; - } - - boolean isValid = isValid(elementValue, typeDefinition, allDataTypes); - - if (false == isValid) { - log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null), typeDefinition.getName()); - return false; - } - - } - - } - - return true; - } else { - log.debug("The value {} of type {} should be json object", (jsonElement != null ? jsonElement.toString() : null), dataTypeDefinition.getName()); - return false; - } - - } - } - - } + } else { + // MAP, LIST, OTHER types cannot be applied data type + // definition scalar type. We currently cannot derived from + // map/list. (cannot add the entry schema to it) + log.debug("We cannot derive from list/map. Thus, the value cannot be not primitive since the data type {} is scalar one", dataTypeDefinition.getName()); + + return false; + } + } + } else { + + if (jsonElement == null || jsonElement.isJsonNull()) { + + return true; + + } else { + + if (jsonElement.isJsonObject()) { + + JsonObject asJsonObject = jsonElement.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); + + for (Entry<String, JsonElement> entry : entrySet) { + String propName = entry.getKey(); + + JsonElement elementValue = entry.getValue(); + + PropertyDefinition propertyDefinition = allProperties.get(propName); + if (propertyDefinition == null) { + log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName()); + return false; + } + String type = propertyDefinition.getType(); + boolean isScalarType = ToscaPropertyType.isScalarType(type); + + if (isScalarType) { + ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); + if (propertyType == null) { + log.debug("cannot find the {} under default tosca property types", type); + return false; + } + PropertyTypeValidator validator = propertyType.getValidator(); + String innerType = null; + if (propertyType == ToscaPropertyType.LIST || propertyType == ToscaPropertyType.MAP) { + if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() != null) { + innerType = propertyDefinition.getSchema().getProperty().getType(); + if (innerType == null) { + log.debug("Property type {} must have inner type in its declaration.", propertyType); + return false; + } + } + } + + String value = null; + if (elementValue != null) { + if (elementValue.isJsonPrimitive() && elementValue.getAsString().isEmpty()) { + value = ""; + } else { + value = elementValue.toString(); + } + } + + boolean isValid = validator.isValid(value, innerType, allDataTypes); + if (!isValid) { + log.debug("Failed to validate the value {} from type {}", value, propertyType); + return false; + } + + } else { + + DataTypeDefinition typeDefinition = allDataTypes.get(type); + if (typeDefinition == null) { + log.debug("The data type {} cannot be found in the given data type list.", type); + return false; + } + + boolean isValid = isValid(elementValue, typeDefinition, allDataTypes); + + if (!isValid) { + log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null), typeDefinition.getName()); + return false; + } + + } + + } + + return true; + } else { + log.debug("The value {} of type {} should be json object", (jsonElement != null ? jsonElement.toString() : null), dataTypeDefinition.getName()); + return false; + } + + } + } + + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java index 2518eaa51e..f9121d17ca 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java @@ -20,41 +20,41 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class FloatValidator implements PropertyTypeValidator { - private static FloatValidator FloatValidator = new FloatValidator(); + private static FloatValidator FloatValidator = new FloatValidator(); - public static FloatValidator getInstance() { - return FloatValidator; - } + public static FloatValidator getInstance() { + return FloatValidator; + } - private FloatValidator() { + private FloatValidator() { - } + } - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - if (value == null || true == value.isEmpty()) { - return true; - } + if (value == null || value.isEmpty()) { + return true; + } - try { - Float.parseFloat(value); - } catch (IllegalArgumentException e) { - return false; - } + try { + Float.parseFloat(value); + } catch (IllegalArgumentException e) { + return false; + } - return true; - } + return true; + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java index ec4051e65c..f527206270 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java @@ -20,42 +20,42 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class HeatBooleanValidator implements PropertyTypeValidator { - private static HeatBooleanValidator booleanValidator = new HeatBooleanValidator(); + private static HeatBooleanValidator booleanValidator = new HeatBooleanValidator(); - public static HeatBooleanValidator getInstance() { - return booleanValidator; - } + public static HeatBooleanValidator getInstance() { + return booleanValidator; + } - private HeatBooleanValidator() { + private HeatBooleanValidator() { - } + } - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - if (value == null || true == value.isEmpty()) { - return true; - } + if (value == null || value.isEmpty()) { + return true; + } - if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false") || value.equalsIgnoreCase("t") - || value.equalsIgnoreCase("f") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("off") - || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("y") - || value.equalsIgnoreCase("n") || value.equalsIgnoreCase("1") || value.equalsIgnoreCase("0")) { - return true; - } + if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false") || value.equalsIgnoreCase("t") + || value.equalsIgnoreCase("f") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("off") + || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("y") + || value.equalsIgnoreCase("n") || value.equalsIgnoreCase("1") || value.equalsIgnoreCase("0")) { + return true; + } - return false; - } + return false; + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java index 464dbf0975..6a2a13402b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java @@ -20,36 +20,36 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.common.util.ValidationUtils; +import java.util.Map; + public class HeatCommaDelimitedListValidator implements PropertyTypeValidator { - private static HeatCommaDelimitedListValidator stringValidator = new HeatCommaDelimitedListValidator(); + private static HeatCommaDelimitedListValidator stringValidator = new HeatCommaDelimitedListValidator(); - public static HeatCommaDelimitedListValidator getInstance() { - return stringValidator; - } + public static HeatCommaDelimitedListValidator getInstance() { + return stringValidator; + } - private HeatCommaDelimitedListValidator() { + private HeatCommaDelimitedListValidator() { - } + } - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - if (value == null || true == value.isEmpty()) { - return true; - } + if (value == null || value.isEmpty()) { + return true; + } - String coverted = ValidationUtils.removeNoneUtf8Chars(value); - return ValidationUtils.validateIsEnglish(coverted); - } + String coverted = ValidationUtils.removeNoneUtf8Chars(value); + return ValidationUtils.validateIsEnglish(coverted); + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java index 37c4a46829..0ae3f74c85 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java @@ -20,42 +20,42 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class HeatNumberValidator implements PropertyTypeValidator { - private static HeatNumberValidator numberValidator = new HeatNumberValidator(); + private static HeatNumberValidator numberValidator = new HeatNumberValidator(); - private static FloatValidator floatValidator = FloatValidator.getInstance(); - private static IntegerValidator integerValidator = IntegerValidator.getInstance(); + private static FloatValidator floatValidator = FloatValidator.getInstance(); + private static IntegerValidator integerValidator = IntegerValidator.getInstance(); - public static HeatNumberValidator getInstance() { - return numberValidator; - } + public static HeatNumberValidator getInstance() { + return numberValidator; + } - private HeatNumberValidator() { + private HeatNumberValidator() { - } + } - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - if (value == null || true == value.isEmpty()) { - return true; - } - boolean valid = integerValidator.isValid(value, null, allDataTypes); + if (value == null || value.isEmpty()) { + return true; + } + boolean valid = integerValidator.isValid(value, null, allDataTypes); - if (!valid) { - valid = floatValidator.isValid(value, null, allDataTypes); - } + if (!valid) { + valid = floatValidator.isValid(value, null, allDataTypes); + } - return valid; - } + return valid; + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java index 8c63090e03..fd71647b8d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java @@ -20,36 +20,36 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.common.util.ValidationUtils; +import java.util.Map; + public class HeatStringValidator implements PropertyTypeValidator { - private static HeatStringValidator stringValidator = new HeatStringValidator(); + private static HeatStringValidator stringValidator = new HeatStringValidator(); - public static HeatStringValidator getInstance() { - return stringValidator; - } + public static HeatStringValidator getInstance() { + return stringValidator; + } - private HeatStringValidator() { + private HeatStringValidator() { - } + } - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - if (value == null || true == value.isEmpty()) { - return true; - } + if (value == null || value.isEmpty()) { + return true; + } - String converted = ValidationUtils.removeNoneUtf8Chars(value); - return ValidationUtils.validateIsEnglish(converted); - } + String converted = ValidationUtils.removeNoneUtf8Chars(value); + return ValidationUtils.validateIsEnglish(converted); + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java index 61d321c45e..484f88e37a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java @@ -20,66 +20,66 @@ package org.openecomp.sdc.be.model.tosca.validators; +import org.openecomp.sdc.be.model.DataTypeDefinition; + import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.openecomp.sdc.be.model.DataTypeDefinition; - public class IntegerValidator implements PropertyTypeValidator { - private static IntegerValidator integerValidator = new IntegerValidator(); + private static IntegerValidator integerValidator = new IntegerValidator(); - private IntegerValidator() { - } + private IntegerValidator() { + } - public static IntegerValidator getInstance() { - return integerValidator; - } + public static IntegerValidator getInstance() { + return integerValidator; + } - private class PatternBase { - public PatternBase(Pattern pattern, Integer base) { - this.pattern = pattern; - this.base = base; - } + private class PatternBase { + public PatternBase(Pattern pattern, Integer base) { + this.pattern = pattern; + this.base = base; + } - Pattern pattern; - Integer base; - } + Pattern pattern; + Integer base; + } - private PatternBase base8Pattern = new PatternBase(Pattern.compile("([-+])?0o([0-7]+)"), 8); - private PatternBase base10Pattern = new PatternBase(Pattern.compile("([-+])?(0|[1-9][0-9]*)"), 10); - private PatternBase base16Pattern = new PatternBase(Pattern.compile("([-+])?0x([0-9a-fA-F]+)"), 16); + private PatternBase base8Pattern = new PatternBase(Pattern.compile("([-+])?0o([0-7]+)"), 8); + private PatternBase base10Pattern = new PatternBase(Pattern.compile("([-+])?(0|[1-9][0-9]*)"), 10); + private PatternBase base16Pattern = new PatternBase(Pattern.compile("([-+])?0x([0-9a-fA-F]+)"), 16); - private PatternBase[] patterns = { base10Pattern, base8Pattern, base16Pattern }; + private PatternBase[] patterns = { base10Pattern, base8Pattern, base16Pattern }; - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - if (value == null || true == value.isEmpty()) { - return true; - } + if (value == null || value.isEmpty()) { + return true; + } - for (PatternBase patternBase : patterns) { - Matcher matcher = patternBase.pattern.matcher(value); - Long parsed = null; - if (matcher.matches()) { - try { - parsed = Long.parseLong(matcher.group(2), patternBase.base); - if (matcher.group(1) != null && matcher.group(1).compareTo("-") == 0) { - parsed *= -1; - } - return (Integer.MIN_VALUE <= parsed && parsed <= (Integer.MAX_VALUE)) ? true : false; - } catch (NumberFormatException e) { - return false; - } - } - } - return false; - } + for (PatternBase patternBase : patterns) { + Matcher matcher = patternBase.pattern.matcher(value); + Long parsed = null; + if (matcher.matches()) { + try { + parsed = Long.parseLong(matcher.group(2), patternBase.base); + if (matcher.group(1) != null && matcher.group(1).compareTo("-") == 0) { + parsed *= -1; + } + return (Integer.MIN_VALUE <= parsed && parsed <= (Integer.MAX_VALUE)) ? true : false; + } catch (NumberFormatException e) { + return false; + } + } + } + return false; + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java index 6a1aff558f..77fcf5214a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java @@ -20,50 +20,48 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.io.StringReader; -import java.util.Map; - -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import com.google.gson.stream.JsonReader; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.io.StringReader; +import java.util.Map; public class JsonValidator implements PropertyTypeValidator { - private static JsonValidator jsonValidator = new JsonValidator(); + private static JsonValidator jsonValidator = new JsonValidator(); - private static Logger log = LoggerFactory.getLogger(JsonValidator.class.getName()); + private static final Logger log = Logger.getLogger(JsonValidator.class.getName()); - private static JsonParser jsonParser = new JsonParser(); + private static JsonParser jsonParser = new JsonParser(); - public static JsonValidator getInstance() { - return jsonValidator; - } + public static JsonValidator getInstance() { + return jsonValidator; + } - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - if (value == null || value.isEmpty()) { - return true; - } - try { - StringReader reader = new StringReader(value); - JsonReader jsonReader = new JsonReader(reader); - jsonReader.setLenient(true); - jsonParser.parse(jsonReader); - } catch (JsonSyntaxException e) { - log.debug("Error parsing JSON property", e); - return false; - } - return true; + if (value == null || value.isEmpty()) { + return true; + } + try { + StringReader reader = new StringReader(value); + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + jsonParser.parse(jsonReader); + } catch (JsonSyntaxException e) { + log.debug("Error parsing JSON property", e); + return false; + } + return true; - } + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java index 73b5e939ef..07e123376a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java @@ -20,42 +20,42 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.common.util.ValidationUtils; +import java.util.Map; + public class KeyValidator implements PropertyTypeValidator { - public static final int STRING_MAXIMUM_LENGTH = 100; + public static final int STRING_MAXIMUM_LENGTH = 100; - private static KeyValidator keyValidator = new KeyValidator(); + private static KeyValidator keyValidator = new KeyValidator(); - public static KeyValidator getInstance() { - return keyValidator; - } + public static KeyValidator getInstance() { + return keyValidator; + } - private KeyValidator() { + private KeyValidator() { - } + } - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - if (value == null || true == value.isEmpty()) { - return false; - } + if (value == null || value.isEmpty()) { + return false; + } - if (value.length() > STRING_MAXIMUM_LENGTH) { - return false; - } - String converted = ValidationUtils.removeNoneUtf8Chars(value); - return ValidationUtils.validateIsEnglish(converted); - } + if (value.length() > STRING_MAXIMUM_LENGTH) { + return false; + } + String converted = ValidationUtils.removeNoneUtf8Chars(value); + return ValidationUtils.validateIsEnglish(converted); + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java index 8eb784029b..ed40964614 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java @@ -20,141 +20,138 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.JsonUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; +import java.util.Map; public class ListValidator implements PropertyTypeValidator { - private static ListValidator listValidator = new ListValidator(); - - private static Logger log = LoggerFactory.getLogger(ListValidator.class.getName()); - - private static JsonParser jsonParser = new JsonParser(); - - private static DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - - public static ListValidator getInstance() { - return listValidator; - } - - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - - log.debug("Going to validate value {} with inner type {}", value, innerType); - - if (value == null || value == "") { - return true; - } - if (innerType == null) { - return false; - } - - PropertyTypeValidator innerValidator; - - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); - - if (innerToscaType != null) { - switch (innerToscaType) { - case STRING: - innerValidator = ToscaPropertyType.STRING.getValidator(); - break; - case INTEGER: - innerValidator = ToscaPropertyType.INTEGER.getValidator(); - break; - case FLOAT: - innerValidator = ToscaPropertyType.FLOAT.getValidator(); - break; - case BOOLEAN: - innerValidator = ToscaPropertyType.BOOLEAN.getValidator(); - break; - case JSON: - innerValidator = ToscaPropertyType.JSON.getValidator(); - break; - default: - log.debug("inner Tosca Type is unknown. {}", innerToscaType); - return false; - } - - } else { - log.debug("inner Tosca Type is: {}", innerType); - - boolean isValid = validateComplexInnerType(value, innerType, allDataTypes); - log.debug("Finish to validate value {} of list with inner type {}. result is {}",value,innerType,isValid); - return isValid; - } - - try { - JsonArray jo = (JsonArray) jsonParser.parse(value); - if(ToscaPropertyType.JSON == innerToscaType) - return true; - int size = jo.size(); - for (int i = 0; i < size; i++) { - JsonElement currentValue = jo.get(i); - String element = JsonUtils.toString(currentValue); - if (!innerValidator.isValid(element, null, allDataTypes)) { - log.debug("validation of element : {} failed", element); - return false; - } - - } - return true; - - } catch (JsonSyntaxException e) { - log.debug("Failed to parse json : {}", value, e); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Validator"); - } - - return false; - - } - - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } - - private boolean validateComplexInnerType(String value, String innerType, - Map<String, DataTypeDefinition> allDataTypes) { - - DataTypeDefinition innerDataTypeDefinition = allDataTypes.get(innerType); - if (innerDataTypeDefinition == null) { - log.debug("Data type {} cannot be found in our data types.", innerType); - return false; - } - - try { - - JsonArray jo = (JsonArray) jsonParser.parse(value); - int size = jo.size(); - for (int i = 0; i < size; i++) { - JsonElement currentValue = jo.get(i); - if (currentValue != null) { - String element = JsonUtils.toString(currentValue); - boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition, - allDataTypes); - if (isValid == false) { - log.debug("Cannot parse value {} from type {} in list parameter",currentValue,innerType); - return false; - } - } - } - - } catch (Exception e) { - log.debug("Error when parsing JSON of object of type ", e); - return false; - } - - return true; - } + private static ListValidator listValidator = new ListValidator(); + + private static final Logger log = Logger.getLogger(ListValidator.class.getName()); + + private static JsonParser jsonParser = new JsonParser(); + + private static DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + + public static ListValidator getInstance() { + return listValidator; + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + log.debug("Going to validate value {} with inner type {}", value, innerType); + + if (value == null || value == "") { + return true; + } + if (innerType == null) { + return false; + } + + PropertyTypeValidator innerValidator; + + ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); + + if (innerToscaType != null) { + switch (innerToscaType) { + case STRING: + innerValidator = ToscaPropertyType.STRING.getValidator(); + break; + case INTEGER: + innerValidator = ToscaPropertyType.INTEGER.getValidator(); + break; + case FLOAT: + innerValidator = ToscaPropertyType.FLOAT.getValidator(); + break; + case BOOLEAN: + innerValidator = ToscaPropertyType.BOOLEAN.getValidator(); + break; + case JSON: + innerValidator = ToscaPropertyType.JSON.getValidator(); + break; + default: + log.debug("inner Tosca Type is unknown. {}", innerToscaType); + return false; + } + + } else { + log.debug("inner Tosca Type is: {}", innerType); + + boolean isValid = validateComplexInnerType(value, innerType, allDataTypes); + log.debug("Finish to validate value {} of list with inner type {}. result is {}",value,innerType,isValid); + return isValid; + } + + try { + JsonArray jo = (JsonArray) jsonParser.parse(value); + if(ToscaPropertyType.JSON == innerToscaType) + return true; + int size = jo.size(); + for (int i = 0; i < size; i++) { + JsonElement currentValue = jo.get(i); + String element = JsonUtils.toString(currentValue); + if (!innerValidator.isValid(element, null, allDataTypes)) { + log.debug("validation of element : {} failed", element); + return false; + } + + } + return true; + + } catch (Exception e) { + log.debug("Failed to parse json : {}", value, e); + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Validator"); + } + + return false; + + } + + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } + + private boolean validateComplexInnerType(String value, String innerType, + Map<String, DataTypeDefinition> allDataTypes) { + + DataTypeDefinition innerDataTypeDefinition = allDataTypes.get(innerType); + if (innerDataTypeDefinition == null) { + log.debug("Data type {} cannot be found in our data types.", innerType); + return false; + } + + try { + + JsonArray jo = (JsonArray) jsonParser.parse(value); + int size = jo.size(); + for (int i = 0; i < size; i++) { + JsonElement currentValue = jo.get(i); + if (currentValue != null) { + String element = JsonUtils.toString(currentValue); + boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition, + allDataTypes); + if (!isValid) { + log.debug("Cannot parse value {} from type {} in list parameter",currentValue,innerType); + return false; + } + } + } + + } catch (Exception e) { + log.debug("Error when parsing JSON of object of type ", e); + return false; + } + + return true; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java index 862766b6fa..996e24ee06 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java @@ -20,22 +20,20 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.JsonUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; /* * Property Type Map correct usage: @@ -47,90 +45,90 @@ validators and converters works the same as before Types: when written line by line : - key1 : val1 - key2 : val2 + key1 : val1 + key2 : val2 key1 and val does not need " " , even if val1 is a string. when written as one line : {"key1":val1 , "key2":val2} Keys always need " " around them. */ public class MapValidator implements PropertyTypeValidator { - private static MapValidator mapValidator = new MapValidator(); - - private static final Logger LOGGER = LoggerFactory.getLogger(MapValidator.class.getName()); - - private static DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - - private static JsonParser jsonParser = new JsonParser(); - - public static MapValidator getInstance() { - return mapValidator; - } - - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - - if (StringUtils.isEmpty(value)) { - return true; - } - if (innerType == null) { - return false; - } - - PropertyTypeValidator innerValidator; - PropertyTypeValidator keyValidator = ToscaPropertyType.KEY.getValidator(); - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); - - if (innerToscaType != null) { - switch (innerToscaType) { - case STRING: - innerValidator = ToscaPropertyType.STRING.getValidator(); - break; - case INTEGER: - innerValidator = ToscaPropertyType.INTEGER.getValidator(); - break; - case FLOAT: - innerValidator = ToscaPropertyType.FLOAT.getValidator(); - break; - case BOOLEAN: - innerValidator = ToscaPropertyType.BOOLEAN.getValidator(); - break; - case JSON: - innerValidator = ToscaPropertyType.JSON.getValidator(); - break; - default: - LOGGER.debug("inner Tosca Type is unknown. {}", innerToscaType); - return false; - } - - } else { - LOGGER.debug("inner Tosca Type is: {}", innerType); - - boolean isValid = validateComplexInnerType(value, innerType, allDataTypes); - LOGGER.debug("Finish to validate value {} of map with inner type {}. result is {}",value,innerType,isValid); - return isValid; - - } - - try { - JsonElement jsonObject = jsonParser.parse(value); - if (!jsonObject.isJsonObject()) { - return false; + private static MapValidator mapValidator = new MapValidator(); + + private static final Logger log = Logger.getLogger(MapValidator.class.getName()); + + private static DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + + private static JsonParser jsonParser = new JsonParser(); + + public static MapValidator getInstance() { + return mapValidator; + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + if (StringUtils.isEmpty(value)) { + return true; + } + if (innerType == null) { + return false; + } + + PropertyTypeValidator innerValidator; + PropertyTypeValidator keyValidator = ToscaPropertyType.KEY.getValidator(); + ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); + + if (innerToscaType != null) { + switch (innerToscaType) { + case STRING: + innerValidator = ToscaPropertyType.STRING.getValidator(); + break; + case INTEGER: + innerValidator = ToscaPropertyType.INTEGER.getValidator(); + break; + case FLOAT: + innerValidator = ToscaPropertyType.FLOAT.getValidator(); + break; + case BOOLEAN: + innerValidator = ToscaPropertyType.BOOLEAN.getValidator(); + break; + case JSON: + innerValidator = ToscaPropertyType.JSON.getValidator(); + break; + default: + log.debug("inner Tosca Type is unknown. {}", innerToscaType); + return false; } - JsonObject valueAsJson = jsonObject.getAsJsonObject(); - return validateJsonObject(allDataTypes, innerValidator, keyValidator, valueAsJson); - } catch (JsonSyntaxException e) { - LOGGER.debug("Failed to parse json : {}", value, e); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Validator"); - } - return false; + } else { + log.debug("inner Tosca Type is: {}", innerType); + + boolean isValid = validateComplexInnerType(value, innerType, allDataTypes); + log.debug("Finish to validate value {} of map with inner type {}. result is {}",value,innerType,isValid); + return isValid; + + } + + try { + JsonElement jsonObject = jsonParser.parse(value); + if (!jsonObject.isJsonObject()) { + return false; + } + JsonObject valueAsJson = jsonObject.getAsJsonObject(); + return validateJsonObject(allDataTypes, innerValidator, keyValidator, valueAsJson); + } catch (JsonSyntaxException e) { + log.debug("Failed to parse json : {}", value, e); + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Validator"); + } - } + return false; - private boolean validateJsonObject(Map<String, DataTypeDefinition> allDataTypes, PropertyTypeValidator innerValidator, PropertyTypeValidator keyValidator, JsonObject asJsonObject) { - Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); - for (Entry<String, JsonElement> entry : entrySet) { + } + + private boolean validateJsonObject(Map<String, DataTypeDefinition> allDataTypes, PropertyTypeValidator innerValidator, PropertyTypeValidator keyValidator, JsonObject asJsonObject) { + Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); + for (Entry<String, JsonElement> entry : entrySet) { String currentKey = entry.getKey(); JsonElement jsonValue = entry.getValue(); @@ -138,52 +136,52 @@ public class MapValidator implements PropertyTypeValidator { if (!innerValidator.isValid(element, null, allDataTypes) || !keyValidator.isValid(entry.getKey(), null, allDataTypes)) { - LOGGER.debug("validation of key : {}, element : {} failed", currentKey, entry.getValue()); + log.debug("validation of key : {}, element : {} failed", currentKey, entry.getValue()); return false; } } - return true; - } - - private boolean validateComplexInnerType(String value, String innerType, - Map<String, DataTypeDefinition> allDataTypes) { - - DataTypeDefinition innerDataTypeDefinition = allDataTypes.get(innerType); - if (innerDataTypeDefinition == null) { - LOGGER.debug("Data type {} cannot be found in our data types.", innerType); - return false; - } - - try { - JsonElement jsonObject = jsonParser.parse(value); - JsonObject asJsonObject = jsonObject.getAsJsonObject(); - Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); - for (Entry<String, JsonElement> entry : entrySet) { - String currentKey = entry.getKey(); - JsonElement currentValue = entry.getValue(); - - if (currentValue != null) { - String element = JsonUtils.toString(currentValue); - boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition, - allDataTypes); - if (!isValid) { - LOGGER.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey); - return false; - } - } - } - - } catch (Exception e) { - LOGGER.debug("Cannot parse value {} of map from inner type {}", value, innerType, e); - return false; - } - - return true; - } - - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + return true; + } + + private boolean validateComplexInnerType(String value, String innerType, + Map<String, DataTypeDefinition> allDataTypes) { + + DataTypeDefinition innerDataTypeDefinition = allDataTypes.get(innerType); + if (innerDataTypeDefinition == null) { + log.debug("Data type {} cannot be found in our data types.", innerType); + return false; + } + + try { + JsonElement jsonObject = jsonParser.parse(value); + JsonObject asJsonObject = jsonObject.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); + for (Entry<String, JsonElement> entry : entrySet) { + String currentKey = entry.getKey(); + JsonElement currentValue = entry.getValue(); + + if (currentValue != null) { + String element = JsonUtils.toString(currentValue); + boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition, + allDataTypes); + if (!isValid) { + log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey); + return false; + } + } + } + + } catch (Exception e) { + log.debug("Cannot parse value {} of map from inner type {}", value, innerType, e); + return false; + } + + return true; + } + + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java index f0cf225c0a..587107a93a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java @@ -20,27 +20,27 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public interface PropertyTypeValidator { - boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes); + boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes); - boolean isValid(String value, String innerType); - /* - * The value format should be validated according to the "Property Type" : - * "integer" - valid tag:yaml.org,2002:int , the number base 8,10,18 should - * be handled ( hint : to validate by calling parseInt( - * s,10)/parseInt(s,16)/parseInt(s,8) or just regexp [-+]?[0-9]+ for Base 10 - * , [-+]?0[0-7]+ for Base 8 , [-+]?0x[0-9a-fA-F]+ for Base 16 - * - * "float" - valid tag:yaml.org,2002:float , parseFloat() "boolean" - valid - * tag:yaml.org,2002:bool : can be only "true" or "false" ( upper case - * characters should be converted to lower case : TRUE ->true, True->true - * "string" - valid tag:yaml.org,2002:str and limited to 100 chars. - * - */ + boolean isValid(String value, String innerType); + /* + * The value format should be validated according to the "Property Type" : + * "integer" - valid tag:yaml.org,2002:int , the number base 8,10,18 should + * be handled ( hint : to validate by calling parseInt( + * s,10)/parseInt(s,16)/parseInt(s,8) or just regexp [-+]?[0-9]+ for Base 10 + * , [-+]?0[0-7]+ for Base 8 , [-+]?0x[0-9a-fA-F]+ for Base 16 + * + * "float" - valid tag:yaml.org,2002:float , parseFloat() "boolean" - valid + * tag:yaml.org,2002:bool : can be only "true" or "false" ( upper case + * characters should be converted to lower case : TRUE ->true, True->true + * "string" - valid tag:yaml.org,2002:str and limited to 100 chars. + * + */ } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java index dad3461c91..cd8d9272f2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java @@ -20,66 +20,65 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; - import org.openecomp.sdc.be.config.Configuration.ToscaValidatorsConfig; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import java.util.Map; public class StringValidator implements PropertyTypeValidator { - public static final int DEFAULT_STRING_MAXIMUM_LENGTH = 2500; - - private static int STRING_MAXIMUM_LENGTH = DEFAULT_STRING_MAXIMUM_LENGTH; - - private static Logger log = LoggerFactory.getLogger(StringValidator.class.getName()); - - private static StringValidator stringValidator = new StringValidator(); - - private StringValidator() { - if (ConfigurationManager.getConfigurationManager() != null) { - ToscaValidatorsConfig toscaValidators = ConfigurationManager.getConfigurationManager().getConfiguration() - .getToscaValidators(); - log.debug("toscaValidators= {}", toscaValidators); - if (toscaValidators != null) { - Integer stringMaxLength = toscaValidators.getStringMaxLength(); - if (stringMaxLength != null) { - STRING_MAXIMUM_LENGTH = stringMaxLength; - } - } - } - } - - public static StringValidator getInstance() { - return stringValidator; - } - - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - - if (value == null || true == value.isEmpty()) { - return true; - } - - if (value.length() > STRING_MAXIMUM_LENGTH) { - log.debug("parameter String length {} is higher than configured({})", value.length(), STRING_MAXIMUM_LENGTH); - return false; - } - String converted = ValidationUtils.removeNoneUtf8Chars(value); - boolean isValid = ValidationUtils.validateIsAscii(converted); - - if (false == isValid && log.isDebugEnabled()) { - log.debug("parameter String value {} is not an ascii string.", value.substring(0, Math.min(value.length(), 20))); - } - - return isValid; - } - - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + public static final int DEFAULT_STRING_MAXIMUM_LENGTH = 2500; + + private static int STRING_MAXIMUM_LENGTH = DEFAULT_STRING_MAXIMUM_LENGTH; + + private static final Logger log = Logger.getLogger(StringValidator.class.getName()); + + private static StringValidator stringValidator = new StringValidator(); + + private StringValidator() { + if (ConfigurationManager.getConfigurationManager() != null) { + ToscaValidatorsConfig toscaValidators = ConfigurationManager.getConfigurationManager().getConfiguration() + .getToscaValidators(); + log.debug("toscaValidators= {}", toscaValidators); + if (toscaValidators != null) { + Integer stringMaxLength = toscaValidators.getStringMaxLength(); + if (stringMaxLength != null) { + STRING_MAXIMUM_LENGTH = stringMaxLength; + } + } + } + } + + public static StringValidator getInstance() { + return stringValidator; + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + if (value == null || value.isEmpty()) { + return true; + } + + if (value.length() > STRING_MAXIMUM_LENGTH) { + log.debug("parameter String length {} is higher than configured({})", value.length(), STRING_MAXIMUM_LENGTH); + return false; + } + String converted = ValidationUtils.removeNoneUtf8Chars(value); + boolean isValid = ValidationUtils.validateIsAscii(converted); + + if (!isValid && log.isDebugEnabled()) { + log.debug("parameter String value {} is not an ascii string.", value.substring(0, Math.min(value.length(), 20))); + } + + return isValid; + } + + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java index 7f8dff42d0..fbec8e8d46 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java @@ -20,37 +20,37 @@ package org.openecomp.sdc.be.model.tosca.validators; +import org.openecomp.sdc.be.model.DataTypeDefinition; + import java.util.Arrays; import java.util.Map; -import org.openecomp.sdc.be.model.DataTypeDefinition; - public class ToscaBooleanValidator implements PropertyTypeValidator { - private static ToscaBooleanValidator booleanValidator = new ToscaBooleanValidator(); + private static ToscaBooleanValidator booleanValidator = new ToscaBooleanValidator(); - private static String[] validValues = { "true", "on", "yes", "y", "false", "off", "no", "n" }; + private static String[] validValues = { "true", "on", "yes", "y", "false", "off", "no", "n" }; - public static ToscaBooleanValidator getInstance() { - return booleanValidator; - } + public static ToscaBooleanValidator getInstance() { + return booleanValidator; + } - private ToscaBooleanValidator() { + private ToscaBooleanValidator() { - } + } - @Override - public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (value == null || true == value.isEmpty()) { - return true; - } + if (value == null || value.isEmpty()) { + return true; + } - return (Arrays.stream(validValues).filter(str -> str.equalsIgnoreCase(value)).toArray().length == 1); - } + return (Arrays.stream(validValues).filter(str -> str.equalsIgnoreCase(value)).toArray().length == 1); + } - @Override - public boolean isValid(String value, String innerType) { - return isValid(value, innerType, null); - } + @Override + public boolean isValid(String value, String innerType) { + return isValid(value, innerType, null); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java index dadfd49831..9dca0389f7 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java @@ -24,13 +24,11 @@ import org.openecomp.sdc.be.model.tosca.constraints.exception.TechnicalException public class ApplicationVersionException extends TechnicalException { - private static final long serialVersionUID = -5192834855057177252L; + public ApplicationVersionException(String message, Throwable cause) { + super(message, cause); + } - public ApplicationVersionException(String message, Throwable cause) { - super(message, cause); - } - - public ApplicationVersionException(String message) { - super(message); - } + public ApplicationVersionException(String message) { + super(message); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java index 905d8bf3bc..e3d8cf06f6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java @@ -40,14 +40,7 @@ package org.openecomp.sdc.be.model.tosca.version; */ import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Locale; -import java.util.Properties; -import java.util.Stack; +import java.util.*; /** * Generic implementation of version comparison. @@ -87,377 +80,374 @@ import java.util.Stack; * @author <a href="mailto:hboutemy@apache.org">Hervé Boutemy</a> */ public class ComparableVersion implements Comparable<ComparableVersion> { - private String value; + private String value; - private String canonical; + private String canonical; - private ListItem items; + private ListItem items; - private interface Item { - int INTEGER_ITEM = 0; - int STRING_ITEM = 1; - int LIST_ITEM = 2; + private interface Item { + int INTEGER_ITEM = 0; + int STRING_ITEM = 1; + int LIST_ITEM = 2; - int compareTo(Item item); + int compareTo(Item item); - int getType(); + int getType(); - boolean isNull(); - } + boolean isNull(); + } - /** - * Represents a numeric item in the version item list. - */ - private static class IntegerItem implements Item { + /** + * Represents a numeric item in the version item list. + */ + private static class IntegerItem implements Item { + private static final String INVALID_ITEM = "invalid item: "; private static final BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); - - private final BigInteger value; - - public static final IntegerItem ZERO = new IntegerItem(); - - private IntegerItem() { - this.value = BIG_INTEGER_ZERO; - } - - public IntegerItem(String str) { - this.value = new BigInteger(str); - } - - @Override - public int getType() { - return INTEGER_ITEM; - } - - @Override - public boolean isNull() { - return BIG_INTEGER_ZERO.equals(value); - } - - @Override - public int compareTo(Item item) { - if (item == null) { - return BIG_INTEGER_ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 - // > 1 - } - - switch (item.getType()) { - case INTEGER_ITEM: - return value.compareTo(((IntegerItem) item).value); - - case STRING_ITEM: - return 1; // 1.1 > 1-sp - - case LIST_ITEM: - return 1; // 1.1 > 1-1 - - default: - throw new RuntimeException("invalid item: " + item.getClass()); - } - } - - @Override - public String toString() { - return value.toString(); - } - } - - /** - * Represents a string in the version item list, usually a qualifier. - */ - private static class StringItem implements Item { - private static final String[] QUALIFIERS = { "alpha", "beta", "milestone", "rc", "snapshot", "", "sp" }; - - private static final List<String> _QUALIFIERS = Arrays.asList(QUALIFIERS); - - private static final Properties ALIASES = new Properties(); - static { - ALIASES.put("ga", ""); - ALIASES.put("final", ""); - ALIASES.put("cr", "rc"); - } - - /** - * A comparable value for the empty-string qualifier. This one is used - * to determine if a given qualifier makes the version older than one - * without a qualifier, or more recent. - */ - private static final String RELEASE_VERSION_INDEX = String.valueOf(_QUALIFIERS.indexOf("")); - - private String value; - - public StringItem(String value, boolean followedByDigit) { - if (followedByDigit && value.length() == 1) { - // a1 = alpha-1, b1 = beta-1, m1 = milestone-1 - switch (value.charAt(0)) { - case 'a': - value = "alpha"; - break; - case 'b': - value = "beta"; - break; - case 'm': - value = "milestone"; - break; - } - } - this.value = ALIASES.getProperty(value, value); - } - - @Override - public int getType() { - return STRING_ITEM; - } - - @Override - public boolean isNull() { - return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0); - } - - /** - * Returns a comparable value for a qualifier. - * - * This method takes into account the ordering of known qualifiers then - * unknown qualifiers with lexical ordering. - * - * just returning an Integer with the index here is faster, but requires - * a lot of if/then/else to check for -1 or QUALIFIERS.size and then - * resort to lexical ordering. Most comparisons are decided by the first - * character, so this is still fast. If more characters are needed then - * it requires a lexical sort anyway. - * - * @param qualifier - * @return an equivalent value that can be used with lexical comparison - */ - public static String comparableQualifier(String qualifier) { - int i = _QUALIFIERS.indexOf(qualifier); - - return i == -1 ? (_QUALIFIERS.size() + "-" + qualifier) : String.valueOf(i); - } - - // @Override - public int compareTo(Item item) { - if (item == null) { - // 1-rc < 1, 1-ga > 1 - return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX); - } - switch (item.getType()) { - case INTEGER_ITEM: - return -1; // 1.any < 1.1 ? - - case STRING_ITEM: - return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value)); - - case LIST_ITEM: - return -1; // 1.any < 1-1 - - default: - throw new RuntimeException("invalid item: " + item.getClass()); - } - } - - @Override - public String toString() { - return value; - } - } - - /** - * Represents a version list item. This class is used both for the global - * item list and for sub-lists (which start with '-(number)' in the version - * specification). - */ - private static class ListItem extends ArrayList<Item> implements Item { - - private static final long serialVersionUID = -4740226741001149657L; - - @Override - public int getType() { - return LIST_ITEM; - } - - @Override - public boolean isNull() { - return (size() == 0); - } - - void normalize() { - for (ListIterator<Item> iterator = listIterator(size()); iterator.hasPrevious();) { - Item item = iterator.previous(); - if (item.isNull()) { - iterator.remove(); // remove null trailing items: 0, "", - // empty list - } else { - break; - } - } - } - - @Override - public int compareTo(Item item) { - if (item == null) { - if (size() == 0) { - return 0; // 1-0 = 1- (normalize) = 1 - } - Item first = get(0); - return first.compareTo(null); - } - switch (item.getType()) { - case INTEGER_ITEM: - return -1; // 1-1 < 1.0.x - - case STRING_ITEM: - return 1; // 1-1 > 1-sp - - case LIST_ITEM: - Iterator<Item> left = iterator(); - Iterator<Item> right = ((ListItem) item).iterator(); - - while (left.hasNext() || right.hasNext()) { - Item l = left.hasNext() ? left.next() : null; - Item r = right.hasNext() ? right.next() : null; - - int result = 0; - if (r != null && l != null) { - result = l.compareTo(r); - } else if (r == null && l == null) { - result = 0; - } else if (l == null) { - result = -1; - } else { - result = 1; - } - - // if this is shorter, then invert the compare and mul with - // -1 - // int result = (l == null ? (r == null ? 0 : -1 * - // r.compareTo(l)) : l.compareTo(r)); - - if (result != 0) { - return result; - } - } - - return 0; - - default: - throw new RuntimeException("invalid item: " + item.getClass()); - } - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder("("); - for (Iterator<Item> iter = iterator(); iter.hasNext();) { - buffer.append(iter.next()); - if (iter.hasNext()) { - buffer.append(','); - } - } - buffer.append(')'); - return buffer.toString(); - } - } - - public ComparableVersion(String version) { - parseVersion(version); - } - - public final void parseVersion(String version) { - this.value = version; - - items = new ListItem(); - - version = version.toLowerCase(Locale.ENGLISH); - - ListItem list = items; - - Stack<Item> stack = new Stack<Item>(); - stack.push(list); - - boolean isDigit = false; - - int startIndex = 0; - - for (int i = 0; i < version.length(); i++) { - char c = version.charAt(i); - - if (c == '.') { - if (i == startIndex) { - list.add(IntegerItem.ZERO); - } else { - list.add(parseItem(isDigit, version.substring(startIndex, i))); - } - startIndex = i + 1; - } else if (c == '-') { - if (i == startIndex) { - list.add(IntegerItem.ZERO); - } else { - list.add(parseItem(isDigit, version.substring(startIndex, i))); - } - startIndex = i + 1; - - if (isDigit) { - list.normalize(); // 1.0-* = 1-* - - if ((i + 1 < version.length()) && Character.isDigit(version.charAt(i + 1))) { - // new ListItem only if previous were digits and new - // char is a digit, - // ie need to differentiate only 1.1 from 1-1 - list.add(list = new ListItem()); - - stack.push(list); - } - } - } else if (Character.isDigit(c)) { - if (!isDigit && i > startIndex) { - list.add(new StringItem(version.substring(startIndex, i), true)); - startIndex = i; - } - - isDigit = true; - } else { - if (isDigit && i > startIndex) { - list.add(parseItem(true, version.substring(startIndex, i))); - startIndex = i; - } - - isDigit = false; - } - } - - if (version.length() > startIndex) { - list.add(parseItem(isDigit, version.substring(startIndex))); - } - - while (!stack.isEmpty()) { - list = (ListItem) stack.pop(); - list.normalize(); - } - - canonical = items.toString(); - } - - private static Item parseItem(boolean isDigit, String buf) { - return isDigit ? new IntegerItem(buf) : new StringItem(buf, false); - } - - @Override - public int compareTo(ComparableVersion o) { - return items.compareTo(o.items); - } - - @Override - public String toString() { - return value; - } - - @Override - public boolean equals(Object o) { - return (o instanceof ComparableVersion) && canonical.equals(((ComparableVersion) o).canonical); - } - - @Override - public int hashCode() { - return canonical.hashCode(); - } + private final BigInteger value; + public static final IntegerItem ZERO = new IntegerItem(); + + private IntegerItem() { + this.value = BIG_INTEGER_ZERO; + } + + public IntegerItem(String str) { + this.value = new BigInteger(str); + } + + @Override + public int getType() { + return INTEGER_ITEM; + } + + @Override + public boolean isNull() { + return BIG_INTEGER_ZERO.equals(value); + } + + @Override + public int compareTo(Item item) { + if (item == null) { + return BIG_INTEGER_ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 + // > 1 + } + + switch (item.getType()) { + case INTEGER_ITEM: + return value.compareTo(((IntegerItem) item).value); + + case STRING_ITEM: + return 1; // 1.1 > 1-sp + + case LIST_ITEM: + return 1; // 1.1 > 1-1 + + default: + throw new RuntimeException(INVALID_ITEM + item.getClass()); + } + } + + @Override + public String toString() { + return value.toString(); + } + } + + /** + * Represents a string in the version item list, usually a qualifier. + */ + private static class StringItem implements Item { + private static final String[] QUALIFIERS = { "alpha", "beta", "milestone", "rc", "snapshot", "", "sp" }; + + private static final List<String> _QUALIFIERS = Arrays.asList(QUALIFIERS); + + private static final Properties ALIASES = new Properties(); + static { + ALIASES.put("ga", ""); + ALIASES.put("final", ""); + ALIASES.put("cr", "rc"); + } + + /** + * A comparable value for the empty-string qualifier. This one is used + * to determine if a given qualifier makes the version older than one + * without a qualifier, or more recent. + */ + private static final String RELEASE_VERSION_INDEX = String.valueOf(_QUALIFIERS.indexOf("")); + + private String value; + + public StringItem(String value, boolean followedByDigit) { + if (followedByDigit && value.length() == 1) { + // a1 = alpha-1, b1 = beta-1, m1 = milestone-1 + switch (value.charAt(0)) { + case 'a': + value = "alpha"; + break; + case 'b': + value = "beta"; + break; + case 'm': + value = "milestone"; + break; + } + } + this.value = ALIASES.getProperty(value, value); + } + + @Override + public int getType() { + return STRING_ITEM; + } + + @Override + public boolean isNull() { + return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0); + } + + /** + * Returns a comparable value for a qualifier. + * + * This method takes into account the ordering of known qualifiers then + * unknown qualifiers with lexical ordering. + * + * just returning an Integer with the index here is faster, but requires + * a lot of if/then/else to check for -1 or QUALIFIERS.size and then + * resort to lexical ordering. Most comparisons are decided by the first + * character, so this is still fast. If more characters are needed then + * it requires a lexical sort anyway. + * + * @param qualifier + * @return an equivalent value that can be used with lexical comparison + */ + public static String comparableQualifier(String qualifier) { + int i = _QUALIFIERS.indexOf(qualifier); + + return i == -1 ? (_QUALIFIERS.size() + "-" + qualifier) : String.valueOf(i); + } + + // @Override + public int compareTo(Item item) { + if (item == null) { + // 1-rc < 1, 1-ga > 1 + return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX); + } + switch (item.getType()) { + case INTEGER_ITEM: + return -1; // 1.any < 1.1 ? + + case STRING_ITEM: + return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value)); + + case LIST_ITEM: + return -1; // 1.any < 1-1 + + default: + throw new RuntimeException("invalid item: " + item.getClass()); + } + } + + @Override + public String toString() { + return value; + } + } + + /** + * Represents a version list item. This class is used both for the global + * item list and for sub-lists (which start with '-(number)' in the version + * specification). + */ + private static class ListItem extends ArrayList<Item> implements Item { + + @Override + public int getType() { + return LIST_ITEM; + } + + @Override + public boolean isNull() { + return (size() == 0); + } + + void normalize() { + for (ListIterator<Item> iterator = listIterator(size()); iterator.hasPrevious();) { + Item item = iterator.previous(); + if (item.isNull()) { + iterator.remove(); // remove null trailing items: 0, "", + // empty list + } else { + break; + } + } + } + + @Override + public int compareTo(Item item) { + if (item == null) { + if (size() == 0) { + return 0; // 1-0 = 1- (normalize) = 1 + } + Item first = get(0); + return first.compareTo(null); + } + switch (item.getType()) { + case INTEGER_ITEM: + return -1; // 1-1 < 1.0.x + + case STRING_ITEM: + return 1; // 1-1 > 1-sp + + case LIST_ITEM: + Iterator<Item> left = iterator(); + Iterator<Item> right = ((ListItem) item).iterator(); + + while (left.hasNext() || right.hasNext()) { + Item l = left.hasNext() ? left.next() : null; + Item r = right.hasNext() ? right.next() : null; + + int result = 0; + if (r != null && l != null) { + result = l.compareTo(r); + } else if (r == null && l == null) { + result = 0; + } else if (l == null) { + result = -1; + } else { + result = 1; + } + + // if this is shorter, then invert the compare and mul with + // -1 + // int result = (l == null ? (r == null ? 0 : -1 * + // r.compareTo(l)) : l.compareTo(r)); + + if (result != 0) { + return result; + } + } + + return 0; + + default: + throw new RuntimeException("invalid item: " + item.getClass()); + } + } + + @Override + public String toString() { + StringBuilder buffer = new StringBuilder("("); + for (Iterator<Item> iter = iterator(); iter.hasNext();) { + buffer.append(iter.next()); + if (iter.hasNext()) { + buffer.append(','); + } + } + buffer.append(')'); + return buffer.toString(); + } + } + + public ComparableVersion(String version) { + parseVersion(version); + } + + public final void parseVersion(String version) { + this.value = version; + + items = new ListItem(); + + version = version.toLowerCase(Locale.ENGLISH); + + ListItem list = items; + + Stack<Item> stack = new Stack<>(); + stack.push(list); + + boolean isDigit = false; + + int startIndex = 0; + + for (int i = 0; i < version.length(); i++) { + char c = version.charAt(i); + + if (c == '.') { + if (i == startIndex) { + list.add(IntegerItem.ZERO); + } else { + list.add(parseItem(isDigit, version.substring(startIndex, i))); + } + startIndex = i + 1; + } else if (c == '-') { + if (i == startIndex) { + list.add(IntegerItem.ZERO); + } else { + list.add(parseItem(isDigit, version.substring(startIndex, i))); + } + startIndex = i + 1; + + if (isDigit) { + list.normalize(); // 1.0-* = 1-* + + if ((i + 1 < version.length()) && Character.isDigit(version.charAt(i + 1))) { + // new ListItem only if previous were digits and new + // char is a digit, + // ie need to differentiate only 1.1 from 1-1 + list.add(list = new ListItem()); + + stack.push(list); + } + } + } else if (Character.isDigit(c)) { + if (!isDigit && i > startIndex) { + list.add(new StringItem(version.substring(startIndex, i), true)); + startIndex = i; + } + + isDigit = true; + } else { + if (isDigit && i > startIndex) { + list.add(parseItem(true, version.substring(startIndex, i))); + startIndex = i; + } + + isDigit = false; + } + } + + if (version.length() > startIndex) { + list.add(parseItem(isDigit, version.substring(startIndex))); + } + + while (!stack.isEmpty()) { + list = (ListItem) stack.pop(); + list.normalize(); + } + + canonical = items.toString(); + } + + private static Item parseItem(boolean isDigit, String buf) { + return isDigit ? new IntegerItem(buf) : new StringItem(buf, false); + } + + @Override + public int compareTo(ComparableVersion o) { + return items.compareTo(o.items); + } + + @Override + public String toString() { + return value; + } + + @Override + public boolean equals(Object o) { + return (o instanceof ComparableVersion) && canonical.equals(((ComparableVersion) o).canonical); + } + + @Override + public int hashCode() { + return canonical.hashCode(); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java index 268ee28b96..0b71f03599 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java @@ -48,145 +48,145 @@ import java.util.regex.Pattern; * @author <a href="mailto:brett@apache.org">Brett Porter</a> */ public class Version implements Comparable<Version> { - private Integer majorVersion; - - private Integer minorVersion; - - private Integer incrementalVersion; - - private Integer buildNumber; - - private String qualifier; - - private ComparableVersion comparable; - - public Version(String version) { - parseVersion(version); - } - - @Override - public int hashCode() { - return 11 + comparable.hashCode(); - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - - if (!(other instanceof Version)) { - return false; - } - - return compareTo((Version) other) == 0; - } - - public int compareTo(Version otherVersion) { - return this.comparable.compareTo(otherVersion.comparable); - } - - public int getMajorVersion() { - return majorVersion != null ? majorVersion : 0; - } - - public int getMinorVersion() { - return minorVersion != null ? minorVersion : 0; - } - - public int getIncrementalVersion() { - return incrementalVersion != null ? incrementalVersion : 0; - } - - public int getBuildNumber() { - return buildNumber != null ? buildNumber : 0; - } - - public String getQualifier() { - return qualifier; - } - - public final void parseVersion(String version) { - comparable = new ComparableVersion(version); - - int index = version.indexOf("-"); - - String part1; - String part2 = null; - - if (index < 0) { - part1 = version; - } else { - part1 = version.substring(0, index); - part2 = version.substring(index + 1); - } - - if (part2 != null) { - try { - if ((part2.length() == 1) || !part2.startsWith("0")) { - buildNumber = Integer.valueOf(part2); - } else { - qualifier = part2; - } - } catch (NumberFormatException e) { - qualifier = part2; - } - } - - if ((!part1.contains(".")) && !part1.startsWith("0")) { - try { - majorVersion = Integer.valueOf(part1); - } catch (NumberFormatException e) { - // qualifier is the whole version, including "-" - qualifier = version; - buildNumber = null; - } - } else { - boolean fallback = false; - - StringTokenizer tok = new StringTokenizer(part1, "."); - try { - majorVersion = getNextIntegerToken(tok); - if (tok.hasMoreTokens()) { - minorVersion = getNextIntegerToken(tok); - } - if (tok.hasMoreTokens()) { - incrementalVersion = getNextIntegerToken(tok); - } - if (tok.hasMoreTokens()) { - qualifier = tok.nextToken(); - fallback = Pattern.compile("\\d+").matcher(qualifier).matches(); - } - - // string tokenzier won't detect these and ignores them - if (part1.contains("..") || part1.startsWith(".") || part1.endsWith(".")) { - fallback = true; - } - } catch (NumberFormatException e) { - fallback = true; - } - - if (fallback) { - // qualifier is the whole version, including "-" - qualifier = version; - majorVersion = null; - minorVersion = null; - incrementalVersion = null; - buildNumber = null; - } - } - } - - private static Integer getNextIntegerToken(StringTokenizer tok) { - String s = tok.nextToken(); - if ((s.length() > 1) && s.startsWith("0")) { - throw new NumberFormatException("Number part has a leading 0: '" + s + "'"); - } - return Integer.valueOf(s); - } - - @Override - public String toString() { - return comparable.toString(); - } + private Integer majorVersion; + + private Integer minorVersion; + + private Integer incrementalVersion; + + private Integer buildNumber; + + private String qualifier; + + private ComparableVersion comparable; + + public Version(String version) { + parseVersion(version); + } + + @Override + public int hashCode() { + return 11 + comparable.hashCode(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + + if (!(other instanceof Version)) { + return false; + } + + return compareTo((Version) other) == 0; + } + + public int compareTo(Version otherVersion) { + return this.comparable.compareTo(otherVersion.comparable); + } + + public int getMajorVersion() { + return majorVersion != null ? majorVersion : 0; + } + + public int getMinorVersion() { + return minorVersion != null ? minorVersion : 0; + } + + public int getIncrementalVersion() { + return incrementalVersion != null ? incrementalVersion : 0; + } + + public int getBuildNumber() { + return buildNumber != null ? buildNumber : 0; + } + + public String getQualifier() { + return qualifier; + } + + public final void parseVersion(String version) { + comparable = new ComparableVersion(version); + + int index = version.indexOf("-"); + + String part1; + String part2 = null; + + if (index < 0) { + part1 = version; + } else { + part1 = version.substring(0, index); + part2 = version.substring(index + 1); + } + + if (part2 != null) { + try { + if ((part2.length() == 1) || !part2.startsWith("0")) { + buildNumber = Integer.valueOf(part2); + } else { + qualifier = part2; + } + } catch (NumberFormatException e) { + qualifier = part2; + } + } + + if ((!part1.contains(".")) && !part1.startsWith("0")) { + try { + majorVersion = Integer.valueOf(part1); + } catch (NumberFormatException e) { + // qualifier is the whole version, including "-" + qualifier = version; + buildNumber = null; + } + } else { + boolean fallback = false; + + StringTokenizer tok = new StringTokenizer(part1, "."); + try { + majorVersion = getNextIntegerToken(tok); + if (tok.hasMoreTokens()) { + minorVersion = getNextIntegerToken(tok); + } + if (tok.hasMoreTokens()) { + incrementalVersion = getNextIntegerToken(tok); + } + if (tok.hasMoreTokens()) { + qualifier = tok.nextToken(); + fallback = Pattern.compile("\\d+").matcher(qualifier).matches(); + } + + // string tokenzier won't detect these and ignores them + if (part1.contains("..") || part1.startsWith(".") || part1.endsWith(".")) { + fallback = true; + } + } catch (NumberFormatException e) { + fallback = true; + } + + if (fallback) { + // qualifier is the whole version, including "-" + qualifier = version; + majorVersion = null; + minorVersion = null; + incrementalVersion = null; + buildNumber = null; + } + } + } + + private static Integer getNextIntegerToken(StringTokenizer tok) { + String s = tok.nextToken(); + if ((s.length() > 1) && s.startsWith("0")) { + throw new NumberFormatException("Number part has a leading 0: '" + s + "'"); + } + return Integer.valueOf(s); + } + + @Override + public String toString() { + return comparable.toString(); + } } |