diff options
Diffstat (limited to 'catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca')
69 files changed, 6105 insertions, 0 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 new file mode 100644 index 0000000000..2bbb84dd20 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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; + +/** + * The primitive type that TOSCA YAML supports. + * + * @author esofer + */ +public enum ToscaPropertyType { + + Root("tosca.datatypes.Root", null, null, null, true), + + STRING("string", StringValidator.getInstance(), StringConvertor.getInstance(), ToscaStringConvertor.getInstance()), + + BOOLEAN("boolean", BooleanValidator.getInstance(), ToscaBooleanConverter.getInstance(), + BooleanConverter.getInstance()), + + FLOAT("float", FloatValidator.getInstance(), ToscaFloatConverter.getInstance(), FloatConverter.getInstance()), + + INTEGER("integer", IntegerValidator.getInstance(), DefaultConverter.getInstance(), IntegerConverter.getInstance()), + + SCALAR_UNIT_SIZE("scalar-unit.size", StringValidator.getInstance(), DefaultConverter.getInstance(), + ToscaValueDefaultConverter.getInstance()), + + SCALAR_UNIT_TIME("scalar-unit.time", StringValidator.getInstance(), DefaultConverter.getInstance(), + ToscaValueDefaultConverter.getInstance()), + + SCALAR_UNIT_FREQUENCY("scalar-unit.frequency", StringValidator.getInstance(), DefaultConverter.getInstance(), + ToscaValueDefaultConverter.getInstance()), + + RANGE("range", StringValidator.getInstance(), DefaultConverter.getInstance(), + ToscaValueDefaultConverter.getInstance()), + + TIMESTAMP("timestamp", StringValidator.getInstance(), DefaultConverter.getInstance(), + ToscaValueDefaultConverter.getInstance()), + + MAP("map", MapValidator.getInstance(), MapConverter.getInstance(), ToscaMapValueConverter.getInstance()), + + LIST("list", ListValidator.getInstance(), ListConverter.getInstance(), ToscaListValueConverter.getInstance()), + + VERSION("version", StringValidator.getInstance(), DefaultConverter.getInstance(), + ToscaValueDefaultConverter.getInstance()), + + KEY("key", KeyValidator.getInstance(), StringConvertor.getInstance(), ToscaValueDefaultConverter.getInstance()), + + JSON("json", JsonValidator.getInstance(), JsonConverter.getInstance(), ToscaJsonValueConverter.getInstance()); + + // CREDENTIAL("tosca.datatypes.Credential", StringValidator.getInstance(), + // DefaultConverter.getInstance()); + + 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, 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 void setType(String type) { + this.type = type; + } + + public PropertyTypeValidator getValidator() { + return validator; + } + + public void setValidator(PropertyTypeValidator validator) { + this.validator = validator; + } + + public PropertyValueConverter getConverter() { + return converter; + } + + public void setConverter(PropertyValueConverter converter) { + this.converter = converter; + } + + public boolean isAbstract() { + return isAbstract; + } + + public void setAbstract(boolean isAbstract) { + this.isAbstract = isAbstract; + } + + public ToscaValueConverter getValueConverter() { + return valueConverter; + } + + public void setValueConverter(ToscaValueConverter valueConverter) { + this.valueConverter = valueConverter; + } + + 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; + } + + public static boolean isScalarType(String dataTypeName) { + + ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); + + return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == 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(); + } +} 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 new file mode 100644 index 0000000000..88642f8240 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca; + +import java.text.DateFormat; +import java.text.ParseException; +import java.util.Locale; + +/** + * The primitive type that TOSCA YAML supports. + * + * @author mkv + */ +public enum ToscaType { + 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 static ToscaType fromYamlTypeName(String typeName) { + if (typeName == null) { + return null; + } + try { + return ToscaType.valueOf(typeName.toUpperCase()); + } catch (IllegalArgumentException e) { + return null; + } + } + + 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 isFloat(String value) { + try { + Float.valueOf(value); + } catch (NumberFormatException e) { + return false; + } + return true; + } + + 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(); + } +} 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 new file mode 100644 index 0000000000..91d806edd9 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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; + +public final class 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"; + + /** + * 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(); + } + + /** + * 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)); + } +} 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 new file mode 100644 index 0000000000..7b46692253 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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; + + private Comparable 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 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); + } +} 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 new file mode 100644 index 0000000000..950a7fa9b9 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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; + + @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 new file mode 100644 index 0000000000..142caa2017 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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); + } +} 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 new file mode 100644 index 0000000000..5f19d15293 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints; + +import java.util.Arrays; +import java.util.List; + +public enum ConstraintType { + + IN_RANGE("inRange"), + + GREATER_THAN("greaterThan", "greater_than"), + + GREATER_OR_EQUAL("greaterOrEqual", "greater_or_equal"), + + LESS_OR_EQUAL("lessOrEqual", "less_or_equal"), + + MIN_LENGTH("minLength", "min_length"), + + VALID_VALUES("validValues", "valid_values"), + + LESS_THAN("lessThan", "less_than"); + + List<String> types; + + private ConstraintType(String... types) { + this.types = Arrays.asList(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; + } +} 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 new file mode 100644 index 0000000000..79ac5caf25 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java @@ -0,0 +1,145 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints; + +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() { + } + + /** + * 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() + ">"); + } + } + + /** + * 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) { + + this.name = name; + this.reference = reference; + this.value = value; + this.type = 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()); + } + } +} 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 new file mode 100644 index 0000000000..530dcb0cc6 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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; + +public class EqualConstraint extends AbstractPropertyConstraint implements Serializable { + /** + * + */ + private static final long serialVersionUID = -1596093341744641483L; + + @NotNull + private String equal; + + // @JsonIgnore + private Object typed; + + 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 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 + ">"); + } +} 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 new file mode 100644 index 0000000000..4f2c3ad9ca --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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); + } + } +} 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 new file mode 100644 index 0000000000..aea2a201ab --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 { + + /** + * + */ + private static final long serialVersionUID = 405723215512121896L; + + public GreaterThanConstraint(String greaterThan) { + super(); + this.greaterThan = greaterThan; + } + + @NotNull + private String greaterThan; + + @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); + } + } + + public String getGreaterThan() { + return 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 new file mode 100644 index 0000000000..e8821c2c21 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints; + +import java.io.Serializable; +import java.util.List; + +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.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; + } + } + + // @JsonProperty + 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 new file mode 100644 index 0000000000..2ba0071f2f --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 { + + /** + * + */ + private static final long serialVersionUID = 6249912030281791233L; + + @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 + "]"); + } + } + + public Integer getLength() { + return 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 new file mode 100644 index 0000000000..1491fe327d --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 { + + /** + * + */ + private static final long serialVersionUID = -4907864317687138678L; + + // @JsonDeserialize(using = TextDeserializer.class) + @NotNull + private String lessOrEqual; + + public LessOrEqualConstraint(String lessOrEqual) { + super(); + this.lessOrEqual = lessOrEqual; + } + + @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); + } + } + + public String getLessOrEqual() { + return 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 new file mode 100644 index 0000000000..2fc43febbf --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 { + + /** + * + */ + private static final long serialVersionUID = 2267623014703859501L; + + @NotNull + private String lessThan; + + public LessThanConstraint(String lessThan) { + super(); + this.lessThan = lessThan; + } + + @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); + } + } + +} 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 new file mode 100644 index 0000000000..b6a80afced --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 { + + /** + * + */ + private static final long serialVersionUID = 6377603705670201256L; + + @NotNull + private Integer maxLength; + + public MaxLengthConstraint(Integer maxLength) { + this.maxLength = maxLength; + } + + 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 + "]"); + } + } + + public Integer getMaxLength() { + return 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 new file mode 100644 index 0000000000..f92e5fbb2c --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 { + + /** + * + */ + private static final long serialVersionUID = 32422424680811240L; + + @NotNull + private Integer minLength; + + public MinLengthConstraint(Integer minLength) { + this.minLength = minLength; + } + + 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 + "]"); + } + } + + public Integer getMinLength() { + return 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 new file mode 100644 index 0000000000..c85c1601e4 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 { + + /** + * + */ + private static final long serialVersionUID = 8708185294968697107L; + + @NotNull + private String pattern; + + // @JsonIgnore + private Pattern compiledPattern; + + 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); + } + } +} 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 new file mode 100644 index 0000000000..738f5150e3 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints; + +import java.io.Serializable; +import java.util.List; +import java.util.Set; + +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 com.google.common.collect.Sets; + +public class ValidValuesConstraint extends AbstractPropertyConstraint implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 5906087180079892853L; + + @NotNull + private List<String> validValues; + // @JsonIgnore + private Set<Object> validValuesTyped; + + public ValidValuesConstraint(List<String> validValues) { + super(); + this.validValues = validValues; + } + + public ValidValuesConstraint() { + super(); + } + + @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"); + } + } + + public List<String> getValidValues() { + return 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 new file mode 100644 index 0000000000..3fd165f41e --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints.exception; + +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil; +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInformation; + +/** + * All functional error related to constraint processing must go here + * + * @author mkv + * + */ +public class ConstraintFunctionalException extends FunctionalException { + + private static final long serialVersionUID = 1L; + + protected ConstraintInformation constraintInformation; + + public ConstraintFunctionalException(String message, Throwable cause) { + super(message, cause); + } + + public ConstraintFunctionalException(String message) { + super(message); + } + + 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 new file mode 100644 index 0000000000..2416405de4 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints.exception; + +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil; +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInformation; + +/** + * Exception to be thrown when a required property is not provided + * + * @author mourouvi + * + */ +public class ConstraintRequiredParameterException extends ConstraintFunctionalException { + + private static final long serialVersionUID = 1L; + + public ConstraintRequiredParameterException(String message) { + super(message); + } + + public ConstraintRequiredParameterException(String message, Throwable cause) { + super(message, cause); + } + + public ConstraintRequiredParameterException(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/ConstraintTechnicalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java new file mode 100644 index 0000000000..3816ac61dd --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints.exception; + +/** + * Base class for all constraint related exceptions + * + * @author esofer + * + */ +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); + } + +} 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 new file mode 100644 index 0000000000..6ba0d9b864 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints.exception; + +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil; +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInformation; + +/** + * Exception to be thrown when a constraint definition is invalid because the + * specified value doesn't match the property type. + * + * @author esofer + */ +public class ConstraintValueDoNotMatchPropertyTypeException extends ConstraintFunctionalException { + + private static final long serialVersionUID = 4342613849660957651L; + + public ConstraintValueDoNotMatchPropertyTypeException(String message) { + super(message); + } + + public ConstraintValueDoNotMatchPropertyTypeException(String message, Throwable cause) { + super(message, cause); + } + + public ConstraintValueDoNotMatchPropertyTypeException(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/ConstraintViolationException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java new file mode 100644 index 0000000000..7fce63841d --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints.exception; + +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil; +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInformation; + +/** + * Exception happened while user violated a predefined constraint + * + * @author mkv + * + */ +public class ConstraintViolationException extends ConstraintFunctionalException { + + private static final long serialVersionUID = 1L; + + public ConstraintViolationException(String message) { + super(message); + } + + public ConstraintViolationException(String message, Throwable cause) { + super(message, cause); + } + + public ConstraintViolationException(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/FunctionalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java new file mode 100644 index 0000000000..1454306e89 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints.exception; + +/** + * All functional exception which is related to user input must go here. It's a + * checked exception to force error handling and checking. + * + * @author mkv + * + */ +public class FunctionalException extends Exception { + + private static final long serialVersionUID = 6712845685798792493L; + + public FunctionalException(String message, Throwable cause) { + super(message, cause); + } + + 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 new file mode 100644 index 0000000000..2b231d98e3 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints.exception; + +/** + * Exception thrown when the user defines invalid custom property constraint + * + * @author mkv + * + */ +public class InvalidPropertyConstraintImplementationException extends ConstraintTechnicalException { + + private static final long serialVersionUID = 2797550944328544706L; + + public InvalidPropertyConstraintImplementationException(String message, Throwable cause) { + super(message, cause); + } + + 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 new file mode 100644 index 0000000000..1bddeea69b --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.constraints.exception; + +/** + * Base class for all Alien technical exception + * + * @author mkv + * + */ +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) { + 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 new file mode 100644 index 0000000000..f721efb3c9 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class BooleanConverter implements ToscaValueConverter { + private static BooleanConverter booleanConverter = new BooleanConverter(); + + public static BooleanConverter getInstance() { + return booleanConverter; + } + + private BooleanConverter() { + + } + + @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/DefaultConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java new file mode 100644 index 0000000000..c190298b52 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class DefaultConverter implements PropertyValueConverter { + + private static DefaultConverter defaultConverter = new DefaultConverter(); + + public static DefaultConverter getInstance() { + return defaultConverter; + } + + private DefaultConverter() { + + } + + @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 new file mode 100644 index 0000000000..d3edd9b8bf --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class FloatConverter implements ToscaValueConverter { + private static FloatConverter floatConverter = new FloatConverter(); + + public static FloatConverter getInstance() { + return floatConverter; + } + + private FloatConverter() { + + } + + @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 new file mode 100644 index 0000000000..147b2e9c52 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class HeatBooleanConverter implements PropertyValueConverter { + + private static HeatBooleanConverter booleanConverter = new HeatBooleanConverter(); + + public static HeatBooleanConverter getInstance() { + return booleanConverter; + } + + private HeatBooleanConverter() { + + } + + @Override + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + + if (value == null) { + 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"; + } + } + +} 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 new file mode 100644 index 0000000000..a0834791ff --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.util.ValidationUtils; + +public class HeatCommaDelimitedListConverter implements PropertyValueConverter { + + private static HeatCommaDelimitedListConverter stringConverter = new HeatCommaDelimitedListConverter(); + + public static HeatCommaDelimitedListConverter getInstance() { + return stringConverter; + } + + private HeatCommaDelimitedListConverter() { + + } + + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + String 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 new file mode 100644 index 0000000000..6e077d60a1 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.util.ValidationUtils; + +public class HeatJsonConverter implements PropertyValueConverter { + + private static HeatJsonConverter jsonConverter = new HeatJsonConverter(); + + public static HeatJsonConverter getInstance() { + return jsonConverter; + } + + private HeatJsonConverter() { + + } + + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + String coverted = ValidationUtils.removeNoneUtf8Chars(original); + coverted = ValidationUtils.removeHtmlTagsOnly(coverted); + coverted = ValidationUtils.normaliseWhitespace(coverted); + coverted = ValidationUtils.stripOctets(coverted); + // As opposed to string converter, keeping the " and ' symbols + return coverted; + } + +} 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 new file mode 100644 index 0000000000..90781be367 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +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(); + + public static HeatNumberConverter getInstance() { + return numberConverter; + } + + private HeatNumberConverter() { + + } + + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + + if (original == null) { + return null; + } + + 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 new file mode 100644 index 0000000000..475db1db7c --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.util.ValidationUtils; + +public class HeatStringConverter implements PropertyValueConverter { + + private static HeatStringConverter stringConverter = new HeatStringConverter(); + + public static HeatStringConverter getInstance() { + return stringConverter; + } + + private HeatStringConverter() { + + } + + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + String coverted = ValidationUtils.removeNoneUtf8Chars(original); + coverted = ValidationUtils.normaliseWhitespace(coverted); + coverted = ValidationUtils.stripOctets(coverted); + coverted = ValidationUtils.removeHtmlTagsOnly(coverted); + coverted = coverted.replaceAll("\"", "").replaceAll("\'", ""); + + 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 new file mode 100644 index 0000000000..076e5aceef --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class IntegerConverter implements ToscaValueConverter { + + private static IntegerConverter integerConverter = new IntegerConverter(); + + public static IntegerConverter getInstance() { + return integerConverter; + } + + private IntegerConverter() { + + } + + @Override + public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + 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 new file mode 100644 index 0000000000..3879430e06 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.stream.JsonReader; + +public class JsonConverter implements PropertyValueConverter { + + private static JsonConverter jsonConverter = new JsonConverter(); + + private static JsonParser jsonParser = new JsonParser(); + + private static Gson gson = GsonFactory.getGson(); + + public static JsonConverter getInstance() { + return 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); + } +} 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 new file mode 100644 index 0000000000..8265cc2690 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java @@ -0,0 +1,217 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +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.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; + +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); + 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); + } + +} 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 new file mode 100644 index 0000000000..f33be29327 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class LowerCaseConverter implements PropertyValueConverter { + + private static LowerCaseConverter booleanConverter = new LowerCaseConverter(); + + public static LowerCaseConverter getInstance() { + return booleanConverter; + } + + private LowerCaseConverter() { + + } + + @Override + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + + 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 new file mode 100644 index 0000000000..921c6d0d41 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java @@ -0,0 +1,249 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +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.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; + +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); + } + +} 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 new file mode 100644 index 0000000000..254785fe8a --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public interface PropertyValueConverter { + + 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 new file mode 100644 index 0000000000..f5a7ff632e --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.util.ValidationUtils; + +public class StringConvertor implements PropertyValueConverter { + + private static StringConvertor stringConverter = new StringConvertor(); + + public static StringConvertor getInstance() { + return stringConverter; + } + + private StringConvertor() { + + } + + @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); + + 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 new file mode 100644 index 0000000000..977415b909 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class ToscaBooleanConverter implements PropertyValueConverter { + + private static ToscaBooleanConverter booleanConverter = new ToscaBooleanConverter(); + + public static ToscaBooleanConverter getInstance() { + return booleanConverter; + } + + private ToscaBooleanConverter() { + + } + + @Override + public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + + if (value == null) { + return null; + } + + 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/ToscaFloatConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java new file mode 100644 index 0000000000..5d7f98e438 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.math.BigDecimal; +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class ToscaFloatConverter implements PropertyValueConverter { + + private static ToscaFloatConverter numberConverter = new ToscaFloatConverter(); + + public static ToscaFloatConverter getInstance() { + return numberConverter; + } + + private ToscaFloatConverter() { + + } + + @Override + public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if (original == null) { + return null; + } + if (original.contains("f") || original.contains("F")) + original = original.toLowerCase().replaceFirst("f", ""); + return new BigDecimal(original).toPlainString(); + } + +} 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 new file mode 100644 index 0000000000..d70088e044 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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; + +public class ToscaJsonValueConverter extends ToscaValueBaseConverter implements ToscaValueConverter { + private static ToscaJsonValueConverter toscaJsonConverter = new ToscaJsonValueConverter(); + + public static ToscaJsonValueConverter getInstance() { + return toscaJsonConverter; + } + + private ToscaJsonValueConverter() { + + } + + 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); + } +} 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 new file mode 100644 index 0000000000..043446e783 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +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) { + log.debug("try to convert scalar value {}", e.getAsString()); + if (e.getAsString() == null) { + convertedValue = null; + } else { + JsonElement singleElement = jsonParser.parse(e.getAsString()); + if (singleElement.isJsonPrimitive()) { + convertedValue = innerConverterFinal.convertToToscaValue(e.getAsString(), innerType, + dataTypes); + } else { + convertedValue = handleComplexJsonValue(singleElement); + } + } + } 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<>(); + // log.debug("try to convert datatype value {}", + // e.getAsString()); + + 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 new file mode 100644 index 0000000000..601d8f0fc8 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.io.StringReader; +import java.util.HashMap; +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.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 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; + 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; + } + } else { + // TODO handle getinput + 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 -> { + log.debug("try convert element {}", e.getValue()); + Object convertedValue = convertDataTypeToToscaMap(innerType, dataTypes, innerConverterFinal, isScalarF, + e.getValue()); + toscaMap.put(e.getKey(), convertedValue); + }); + return toscaMap; + } catch (JsonParseException e) { + log.debug("Failed to parse json : {}. {}", value, e); + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); + return null; + } + } + + public Object convertDataTypeToToscaMap(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 { + JsonObject asJsonObjectIn = entryValue.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet(); + + DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); + Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); + Map<String, Object> toscaObjectPresentation = new HashMap<>(); + + for (Entry<String, JsonElement> entry : entrySetIn) { + String propName = entry.getKey(); + + JsonElement elementValue = entry.getValue(); + Object convValue; + if (isScalarF == false) { + PropertyDefinition propertyDefinition = allProperties.get(propName); + if (propertyDefinition == null && isScalarF) { + log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName()); + continue; + } + + 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.getAsString(), type, dataTypes); + } + } else { + if (elementValue.isJsonPrimitive()) { + convValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive()); + } else { + convValue = handleComplexJsonValue(elementValue); + } + } + 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 new file mode 100644 index 0000000000..e228d256c2 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class ToscaStringConvertor implements ToscaValueConverter { + private static ToscaStringConvertor stringConverter = new ToscaStringConvertor(); + + public static ToscaStringConvertor getInstance() { + return stringConverter; + } + + private ToscaStringConvertor() { + + } + + @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 new file mode 100644 index 0000000000..e886327481 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 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.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; + +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{ + 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(); + } + } +} 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 new file mode 100644 index 0000000000..1b5d4697be --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public interface ToscaValueConverter { + 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 new file mode 100644 index 0000000000..b6eb24276e --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.converters; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class ToscaValueDefaultConverter implements ToscaValueConverter { + private static ToscaValueDefaultConverter deafultConverter = new ToscaValueDefaultConverter(); + + public static ToscaValueDefaultConverter getInstance() { + return deafultConverter; + } + + private ToscaValueDefaultConverter() { + + } + + @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 new file mode 100644 index 0000000000..def0e7c391 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +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" }; + + public static BooleanValidator getInstance() { + return booleanValidator; + } + + private BooleanValidator() { + + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + if (value == null || true == value.isEmpty()) { + return true; + } + + 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); + } +} 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 new file mode 100644 index 0000000000..d376a1ec13 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java @@ -0,0 +1,499 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 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.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +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 com.google.gson.Gson; +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; + +public class DataTypeValidatorConverter { + + private static DataTypeValidatorConverter dataTypeValidatorConverter = new DataTypeValidatorConverter(); + + public static DataTypeValidatorConverter getInstance() { + return dataTypeValidatorConverter; + } + + private DataTypeValidatorConverter() { + + } + + private static Logger log = LoggerFactory.getLogger(DataTypeValidatorConverter.class.getName()); + + JsonParser jsonParser = new JsonParser(); + + Gson gson = new Gson(); + + ImmutablePair<JsonElement, Boolean> falseResult = new ImmutablePair<JsonElement, Boolean>(null, false); + ImmutablePair<JsonElement, Boolean> trueEmptyResult = new ImmutablePair<JsonElement, Boolean>(null, true); + + ImmutablePair<String, Boolean> trueStringEmptyResult = new ImmutablePair<String, Boolean>(null, true); + ImmutablePair<String, Boolean> falseStringEmptyResult = new ImmutablePair<String, Boolean>(null, true); + + private ToscaPropertyType isDataTypeDerviedFromScalarType(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; + } + + 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 (false == 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 (true == 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 (false == 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 (true == 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; + } + + ImmutablePair<JsonElement, Boolean> isValid = validateAndUpdate(elementValue, + typeDefinition, allDataTypes); + + if (false == 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; + } + + private String getValueFromJsonElement(JsonElement jsonElement) { + String value = null; + + if (jsonElement == null || jsonElement.isJsonNull()) { + value = PropertyOperation.EMPTY_VALUE; + } else { + if (jsonElement.toString().isEmpty()) { + value = ""; + } else { + value = jsonElement.toString(); + } + } + + return value; + } + + 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 " + dataTypeDefinition.getName() + " from type " + + 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; + + } 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 tpye {}", 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 decleration.", 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 {} canot 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; + } + + } + } + + } + + // public ImmutablePair<String, Boolean> + // validateAndUpdateAndReturnString(String value, DataTypeDefinition + // dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { + // + // ImmutablePair<JsonElement, Boolean> result = falseResult; + // + // if (value == null || value.isEmpty()) { + // return trueStringEmptyResult; + // } + // + // JsonElement jsonElement = null; + // try { + // jsonElement = jsonParser.parse(value); + // } catch (JsonSyntaxException e) { + // return falseStringEmptyResult; + // } + // + // result = validateAndUpdate(jsonElement, dataTypeDefinition, + // allDataTypes); + // + // if (result.right.booleanValue() == false) { + // log.debug("The value {} of property from type {} is invalid", value, dataTypeDefinition.getName()); + // return new ImmutablePair<String, Boolean>(value, false); + // } + // + // String valueFromJsonElement = getValueFromJsonElement(result.left); + // + // return new ImmutablePair<String, Boolean>(valueFromJsonElement, true); + // } + +} 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 new file mode 100644 index 0000000000..2518eaa51e --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class FloatValidator implements PropertyTypeValidator { + + private static FloatValidator FloatValidator = new FloatValidator(); + + public static FloatValidator getInstance() { + return FloatValidator; + } + + private FloatValidator() { + + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + if (value == null || true == value.isEmpty()) { + return true; + } + + try { + Float.parseFloat(value); + } catch (IllegalArgumentException 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/HeatBooleanValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java new file mode 100644 index 0000000000..ec4051e65c --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class HeatBooleanValidator implements PropertyTypeValidator { + + private static HeatBooleanValidator booleanValidator = new HeatBooleanValidator(); + + public static HeatBooleanValidator getInstance() { + return booleanValidator; + } + + private HeatBooleanValidator() { + + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + if (value == null || true == 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; + } + + return false; + } + + @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 new file mode 100644 index 0000000000..464dbf0975 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.util.ValidationUtils; + +public class HeatCommaDelimitedListValidator implements PropertyTypeValidator { + + private static HeatCommaDelimitedListValidator stringValidator = new HeatCommaDelimitedListValidator(); + + public static HeatCommaDelimitedListValidator getInstance() { + return stringValidator; + } + + private HeatCommaDelimitedListValidator() { + + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + if (value == null || true == value.isEmpty()) { + return true; + } + + String coverted = ValidationUtils.removeNoneUtf8Chars(value); + return ValidationUtils.validateIsEnglish(coverted); + } + + @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 new file mode 100644 index 0000000000..37c4a46829 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public class HeatNumberValidator implements PropertyTypeValidator { + + private static HeatNumberValidator numberValidator = new HeatNumberValidator(); + + private static FloatValidator floatValidator = FloatValidator.getInstance(); + private static IntegerValidator integerValidator = IntegerValidator.getInstance(); + + public static HeatNumberValidator getInstance() { + return numberValidator; + } + + private HeatNumberValidator() { + + } + + @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 (!valid) { + valid = floatValidator.isValid(value, null, allDataTypes); + } + + return valid; + } + + @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 new file mode 100644 index 0000000000..0e7b7f6648 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.util.ValidationUtils; + +public class HeatStringValidator implements PropertyTypeValidator { + + private static HeatStringValidator stringValidator = new HeatStringValidator(); + + public static HeatStringValidator getInstance() { + return stringValidator; + } + + private HeatStringValidator() { + + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + if (value == null || true == value.isEmpty()) { + return true; + } + + String coverted = ValidationUtils.removeNoneUtf8Chars(value); + return ValidationUtils.validateIsEnglish(coverted); + } + + @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 new file mode 100644 index 0000000000..61d321c45e --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +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 IntegerValidator() { + } + + public static IntegerValidator getInstance() { + return integerValidator; + } + + private class PatternBase { + public PatternBase(Pattern pattern, Integer base) { + this.pattern = pattern; + this.base = 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[] patterns = { base10Pattern, base8Pattern, base16Pattern }; + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + if (value == null || true == 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; + } + + @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 new file mode 100644 index 0000000000..164fe62792 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.io.StringReader; +import java.util.Map; + +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.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.JsonParser; +import com.google.gson.JsonSyntaxException; +import com.google.gson.stream.JsonReader; + +public class JsonValidator implements PropertyTypeValidator { + + private static JsonValidator jsonValidator = new JsonValidator(); + + private static Logger log = LoggerFactory.getLogger(JsonValidator.class.getName()); + + private static JsonParser jsonParser = new JsonParser(); + + public static JsonValidator getInstance() { + return jsonValidator; + } + + @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; + + } + + @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 new file mode 100644 index 0000000000..4b11e26d05 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.util.ValidationUtils; + +public class KeyValidator implements PropertyTypeValidator { + + public static final int STRING_MAXIMUM_LENGTH = 100; + + private static KeyValidator keyValidator = new KeyValidator(); + + public static KeyValidator getInstance() { + return keyValidator; + } + + private KeyValidator() { + + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + + if (value == null || true == value.isEmpty()) { + return false; + } + + if (value.length() > STRING_MAXIMUM_LENGTH) { + return false; + } + String coverted = ValidationUtils.removeNoneUtf8Chars(value); + return ValidationUtils.validateIsEnglish(coverted); + } + + @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 new file mode 100644 index 0000000000..92834690b8 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java @@ -0,0 +1,160 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.util.Map; + +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.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.JsonParser; +import com.google.gson.JsonSyntaxException; + +public class ListValidator implements PropertyTypeValidator { + + private static ListValidator listValidator = new ListValidator(); + + private static Logger log = LoggerFactory.getLogger(ListValidator.class.getName()); + Gson gson = new Gson(); + + 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); + 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; + } +} 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 new file mode 100644 index 0000000000..c8ffc3f4b8 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +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.tosca.ToscaPropertyType; +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.JsonParser; +import com.google.gson.JsonSyntaxException; + +/* + * Property Type Map correct usage: + * null key null value = Yaml reader error +valid key null value = key & value deleted +duplicated keys = last key is taken +mismatch between inner type and values type = returned mismatch in data type +validators and converters works the same as before + +Types: +when written line by line : + 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 Logger log = LoggerFactory.getLogger(MapValidator.class.getName()); + Gson gson = new Gson(); + + 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 (value == null || 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; + } + + } 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); + JsonObject asJsonObject = jsonObject.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); + for (Entry<String, JsonElement> entry : entrySet) { + String currentKey = entry.getKey(); + JsonElement jsonValue = entry.getValue(); + + String element = JsonUtils.toString(jsonValue); + + if (!innerValidator.isValid(element, null, allDataTypes) + || !keyValidator.isValid(entry.getKey(), null, allDataTypes)) { + log.debug("validation of key : {}, element: {} failed", currentKey, entry.getValue()); + return false; + } + } + + return true; + } catch (JsonSyntaxException e) { + log.debug("Failed to parse json : {}. {}", value, e); + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Validator"); + } + + return false; + + } + + 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 == false) { + 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 new file mode 100644 index 0000000000..35862148f9 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.util.Map; + +import org.openecomp.sdc.be.model.DataTypeDefinition; + +public interface PropertyTypeValidator { + + 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. + * + */ + +} 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 new file mode 100644 index 0000000000..06994505a9 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +import java.util.Map; + +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.Configuration.ToscaValidatorsConfig; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StringValidator implements PropertyTypeValidator { + + public static final int DEFAULT_STRING_MAXIMUM_LENGTH = 100; + + public static int STRING_MAXIMUM_LENGTH = DEFAULT_STRING_MAXIMUM_LENGTH; + + private static Logger log = LoggerFactory.getLogger(StringValidator.class.getName()); + + private static StringValidator stringValidator = new StringValidator(); + + public static StringValidator getInstance() { + return 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; + } + } + } + } + + @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 the configured({})", value.length(), STRING_MAXIMUM_LENGTH); + return false; + } + String coverted = ValidationUtils.removeNoneUtf8Chars(value); + boolean isValid = ValidationUtils.validateIsAscii(coverted); + + if (false == isValid) { + log.debug("parameter String value {} is not ascii string.", (value != null ? value.substring(0, Math.min(value.length(), 20)) : null)); + } + + 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 new file mode 100644 index 0000000000..7f8dff42d0 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.validators; + +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 String[] validValues = { "true", "on", "yes", "y", "false", "off", "no", "n" }; + + public static ToscaBooleanValidator getInstance() { + return booleanValidator; + } + + private ToscaBooleanValidator() { + + } + + @Override + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + + if (value == null || true == value.isEmpty()) { + return true; + } + + 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); + } +} 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 new file mode 100644 index 0000000000..dadfd49831 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.version; + +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) { + 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 new file mode 100644 index 0000000000..905d8bf3bc --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java @@ -0,0 +1,463 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.version; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +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; + +/** + * Generic implementation of version comparison. + * + * <p> + * Features: + * <ul> + * <li>mixing of '<code>-</code>' (dash) and '<code>.</code>' (dot) + * separators,</li> + * <li>transition between characters and digits also constitutes a separator: + * <code>1.0alpha1 => [1, 0, alpha, 1]</code></li> + * <li>unlimited number of version components,</li> + * <li>version components in the text can be digits or strings,</li> + * <li>strings are checked for well-known qualifiers and the qualifier ordering + * is used for version ordering. Well-known qualifiers (case insensitive) are: + * <ul> + * <li><code>alpha</code> or <code>a</code></li> + * <li><code>beta</code> or <code>b</code></li> + * <li><code>milestone</code> or <code>m</code></li> + * <li><code>rc</code> or <code>cr</code></li> + * <li><code>snapshot</code></li> + * <li><code>(the empty string)</code> or <code>ga</code> or + * <code>final</code></li> + * <li><code>sp</code></li> + * </ul> + * Unknown qualifiers are considered after known qualifiers, with lexical order + * (always case insensitive),</li> + * <li>a dash usually precedes a qualifier, and is always less important than + * something preceded with a dot.</li> + * </ul> + * </p> + * + * @see <a href= + * "https://cwiki.apache.org/confluence/display/MAVENOLD/Versioning">"Versioning" + * on Maven Wiki</a> + * @author <a href="mailto:kenney@apache.org">Kenney Westerhof</a> + * @author <a href="mailto:hboutemy@apache.org">Hervé Boutemy</a> + */ +public class ComparableVersion implements Comparable<ComparableVersion> { + private String value; + + private String canonical; + + private ListItem items; + + private interface Item { + int INTEGER_ITEM = 0; + int STRING_ITEM = 1; + int LIST_ITEM = 2; + + int compareTo(Item item); + + int getType(); + + boolean isNull(); + } + + /** + * Represents a numeric item in the version item list. + */ + private static class IntegerItem implements 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(); + } +} 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 new file mode 100644 index 0000000000..268ee28b96 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java @@ -0,0 +1,192 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.tosca.version; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.StringTokenizer; +import java.util.regex.Pattern; + +/** + * Default implementation of artifact versioning. + * + * @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(); + } +} |