diff options
Diffstat (limited to 'common-parameters')
62 files changed, 2700 insertions, 2574 deletions
diff --git a/common-parameters/pom.xml b/common-parameters/pom.xml index 9b8f01d9..b3be6500 100644 --- a/common-parameters/pom.xml +++ b/common-parameters/pom.xml @@ -1,7 +1,8 @@ <!-- ============LICENSE_START======================================================= Copyright (C) 2018 Ericsson. All rights reserved. - Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + Modifications Copyright (C) 2023-2024 Nordix Foundation. ================================================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -23,7 +24,7 @@ <parent> <groupId>org.onap.policy.common</groupId> <artifactId>common-modules</artifactId> - <version>1.6.2-SNAPSHOT</version> + <version>2.1.3-SNAPSHOT</version> </parent> <artifactId>common-parameters</artifactId> @@ -31,32 +32,39 @@ <description>[${project.parent.artifactId}] module provides common property and parameter handling the ONAP Policy Framework</description> <dependencies> - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-lang3</artifactId> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <scope>provided</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> - <groupId>org.assertj</groupId> - <artifactId>assertj-core</artifactId> - <scope>test</scope> + <groupId>jakarta.validation</groupId> + <artifactId>jakarta.validation-api</artifactId> </dependency> <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + </dependency> + <dependency> + <groupId>com.google.re2j</groupId> + <artifactId>re2j</artifactId> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> - <groupId>org.yaml</groupId> - <artifactId>snakeyaml</artifactId> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> </dependencies> diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java index f8eebcf1..e1620530 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java @@ -1,6 +1,6 @@ -/* +/*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 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. @@ -23,6 +23,9 @@ package org.onap.policy.common.parameters; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.BiConsumer; import java.util.function.Function; /** @@ -65,6 +68,19 @@ public class BeanValidationResult extends ValidationResultImpl { } /** + * Adds a result to this result. + * @param name name of the object of this result + * @param object object being validated + * @param status status of the new result + * @param message new result message + * @return {@code true} if the status is {@code null} or valid, {@code false} if the + * status is invalid + */ + public boolean addResult(String name, Object object, ValidationStatus status, String message) { + return addResult(new ObjectValidationResult(name, object, status, message)); + } + + /** * Validates that a sub-object within the bean is not {@code null}. * * @param subName name of the sub-object @@ -72,7 +88,7 @@ public class BeanValidationResult extends ValidationResultImpl { * @return {@code true} if the value is not null, {@code false} otherwise */ public boolean validateNotNull(String subName, Object subObject) { - ObjectValidationResult result = new ObjectValidationResult(subName, subObject); + var result = new ObjectValidationResult(subName, subObject); if (result.validateNotNull()) { return true; @@ -110,10 +126,10 @@ public class BeanValidationResult extends ValidationResultImpl { return true; } - BeanValidationResult result = new BeanValidationResult(listName, null); + var result = new BeanValidationResult(listName, null); for (T item : list) { if (item == null) { - result.addResult(new ObjectValidationResult("item", item, ValidationStatus.INVALID, "null")); + result.addResult("item", item, ValidationStatus.INVALID, "null"); } else { result.addResult(itemValidator.apply(item)); } @@ -129,6 +145,34 @@ public class BeanValidationResult extends ValidationResultImpl { } /** + * Validates the entries in a map. + * + * @param mapName name of the list + * @param map map whose entries are to be validated, or {@code null} + * @param entryValidator function to validate an entry in the map + * @return {@code true} if all entries in the map are valid, {@code false} otherwise + */ + public <V> boolean validateMap(String mapName, Map<String, V> map, + BiConsumer<BeanValidationResult, Entry<String, V>> entryValidator) { + if (map == null) { + return true; + } + + var result = new BeanValidationResult(mapName, null); + for (Entry<String, V> ent : map.entrySet()) { + entryValidator.accept(result, ent); + } + + if (result.isValid()) { + return true; + + } else { + addResult(result); + return false; + } + } + + /** * Gets the validation result. * * @param initialIndentation the indentation to use on the main result output @@ -142,7 +186,7 @@ public class BeanValidationResult extends ValidationResultImpl { return null; } - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); builder.append(initialIndentation); builder.append('"'); diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidator.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidator.java new file mode 100644 index 00000000..4ed7e42c --- /dev/null +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidator.java @@ -0,0 +1,432 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; +import org.apache.commons.lang3.StringUtils; +import org.onap.policy.common.parameters.annotations.ClassName; +import org.onap.policy.common.parameters.annotations.Max; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; +import org.onap.policy.common.parameters.annotations.Pattern; +import org.onap.policy.common.parameters.annotations.Size; +import org.onap.policy.common.parameters.annotations.Valid; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Bean validator, supporting the parameter annotations. + */ +public class BeanValidator { + public static final Logger logger = LoggerFactory.getLogger(BeanValidator.class); + + /** + * Validates top level fields within an object. For each annotated field, it retrieves + * the value using the public "getter" method for the field. If there is no public + * "getter" method, then it throws an exception. Otherwise, it validates the retrieved + * value based on the annotations. This recurses through super classes looking for + * fields to be verified, but it does not examine any interfaces. + * + * @param name name of the object being validated + * @param object object to be validated. If {@code null}, then an empty result is + * returned + * @return the validation result + */ + public BeanValidationResult validateTop(String name, Object object) { + var result = new BeanValidationResult(name, object); + if (object == null) { + return result; + } + + // check class hierarchy - don't need to check interfaces + for (Class<?> clazz = object.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + validateFields(result, object, clazz); + } + + return result; + } + + /** + * Adds validators based on the annotations that are available. + * + * @param validator where to add the validators + */ + protected void addValidators(ValueValidator validator) { + validator.addAnnotation(NotNull.class, this::verNotNull); + validator.addAnnotation(NotBlank.class, this::verNotBlank); + validator.addAnnotation(Size.class, this::verSize); + validator.addAnnotation(Max.class, this::verMax); + validator.addAnnotation(Min.class, this::verMin); + validator.addAnnotation(Pattern.class, this::verRegex); + validator.addAnnotation(ClassName.class, this::verClassName); + validator.addAnnotation(Valid.class, this::verCascade); + } + + /** + * Performs validation of all annotated fields found within the class. + * + * @param result validation results are added here + * @param object object whose fields are to be validated + * @param clazz class, within the object's hierarchy, to be examined for fields to be + * verified + */ + private void validateFields(BeanValidationResult result, Object object, Class<?> clazz) { + for (Field field : clazz.getDeclaredFields()) { + var validator = makeFieldValidator(clazz, field); + validator.validateField(result, object); + } + } + + /** + * Verifies that the value is not null. + * + * @param result where to add the validation result + * @param fieldName field whose value is being verified + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verNotNull(BeanValidationResult result, String fieldName, Object value) { + if (value == null) { + result.addResult(fieldName, xlate(value), ValidationStatus.INVALID, "is null"); + return false; + } + + return true; + } + + /** + * Verifies that the value is not blank. Note: this does <i>not</i> verify that the + * value is not {@code null}. + * + * @param result where to add the validation result + * @param fieldName field whose value is being verified + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verNotBlank(BeanValidationResult result, String fieldName, Object value) { + if (value instanceof String && StringUtils.isBlank(value.toString())) { + result.addResult(fieldName, xlate(value), ValidationStatus.INVALID, "is blank"); + return false; + } + + return true; + } + + /** + * Verifies that the value has the specified number of elements. + * + * @param result where to add the validation result + * @param fieldName field whose value is being verified + * @param annot annotation against which the value is being verified + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verSize(BeanValidationResult result, String fieldName, Size annot, Object value) { + int size; + if (value instanceof Collection) { + size = ((Collection<?>) value).size(); + + } else if (value instanceof Map) { + size = ((Map<?, ?>) value).size(); + + } else { + return true; + } + + + if (size < annot.min()) { + result.addResult(fieldName, xlate(value), ValidationStatus.INVALID, + "minimum number of elements: " + annot.min()); + return false; + } + + return true; + } + + /** + * Verifies that the value matches a regular expression. + * + * @param result where to add the validation result + * @param fieldName field whose value is being verified + * @param annot annotation against which the value is being verified + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verRegex(BeanValidationResult result, String fieldName, Pattern annot, Object value) { + try { + if (value instanceof String && com.google.re2j.Pattern.matches(annot.regexp(), value.toString())) { + return true; + } + + } catch (RuntimeException e) { + logger.warn("validation error for regular expression: {}", annot.regexp(), e); + } + + result.addResult(fieldName, xlate(value), ValidationStatus.INVALID, + "does not match regular expression " + annot.regexp()); + return false; + } + + /** + * Verifies that the value is <= the minimum value. + * + * @param result where to add the validation result + * @param fieldName field whose value is being verified + * @param annot annotation against which the value is being verified + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verMax(BeanValidationResult result, String fieldName, Max annot, Object value) { + if (!(value instanceof Number)) { + return true; + } + + Number num = (Number) value; + if (num instanceof Integer || num instanceof Long) { + if (num.longValue() <= annot.value()) { + return true; + } + + } else if (num instanceof Float || num instanceof Double) { + if (num.doubleValue() <= annot.value()) { + return true; + } + + } else { + return true; + } + + result.addResult(fieldName, xlate(value), ValidationStatus.INVALID, + "exceeds the maximum value: " + annot.value()); + return false; + } + + /** + * Verifies that the value is >= the minimum value. + * + * @param result where to add the validation result + * @param fieldName field whose value is being verified + * @param annot annotation against which the value is being verified + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verMin(BeanValidationResult result, String fieldName, Min annot, Object value) { + return verMin(result, fieldName, annot.value(), value); + } + + /** + * Verifies that the value is >= the minimum value. + * + * @param result where to add the validation result + * @param fieldName field whose value is being verified + * @param min minimum against which the value is being verified + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verMin(BeanValidationResult result, String fieldName, long min, Object value) { + if (!(value instanceof Number)) { + return true; + } + + Number num = (Number) value; + if (num instanceof Integer || num instanceof Long) { + if (num.longValue() >= min) { + return true; + } + + } else if (num instanceof Float || num instanceof Double) { + if (num.doubleValue() >= min) { + return true; + } + + } else { + return true; + } + + result.addResult(fieldName, xlate(value), ValidationStatus.INVALID, + "is below the minimum value: " + min); + return false; + } + + /** + * Verifies that the value is a valid class name. + * + * @param result where to add the validation result + * @param fieldName field whose value is being verified + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verClassName(BeanValidationResult result, String fieldName, Object value) { + if (!(value instanceof String)) { + return true; + } + + try { + Class.forName(value.toString()); + return true; + + } catch (final ClassNotFoundException exp) { + result.addResult(fieldName, value, ValidationStatus.INVALID, "class is not in the classpath"); + return false; + } + } + + /** + * Verifies that the value is valid by recursively invoking + * {@link #validateTop(String, Object)}. + * + * @param result where to add the validation result + * @param fieldName field whose value is being verified + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verCascade(BeanValidationResult result, String fieldName, Object value) { + if (value == null || value instanceof Collection || value instanceof Map) { + return true; + } + + BeanValidationResult result2 = (value instanceof ParameterGroup ? ((ParameterGroup) value).validate() + : validateTop(fieldName, value)); + + if (result2.isClean()) { + return true; + } + + result.addResult(result2); + + return result2.isValid(); + } + + /** + * Validates the items in a collection. + * + * @param result where to add the validation result + * @param fieldName name of the field containing the collection + * @param itemValidator validator for individual items within the list + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verCollection(BeanValidationResult result, String fieldName, ValueValidator itemValidator, + Object value) { + + if (!(value instanceof Collection)) { + return true; + } + + Collection<?> list = (Collection<?>) value; + + var result2 = new BeanValidationResult(fieldName, value); + var count = 0; + for (Object item : list) { + itemValidator.validateValue(result2, String.valueOf(count++), item); + } + + if (result2.isClean()) { + return true; + } + + result.addResult(result2); + return false; + } + + /** + * Validates the items in a Map. + * + * @param result where to add the validation result + * @param fieldName name of the field containing the map + * @param keyValidator validator for an individual key within the Map entry + * @param valueValidator validator for an individual value within the Map entry + * @param value value to be verified + * @return {@code true} if the next check should be performed, {@code false} otherwise + */ + public boolean verMap(BeanValidationResult result, String fieldName, ValueValidator keyValidator, + ValueValidator valueValidator, Object value) { + + if (!(value instanceof Map)) { + return true; + } + + Map<?, ?> map = (Map<?, ?>) value; + + var result2 = new BeanValidationResult(fieldName, value); + + for (Entry<?, ?> entry : map.entrySet()) { + String name = getEntryName(entry); + + var result3 = new BeanValidationResult(name, entry); + keyValidator.validateValue(result3, "key", entry.getKey()); + valueValidator.validateValue(result3, "value", entry.getValue()); + + if (!result3.isClean()) { + result2.addResult(result3); + } + } + + if (result2.isClean()) { + return true; + } + + result.addResult(result2); + return false; + } + + /** + * Gets a name for an entry. + * + * @param entry entry whose name is to be determined + * @return a name for the entry + */ + protected <K, V> String getEntryName(Map.Entry<K, V> entry) { + var key = entry.getKey(); + if (key == null) { + return ""; + } + + return key.toString(); + } + + /** + * Makes a field validator. + * + * @param clazz class containing the field + * @param field field of interest + * @return a validator for the given field + */ + protected FieldValidator makeFieldValidator(Class<?> clazz, Field field) { + return new FieldValidator(this, clazz, field); + } + + /** + * Translates a value to something printable, for use by + * {@link ObjectValidationResult}. This default method simply returns the original + * value. + * + * @param value value to be translated + * @return the translated value + */ + public Object xlate(Object value) { + return value; + } +} diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java deleted file mode 100644 index f35d1970..00000000 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * This class holds the result of the validation of a parameter group. - */ -public abstract class CommonGroupValidationResult implements ValidationResult { - - - private final String messagePrefix; - - /** - * Validation status for the entire class. - */ - protected ValidationStatus status = ValidationStatus.CLEAN; - - /** - * Status message. - */ - protected String message; - - /** - * Validation results for each parameter in the group. - */ - protected final Map<String, ValidationResult> validationResultMap = new LinkedHashMap<>(); - - - /** - * Constructs the object. - * - * @param messagePrefix status message prefix - */ - public CommonGroupValidationResult(String messagePrefix) { - this.messagePrefix = messagePrefix; - this.message = messagePrefix + status.toString(); - } - - /** - * Gets the status of validation. - * - * @return the status - */ - @Override - public ValidationStatus getStatus() { - return status; - } - - /** - * Set the validation result on a parameter group. - * - * @param status The validation status the parameter group is receiving - * @param message The validation message explaining the validation status - */ - @Override - public void setResult(ValidationStatus status, String message) { - setResult(status); - this.message = message; - } - - /** - * Set the validation result on a parameter group. On a sequence of calls, the most - * serious validation status is recorded, assuming the status enum ordinal increase in - * order of severity - * - * @param status The validation status the parameter group is receiving - */ - public void setResult(final ValidationStatus status) { - if (this.status.ordinal() < status.ordinal()) { - this.status = status; - this.message = messagePrefix + status; - } - } - - /** - * Gets the validation result. - * - * @param initialIndentation the indentation to use on the main result output - * @param subIndentation the indentation to use on sub parts of the result output - * @param showClean output information on clean fields - * @return the result - */ - @Override - public String getResult(final String initialIndentation, final String subIndentation, final boolean showClean) { - if (status == ValidationStatus.CLEAN && !showClean) { - return null; - } - - StringBuilder result = new StringBuilder(); - - result.append(initialIndentation); - - addGroupTypeName(result); - - result.append(status); - result.append(", "); - result.append(message); - result.append('\n'); - - for (ValidationResult fieldResult : validationResultMap.values()) { - String msg = fieldResult.getResult(initialIndentation + subIndentation, subIndentation, showClean); - if (msg != null) { - result.append(msg); - } - } - - return result.toString(); - } - - /** - * Adds the group type and name to the result string. - * - * @param result result string - */ - protected abstract void addGroupTypeName(StringBuilder result); -} diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/FieldValidator.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/FieldValidator.java new file mode 100644 index 00000000..d441c286 --- /dev/null +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/FieldValidator.java @@ -0,0 +1,292 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import com.google.gson.annotations.SerializedName; +import java.lang.annotation.Annotation; +import java.lang.reflect.AnnotatedParameterizedType; +import java.lang.reflect.AnnotatedType; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.Map; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import org.apache.commons.lang3.StringUtils; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Validator of the contents of a field, supporting the parameter annotations. + */ +public class FieldValidator extends ValueValidator { + + /** + * {@code True} if there is a field-level annotation, {@code false} otherwise. + */ + @Getter + @Setter(AccessLevel.PROTECTED) + private boolean fieldAnnotated = false; + + /** + * Class containing the field of interest. + */ + private final Class<?> clazz; + + /** + * Field of interest. + */ + private final Field field; + + /** + * Name of the field when serialized (i.e., as the client would know it). + */ + private final String serializedName; + + /** + * Method to retrieve the field's value. + */ + private Method accessor; + + + /** + * Constructs the object. + * + * @param validator provider of validation methods + * @param clazz class containing the field + * @param field field whose value is to be validated + */ + public FieldValidator(BeanValidator validator, Class<?> clazz, Field field) { + this.clazz = clazz; + this.field = field; + + String fieldName = field.getName(); + if (fieldName.contains("$")) { + serializedName = fieldName; + return; + } + + SerializedName serAnnot = field.getAnnotation(SerializedName.class); + serializedName = (serAnnot != null ? serAnnot.value() : fieldName); + + validator.addValidators(this); + addListValidator(validator); + addMapValidator(validator); + + if (checkers.isEmpty()) { + // has no annotations - nothing to check + return; + } + + // verify the field type is of interest + int mod = field.getModifiers(); + if (Modifier.isStatic(mod)) { + classOnly(clazz.getName() + "." + fieldName + " is annotated but the field is static"); + checkers.clear(); + return; + } + + // get the field's "getter" method + accessor = getAccessor(clazz, fieldName); + if (accessor == null) { + classOnly(clazz.getName() + "." + fieldName + " is annotated but has no \"get\" method"); + checkers.clear(); + return; + } + + // determine if null is allowed + if (field.getAnnotation(NotNull.class) != null || clazz.getAnnotation(NotNull.class) != null) { + setNullAllowed(false); + } + } + + /** + * Adds validators for the individual items within a collection, if the field is a + * collection. + * + * @param validator provider of validation methods + */ + private void addListValidator(BeanValidator validator) { + if (!Collection.class.isAssignableFrom(field.getType())) { + return; + } + + var tannot = field.getAnnotatedType(); + if (!(tannot instanceof AnnotatedParameterizedType)) { + return; + } + + AnnotatedType[] targs = ((AnnotatedParameterizedType) tannot).getAnnotatedActualTypeArguments(); + if (targs.length != 1) { + return; + } + + var itemValidator = new ItemValidator(validator, targs[0]); + if (itemValidator.isEmpty()) { + return; + } + + checkers.add((result, fieldName, value) -> validator.verCollection(result, fieldName, itemValidator, value)); + } + + /** + * Adds validators for the individual entries within a map, if the field is a map. + * + * @param validator provider of validation methods + */ + private void addMapValidator(BeanValidator validator) { + if (!Map.class.isAssignableFrom(field.getType())) { + return; + } + + var tannot = field.getAnnotatedType(); + if (!(tannot instanceof AnnotatedParameterizedType)) { + return; + } + + AnnotatedType[] targs = ((AnnotatedParameterizedType) tannot).getAnnotatedActualTypeArguments(); + if (targs.length != 2) { + return; + } + + var keyValidator = new ItemValidator(validator, targs[0]); + var valueValidator = new ItemValidator(validator, targs[1]); + if (keyValidator.isEmpty() && valueValidator.isEmpty()) { + return; + } + + checkers.add((result, fieldName, value) -> validator.verMap(result, fieldName, keyValidator, valueValidator, + value)); + } + + /** + * Performs validation of a single field. + * + * @param result validation results are added here + * @param object object whose field is to be validated + */ + public void validateField(BeanValidationResult result, Object object) { + if (isEmpty()) { + // has no annotations - nothing to check + return; + } + + // get the value + Object value = getValue(object, accessor); + + validateValue(result, serializedName, value); + } + + /** + * Gets the value from the object using the accessor function. + * + * @param object object whose value is to be retrieved + * @param accessor "getter" method + * @return the object's value + */ + private Object getValue(Object object, Method accessor) { + try { + return accessor.invoke(object); + + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new IllegalArgumentException(clazz.getName() + "." + field.getName() + " accessor threw an exception", + e); + } + } + + /** + * Throws an exception if there are field-level annotations. + * + * @param exceptionMessage exception message + */ + private void classOnly(String exceptionMessage) { + if (isFieldAnnotated()) { + throw new IllegalArgumentException(exceptionMessage); + } + } + + /** + * Gets an annotation from the field or the class. + * + * @param annotClass annotation class of interest + * @return the annotation, or {@code null} if neither the field nor the class has the + * desired annotation + */ + @Override + public <T extends Annotation> T getAnnotation(Class<T> annotClass) { + + // field annotation takes precedence over class annotation + var annot = field.getAnnotation(annotClass); + if (annot != null) { + setFieldAnnotated(true); + return annot; + } + + return clazz.getAnnotation(annotClass); + } + + /** + * Gets an accessor method for the given field. + * + * @param clazz class whose methods are to be searched + * @param fieldName field whose "getter" is to be identified + * @return the field's "getter" method, or {@code null} if it is not found + */ + private Method getAccessor(Class<?> clazz, String fieldName) { + var capname = StringUtils.capitalize(fieldName); + var accessor2 = getMethod(clazz, "get" + capname); + if (accessor2 != null) { + return accessor2; + } + + return getMethod(clazz, "is" + capname); + } + + /** + * Gets the "getter" method having the specified name. + * + * @param clazz class whose methods are to be searched + * @param methodName name of the method of interest + * @return the method, or {@code null} if it is not found + */ + private Method getMethod(Class<?> clazz, String methodName) { + for (Method method : clazz.getMethods()) { + if (methodName.equals(method.getName()) && validMethod(method)) { + return method; + } + } + + return null; + } + + /** + * Determines if a method is a valid "getter". + * + * @param method method to be checked + * @return {@code true} if the method is a valid "getter", {@code false} otherwise + */ + private boolean validMethod(Method method) { + int mod = method.getModifiers(); + return !(Modifier.isStatic(mod) || method.getReturnType() == void.class || method.getParameterCount() != 0); + } +} diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java deleted file mode 100644 index 2a616dba..00000000 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java +++ /dev/null @@ -1,112 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import java.lang.reflect.Field; -import java.util.Map; -import java.util.Map.Entry; - -/** - * This class holds the result of the validation of a map of parameter groups. - */ -public class GroupMapValidationResult extends CommonGroupValidationResult { - // The name of the parameter group map - final String mapParameterName; - - /** - * Constructor, create the group map validation result. - * - * @param field the map parameter field - * @param mapObject the value of the map parameter field - */ - protected GroupMapValidationResult(final Field field, final Object mapObject) { - super(ParameterConstants.PARAMETER_GROUP_MAP_HAS_STATUS_MESSAGE); - - this.mapParameterName = field.getName(); - - // Cast the map object to a map of parameter groups keyed by string, we can't type check maps - // due to restrictions on generics so we have to check each entry key is a string and each entry - // value is a parameter group - @SuppressWarnings("unchecked") - Map<String, ParameterGroup> parameterGroupMap = (Map<String, ParameterGroup>) mapObject; - - // Add a validation result per map entry - for (Entry<String, ParameterGroup> parameterGroupMapEntry : parameterGroupMap.entrySet()) { - // Create a validation status entry for the map - validationResultMap.put(parameterGroupMapEntry.getKey(), - new GroupValidationResult(parameterGroupMapEntry.getValue())); - } - } - - /** - * Gets the name of the parameter being validated. - * - * @return the name - */ - @Override - public String getName() { - return mapParameterName; - } - - /** - * Set the validation result on a parameter map entry. - * - * @param entryName The name of the parameter map entry - * @param status The validation status for the entry - * @param message The validation message for the entry - */ - public void setResult(final String entryName, final ValidationStatus status, final String message) { - ValidationResult validationResult = validationResultMap.get(entryName); - if (validationResult == null) { - throw new ParameterRuntimeException("no entry with name \"" + entryName + "\" exists"); - } - - // Set the status of the parameter group and replace the field result - validationResult.setResult(status, message); - this.setResult(status); - } - - - /** - * Set the validation result on a parameter map entry. - * - * @param entryName The name of the parameter map entry - * @param mapEntryValidationResult The validation result for the entry - */ - public void setResult(final String entryName, final ValidationResult mapEntryValidationResult) { - ValidationResult validationResult = validationResultMap.get(entryName); - if (validationResult == null) { - throw new ParameterRuntimeException("no entry with name \"" + entryName + "\" exists"); - } - - // Set the status of the parameter group and replace the field result - validationResultMap.put(entryName, mapEntryValidationResult); - this.setResult(mapEntryValidationResult.getStatus()); - } - - @Override - protected void addGroupTypeName(StringBuilder result) { - result.append("parameter group map \""); - result.append(mapParameterName); - result.append("\" "); - } -}
\ No newline at end of file diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java deleted file mode 100644 index fd680451..00000000 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java +++ /dev/null @@ -1,391 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2018-2019 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import org.apache.commons.lang3.StringUtils; - -/** - * This class holds the result of the validation of a parameter group. - */ -public class GroupValidationResult extends CommonGroupValidationResult { - // The parameter group which the validation result applies - private final ParameterGroup parameterGroup; - - /** - * Constructor, create the field validation result with default arguments. - * - * @param parameterGroup the parameter group being validated - */ - public GroupValidationResult(final ParameterGroup parameterGroup) { - super(ParameterConstants.PARAMETER_GROUP_HAS_STATUS_MESSAGE); - - this.parameterGroup = parameterGroup; - - // Parameter group definitions may be optional - if (parameterGroup == null) { - return; - } - - // Add a validation result for all fields in the declared class - for (Field field : parameterGroup.getClass().getDeclaredFields()) { - // Check if a validation result should be added for this declared field - if (isIncludedField(field)) { - // Set a validation result for the field - validationResultMap.put(field.getName(), getSetValidationResult(field, parameterGroup)); - } - } - - // Add a validation result for protected and public fields in super classes - for (Field field : getSuperclassFields(parameterGroup.getClass().getSuperclass())) { - // Check if a validation result should be added for this declared field - if (isIncludedField(field)) { - // Set a validation result for the field - validationResultMap.putIfAbsent(field.getName(), getSetValidationResult(field, parameterGroup)); - } - } - } - - /** - * Construct a validation result for a field, updating "this" status. - * - * @param field The parameter field - * @param ParameterGroup The parameter group containing the field - * @return the validation result - * @throws Exception on accessing private fields - */ - private ValidationResult getSetValidationResult(Field field, ParameterGroup parameterGroup) { - ValidationResult result = getValidationResult(field, parameterGroup); - setResult(result.getStatus()); - - return result; - } - - /** - * Construct a validation result for a field. - * - * @param field The parameter field - * @param ParameterGroup The parameter group containing the field - * @return the validation result - * @throws Exception on accessing private fields - */ - private ValidationResult getValidationResult(final Field field, final ParameterGroup parameterGroup) { - final String fieldName = field.getName(); - final Class<?> fieldType = field.getType(); - final Object fieldObject = getObjectField(parameterGroup, field); - - // perform null checks - ParameterValidationResult result = new ParameterValidationResult(field, fieldObject); - if (!result.isValid()) { - return result; - } - - // Nested parameter groups are allowed - if (ParameterGroup.class.isAssignableFrom(fieldType)) { - if (null != fieldObject) { - return ((ParameterGroup) fieldObject).validate(); - } - else { - return new GroupValidationResult((ParameterGroup) fieldObject); - } - } - - // Nested maps of parameter groups are allowed - if (Map.class.isAssignableFrom(field.getType())) { - checkMapIsParameterGroupMap(fieldName, fieldObject); - return new GroupMapValidationResult(field, fieldObject); - } - - // Collections of parameter groups are not allowed - if (Collection.class.isAssignableFrom(field.getType())) { - checkCollection4ParameterGroups(fieldName, fieldObject); - return result; - } - - // It's a regular parameter - return result; - } - - /** - * Get the value of a field in an object using a getter found with reflection. - * - * @param targetObject The object on which to read the field value - * @param fieldName The name of the field - * @return The field value - */ - private Object getObjectField(final Object targetObject, final Field field) { - String getterMethodName; - - // Check for Boolean fields, the convention for boolean getters is that they start with "is" - // If the field name already starts with "is" then the getter has the field name otherwise - // the field name is prepended with "is" - if (boolean.class.equals(field.getType())) { - if (field.getName().startsWith("is")) { - getterMethodName = field.getName(); - } else { - getterMethodName = "is" + StringUtils.capitalize(field.getName()); - } - } else { - getterMethodName = "get" + StringUtils.capitalize(field.getName()); - } - - // Look up the getter method for the field - Method getterMethod; - try { - getterMethod = targetObject.getClass().getMethod(getterMethodName, (Class<?>[]) null); - } catch (NoSuchMethodException | SecurityException e) { - throw new ParameterRuntimeException("could not get getter method for parameter \"" + field.getName() + "\"", - e); - } - - // Invoke the getter - try { - return getterMethod.invoke(targetObject, (Object[]) null); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new ParameterRuntimeException("error calling getter method for parameter \"" + field.getName() + "\"", - e); - } - } - - /** - * Check if this field is a map of parameter groups indexed by string keys. - * - * @param fieldName the name of the collection field. - * @param mapObject the map object to check - */ - private void checkMapIsParameterGroupMap(String fieldName, Object mapObject) { - if (mapObject == null) { - throw new ParameterRuntimeException("map parameter \"" + fieldName + "\" is null"); - } - - Map<?, ?> incomingMap = (Map<?, ?>) mapObject; - - for (Entry<?, ?> mapEntry : incomingMap.entrySet()) { - // Check the key is a string - if (!String.class.isAssignableFrom(mapEntry.getKey().getClass())) { - throw new ParameterRuntimeException("map entry is not a parameter group keyed by a string, key \"" - + mapEntry.getKey() + "\" in map \"" + fieldName + "\" is not a string"); - } - - // Check the value is a parameter group - if (!ParameterGroup.class.isAssignableFrom(mapEntry.getValue().getClass())) { - throw new ParameterRuntimeException("map entry is not a parameter group keyed by a string, value \"" - + mapEntry.getValue() + "\" in map \"" + fieldName + "\" is not a parameter group"); - } - } - } - - /** - * Check if this field contains parameter groups. - * - * @param fieldName the name of the collection field. - * @param collectionObject the collection object to check - */ - private void checkCollection4ParameterGroups(final String fieldName, final Object collectionObject) { - if (collectionObject == null) { - throw new ParameterRuntimeException("collection parameter \"" + fieldName + "\" is null"); - } - - Collection<?> collection2Check = (Collection<?>) collectionObject; - - for (Object collectionMember : collection2Check) { - if (ParameterGroup.class.isAssignableFrom(collectionMember.getClass())) { - throw new ParameterRuntimeException("collection parameter \"" + fieldName + "\" is illegal," - + " parameter groups are not allowed as collection members"); - } - } - } - - /** - * Gets the parameter group for this validation result. - * - * @return the parameter class - */ - public ParameterGroup getParameterGroup() { - return parameterGroup; - } - - /** - * Gets the name of the parameter group being validated. - * - * @return the name - */ - @Override - public String getName() { - return parameterGroup.getName(); - } - - /** - * Set the validation result on a parameter in a parameter group. - * - * @param parameterName The name of the parameter - * @param status The validation status the field is receiving - * @param message The validation message explaining the validation status - */ - public void setResult(final String parameterName, final ValidationStatus status, final String message) { - ValidationResult validationResult = validationResultMap.get(parameterName); - - if (validationResult == null) { - throw new ParameterRuntimeException("no parameter field exists for parameter: " + parameterName); - } - - // Set the status and the message on the result irrespective of validation result type - validationResult.setResult(status, message); - - // Set the status of this result - this.setResult(status); - } - - /** - * Set the validation result on a nested parameter group. - * - * @param parameterName The name of the parameter field - * @param nestedValidationResult The validation result from a nested field - */ - public void setResult(final String parameterName, final ValidationResult nestedValidationResult) { - GroupValidationResult groupValidationResult; - try { - groupValidationResult = (GroupValidationResult) validationResultMap.get(parameterName); - } catch (ClassCastException e) { - throw new ParameterRuntimeException("parameter is not a nested group parameter: " + parameterName, e); - } - - if (groupValidationResult == null) { - throw new ParameterRuntimeException("no nested parameter field exists for parameter: " + parameterName); - } - - // Set the status of the parameter group and replace the field result - validationResultMap.put(parameterName, nestedValidationResult); - this.setResult(nestedValidationResult.getStatus()); - } - - /** - * Set the validation result on a nested parameter group map entry. - * - * @param parameterName The name of the parameter field - * @param key The key of the map entry - * @param nestedMapValidationResult The validation result from a nested map entry - */ - public void setResult(final String parameterName, final String key, - final ValidationResult nestedMapValidationResult) { - GroupMapValidationResult groupMapValidationResult; - try { - groupMapValidationResult = (GroupMapValidationResult) validationResultMap.get(parameterName); - } catch (ClassCastException e) { - throw new ParameterRuntimeException("parameter is not a nested group map parameter: " + parameterName, e); - } - - if (groupMapValidationResult == null) { - throw new ParameterRuntimeException("no group map parameter field exists for parameter: " + parameterName); - } - - // Set the status of the parameter group and the field - groupMapValidationResult.setResult(key, nestedMapValidationResult); - this.setResult(nestedMapValidationResult.getStatus()); - } - - /** - * Set the validation status on a group map entry. - * - * @param parameterName The name of the parameter field - * @param key The key of the map entry - * @param status The validation status of the entry - * @param message The message for the parameter group - */ - public void setResult(final String parameterName, final String key, final ValidationStatus status, - final String message) { - GroupMapValidationResult groupMapValidationResult; - try { - groupMapValidationResult = (GroupMapValidationResult) validationResultMap.get(parameterName); - } catch (ClassCastException e) { - throw new ParameterRuntimeException("parameter is not a nested group map parameter: " + parameterName, e); - } - - if (groupMapValidationResult == null) { - throw new ParameterRuntimeException("no group map parameter field exists for parameter: " + parameterName); - } - - // Set the status of the parameter group and the field - groupMapValidationResult.setResult(key, status, message); - this.setResult(status); - } - - @Override - protected void addGroupTypeName(StringBuilder result) { - result.append("parameter group \""); - - if (parameterGroup != null) { - result.append(parameterGroup.getName()); - result.append("\" type \""); - result.append(parameterGroup.getClass().getName()); - } else { - result.append("UNDEFINED"); - } - - result.append("\" "); - } - - - /** - * Check if a field should be included for validation. - * - * @param field the field to check for inclusion - * @return true of the field should be included - */ - private boolean isIncludedField(final Field field) { - return !field.getName().startsWith("$") && !field.getName().startsWith("_") - && !Modifier.isStatic(field.getModifiers()); - } - - /** - * Get the public and protected fields of super classes. - * @param firstSuperClass the first superclass to check - * - * @return a set of the superclass fields - */ - private List<Field> getSuperclassFields(final Class<?> firstSuperClass) { - List<Field> superclassFields = new ArrayList<>(); - - Class<?> currentClass = firstSuperClass; - while (currentClass.getSuperclass() != null) { - for (Field field : currentClass.getDeclaredFields()) { - // Check if this field is public or protected - if (Modifier.isPublic(field.getModifiers()) || Modifier.isProtected(field.getModifiers())) { - superclassFields.add(field); - } - } - - // Check the next super class down - currentClass = currentClass.getSuperclass(); - } - - return superclassFields; - } -} diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ItemValidator.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ItemValidator.java new file mode 100644 index 00000000..44b70cdf --- /dev/null +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ItemValidator.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import java.lang.annotation.Annotation; +import java.lang.reflect.AnnotatedType; + +/** + * Validator of an "item", which is typically found in a collection, or the key or value + * components of an entry in a Map. + */ +public class ItemValidator extends ValueValidator { + private final AnnotatedType annotatedType; + + /** + * Constructs the object. + * + * @param validator provider of validation methods + * @param annotatedType a type having validation annotations to be + * applied to the item + */ + public ItemValidator(BeanValidator validator, AnnotatedType annotatedType) { + this(validator, annotatedType, true); + } + + /** + * Constructs the object. + * + * @param validator provider of validation methods + * @param annotatedType a type having validation annotations to be + * applied to the item + * @param addValidators {@code true} if to add validators + */ + public ItemValidator(BeanValidator validator, AnnotatedType annotatedType, boolean addValidators) { + this.annotatedType = annotatedType; + + if (addValidators) { + validator.addValidators(this); + } + } + + /** + * Gets an annotation from the field or the class. + * + * @param annotClass annotation class of interest + * @return the annotation, or {@code null} if the {@link #annotatedType} does + * not contain the desired annotation + */ + @Override + public <T extends Annotation> T getAnnotation(Class<T> annotClass) { + return annotatedType.getAnnotation(annotClass); + } +} diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ObjectValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ObjectValidationResult.java index e5597206..af1884a3 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ObjectValidationResult.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ObjectValidationResult.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 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. @@ -40,6 +40,8 @@ public class ObjectValidationResult extends ValidationResultImpl { * * @param name name of the object of this result * @param object object being validated + * @param status result status + * @param message result message */ public ObjectValidationResult(String name, Object object, ValidationStatus status, String message) { super(name, object, status, message); diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterConstants.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterConstants.java index 240b1f40..300d49c7 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterConstants.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterConstants.java @@ -1,45 +1,43 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2021 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. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.onap.policy.common.parameters; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + /** * This static class holds the values of constants for parameter handling. */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ParameterConstants { // Indentation is 0 on the left and 2 for each level of hierarchy public static final String DEFAULT_INITIAL_RESULT_INDENTATION = ""; public static final String DEFAULT_RESULT_INDENTATION = " "; - + // By default we do not show validation results for parameters that are validated as clean public static final boolean DO_NOT_SHOW_CLEAN_RESULTS = false; - + // Messages for clean validations public static final String PARAMETER_GROUP_HAS_STATUS_MESSAGE = "parameter group has status "; public static final String PARAMETER_GROUP_MAP_HAS_STATUS_MESSAGE = "parameter group map has status "; public static final String PARAMETER_HAS_STATUS_MESSAGE = "parameter has status "; - - /** - * Private constructor to prevent subclassing. - */ - private ParameterConstants() { - // Private constructor to prevent subclassing - } -}
\ No newline at end of file +} diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java index 0b29a4e6..aa3105ef 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2021 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. @@ -20,6 +21,8 @@ package org.onap.policy.common.parameters; +import lombok.Getter; + /** * Exception thrown oon parameter reading, validation, and check errors. * @@ -29,6 +32,7 @@ public class ParameterException extends Exception { private static final long serialVersionUID = -8507246953751956974L; // The object on which the exception was thrown + @Getter private final transient Object object; /** @@ -84,28 +88,19 @@ public class ParameterException extends Exception { /** * Build a cascaded message from an exception and all its nested exceptions. - * + * * @param throwable the top level exception * @return cascaded message string */ public static String buildCascadedMessage(final Throwable throwable) { - final StringBuilder builder = new StringBuilder(); + final var builder = new StringBuilder(); builder.append(throwable.getMessage()); - for (Throwable t = throwable; t != null; t = t.getCause()) { + for (var t = throwable; t != null; t = t.getCause()) { builder.append("\ncaused by: "); builder.append(t.getMessage()); } return builder.toString(); } - - /** - * Get the object on which the exception was thrown. - * - * @return The object on which the exception was thrown - */ - public Object getObject() { - return object; - } } diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroup.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroup.java index 8bfa183b..ab610933 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroup.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroup.java @@ -1,19 +1,20 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2021 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. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ @@ -29,28 +30,28 @@ package org.onap.policy.common.parameters; public interface ParameterGroup { /** * Get the group name. - * + * * @return the group name */ public String getName(); /** * Set the group name. - * + * * @param name the group name */ public void setName(final String name); /** * Validate parameters. - * + * * @return the result of the parameter validation */ - GroupValidationResult validate(); + BeanValidationResult validate(); /** * Check if the parameters are valid. - * + * * @return true if the parameters are valid */ default boolean isValid() { diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroupImpl.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroupImpl.java index f0f34ac1..8a987bdd 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroupImpl.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterGroupImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 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. @@ -20,7 +20,9 @@ package org.onap.policy.common.parameters; +import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; import org.onap.policy.common.parameters.annotations.NotBlank; import org.onap.policy.common.parameters.annotations.NotNull; @@ -32,30 +34,16 @@ import org.onap.policy.common.parameters.annotations.NotNull; @NotBlank @Getter @Setter +@NoArgsConstructor +@AllArgsConstructor public class ParameterGroupImpl implements ParameterGroup { /** - * Group name. Note: this MUST not be "private" or it will not be validated. + * Group name. */ - protected String name; - - /** - * Constructs the object, with a {@code null} name. - */ - public ParameterGroupImpl() { - this.name = null; - } - - /** - * Constructs the object. - * - * @param name the group's name - */ - public ParameterGroupImpl(String name) { - this.name = name; - } + private String name; @Override - public GroupValidationResult validate() { - return new GroupValidationResult(this); + public BeanValidationResult validate() { + return new BeanValidator().validateTop(getClass().getSimpleName(), this); } } diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterRuntimeException.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterRuntimeException.java index 071593a9..4eb79447 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterRuntimeException.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterRuntimeException.java @@ -1,25 +1,28 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2021 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. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.onap.policy.common.parameters; +import lombok.Getter; + /** * A run time exception thrown on parameter validations. * @@ -29,6 +32,7 @@ public class ParameterRuntimeException extends RuntimeException { private static final long serialVersionUID = -8507246953751956974L; // The object on which the exception was thrown + @Getter private final transient Object object; /** @@ -81,13 +85,4 @@ public class ParameterRuntimeException extends RuntimeException { public String getCascadedMessage() { return ParameterException.buildCascadedMessage(this); } - - /** - * Get the object on which the exception was thrown. - * - * @return The object - */ - public Object getObject() { - return object; - } } diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java index 358e5535..a368d25f 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java @@ -1,19 +1,20 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2021 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. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ @@ -24,37 +25,32 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; /** * The parameter service makes ONAP PF parameter groups available to all classes in a JVM. - * + * * <p>The reason for having a parameter service is to avoid having to pass parameters down long call chains in modules * such as PDPs and editors. The parameter service makes correct and verified parameters available statically. - * + * * <p>The parameter service must be used with care because changing a parameter set anywhere in a JVM will affect all * users of those parameters anywhere in the JVM. * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public abstract class ParameterService { +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class ParameterService { // The map holding the parameters private static Map<String, ParameterGroup> parameterGroupMap = new ConcurrentHashMap<>(); /** - * This class is an abstract static class that cannot be extended. - */ - private ParameterService() { - } - - /** * Register a parameter group with the parameter service. * * @param parameterGroup the parameter group */ public static void register(final ParameterGroup parameterGroup) { - if (!parameterGroupMap.containsKey(parameterGroup.getName())) { - parameterGroupMap.put(parameterGroup.getName(), parameterGroup); - } else { + if (parameterGroupMap.putIfAbsent(parameterGroup.getName(), parameterGroup) != null) { throw new ParameterRuntimeException( "\"" + parameterGroup.getName() + "\" already registered in parameter service"); } @@ -70,7 +66,7 @@ public abstract class ParameterService { if (overwrite && parameterGroupMap.containsKey(parameterGroup.getName())) { deregister(parameterGroup); } - + register(parameterGroup); } @@ -80,9 +76,7 @@ public abstract class ParameterService { * @param parameterGroupName the name of the parameter group */ public static void deregister(final String parameterGroupName) { - if (parameterGroupMap.containsKey(parameterGroupName)) { - parameterGroupMap.remove(parameterGroupName); - } else { + if (parameterGroupMap.remove(parameterGroupName) == null) { throw new ParameterRuntimeException("\"" + parameterGroupName + "\" not registered in parameter service"); } } @@ -104,7 +98,7 @@ public abstract class ParameterService { */ public static <T extends ParameterGroup> T get(final String parameterGroupName) { @SuppressWarnings("unchecked") - final T parameterGroup = (T) parameterGroupMap.get(parameterGroupName); + final var parameterGroup = (T) parameterGroupMap.get(parameterGroupName); if (parameterGroup == null) { throw new ParameterRuntimeException("\"" + parameterGroupName + "\" not found in parameter service"); @@ -120,7 +114,7 @@ public abstract class ParameterService { * @return true if the parameter is defined */ public static boolean contains(final String parameterGroupName) { - return parameterGroupMap.containsKey(parameterGroupName) && parameterGroupMap.get(parameterGroupName) != null; + return parameterGroupMap.get(parameterGroupName) != null; } /** diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java index 35837376..7e56230d 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019, 2021 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. @@ -73,7 +73,7 @@ public class ParameterValidationResult implements ValidationResult { * @param parameterValue field's value */ private void checkMinValue(final Field field, final Object parameterValue) { - Min minAnnot = field.getAnnotation(Min.class); + var minAnnot = field.getAnnotation(Min.class); if (minAnnot != null && ((Number) parameterValue).longValue() < minAnnot.value()) { setResult(ValidationStatus.INVALID, "must be >= " + minAnnot.value()); } @@ -86,7 +86,7 @@ public class ParameterValidationResult implements ValidationResult { * @param parameterValue field's value */ private void checkMaxValue(final Field field, final Object parameterValue) { - Max maxAnnot = field.getAnnotation(Max.class); + var maxAnnot = field.getAnnotation(Max.class); if (maxAnnot != null && ((Number) parameterValue).longValue() > maxAnnot.value()) { setResult(ValidationStatus.INVALID, "must be <= " + maxAnnot.value()); } @@ -102,7 +102,7 @@ public class ParameterValidationResult implements ValidationResult { * @return the field's annotation, or {@code null} if it does not exist */ private static <T extends Annotation> T getAnyAnnotation(final Field field, Class<T> annotClass) { - T annot = field.getAnnotation(annotClass); + var annot = field.getAnnotation(annotClass); if (annot != null) { return annot; } @@ -157,21 +157,13 @@ public class ParameterValidationResult implements ValidationResult { return null; } - StringBuilder validationResultBuilder = new StringBuilder(); - - validationResultBuilder.append(initialIndentation); - validationResultBuilder.append("field \""); - validationResultBuilder.append(getName()); - validationResultBuilder.append("\" type \""); - validationResultBuilder.append(field.getType().getName()); - validationResultBuilder.append("\" value \""); - validationResultBuilder.append(parameterValue); - validationResultBuilder.append("\" "); - validationResultBuilder.append(getStatus()); - validationResultBuilder.append(", "); - validationResultBuilder.append(message); - validationResultBuilder.append('\n'); - - return validationResultBuilder.toString(); + return initialIndentation + + "field \"" + getName() + + "\" type \"" + field.getType().getName() + + "\" value \"" + parameterValue + + "\" " + getStatus() + + ", " + + message + + '\n'; } } diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ValidationResultImpl.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ValidationResultImpl.java index 1d8aa239..45898818 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ValidationResultImpl.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ValidationResultImpl.java @@ -1,6 +1,7 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2020 Bell Canada. 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. @@ -20,12 +21,14 @@ package org.onap.policy.common.parameters; +import lombok.AllArgsConstructor; import lombok.Getter; /** * Basic implementation of a ValidationResult. */ @Getter +@AllArgsConstructor public abstract class ValidationResultImpl implements ValidationResult { public static final String ITEM_HAS_STATUS_MESSAGE = "item has status "; @@ -56,27 +59,12 @@ public abstract class ValidationResultImpl implements ValidationResult { * @param name name of the object of this result * @param object object being validated */ - public ValidationResultImpl(String name, Object object) { + protected ValidationResultImpl(String name, Object object) { this.name = name; this.object = object; } /** - * Constructs the object. - * - * @param name name of the object of this result - * @param object object being validated - * @param status the validation status - * @param message the validation message explaining the validation status - */ - public ValidationResultImpl(String name, Object object, ValidationStatus status, String message) { - this.name = name; - this.object = object; - this.status = status; - this.message = message; - } - - /** * Validates that the value is not {@code null}. * * @return {@code true} if the value is not null, {@code false} otherwise diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ValueValidator.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ValueValidator.java new file mode 100644 index 00000000..faf41008 --- /dev/null +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ValueValidator.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.List; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Validator of a value. + * <p/> + * Note: this currently does not support Min/Max validation of "short" or "byte"; these + * annotations are simply ignored for these types. + */ +@NoArgsConstructor +public class ValueValidator { + + /** + * {@code True} if the value is allowed to be {@code null}, {@code false} otherwise. + * Subclasses are expected to set this, typically based on the validation annotations + * associated with the value. + */ + @Getter + @Setter(AccessLevel.PROTECTED) + private boolean nullAllowed = true; + + /** + * Predicates to invoke to validate an object. + * <p/> + * Note: each predicate is expected to return {@code true} if the next check is + * allowed to proceed, {@code false} otherwise. In addition, if {@link #nullAllowed} + * is {@code true}, then the predicates must be prepared to deal with a {@code null} + * Object as their input parameter. + */ + protected List<Checker> checkers = new ArrayList<>(10); + + /** + * Determines if the validator has anything to check. + * + * @return {@code true} if the validator is empty (i.e., has nothing to check) + */ + public boolean isEmpty() { + return checkers.isEmpty(); + } + + /** + * Performs validation of a single field. + * + * @param result validation results are added here + * @param fieldName field whose value is being verified + * @param value value to be validated + */ + protected void validateValue(BeanValidationResult result, String fieldName, Object value) { + + if (value == null && isNullAllowed()) { + // value is null and null is allowed - just return + return; + } + + for (Checker checker : checkers) { + if (!checker.test(result, fieldName, value)) { + // invalid - don't bother with additional checks + return; + } + } + } + + /** + * Looks for an annotation at the class or field level. If an annotation is found at + * either the field or class level, then it adds a verifier to + * {@link ValueValidator#checkers}. + * + * @param annotClass class of annotation to find + * @param checker function to validate the value + */ + public <T extends Annotation> void addAnnotation(Class<T> annotClass, Checker checker) { + var annot = getAnnotation(annotClass); + if (annot != null) { + checkers.add(checker); + + if (annotClass == NotNull.class) { + setNullAllowed(false); + } + } + } + + /** + * Looks for an annotation at the class or field level. If an annotation is found at + * either the field or class level, then it adds a verifier to + * {@link ValueValidator#checkers}. + * + * @param annotClass class of annotation to find + * @param checker function to validate the value + */ + public <T extends Annotation> void addAnnotation(Class<T> annotClass, CheckerWithAnnot<T> checker) { + var annot = getAnnotation(annotClass); + if (annot != null) { + checkers.add((result, fieldName, value) -> checker.test(result, fieldName, annot, value)); + } + } + + /** + * Gets an annotation from the field or the class. The default method simply returns + * {@code null}. + * + * @param annotClass annotation class of interest + * @return the annotation, or {@code null} if neither the field nor the class has the + * desired annotation + */ + public <T extends Annotation> T getAnnotation(Class<T> annotClass) { + return null; + } + + // functions to validate a value extracted from a field + + public static interface Checker { + boolean test(BeanValidationResult result, String fieldName, Object value); + } + + public static interface CheckerWithAnnot<T extends Annotation> { + boolean test(BeanValidationResult result, String fieldName, T annotation, Object value); + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/EmptyParameterGroup.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/ClassName.java index d1787482..14d76fd7 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/EmptyParameterGroup.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/ClassName.java @@ -1,7 +1,8 @@ -/*- +/* * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * ONAP + * ================================================================================ + * Copyright (C) 2021 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. @@ -14,18 +15,23 @@ * 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. - * - * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.policy.common.parameters.testclasses; +package org.onap.policy.common.parameters.annotations; -import org.onap.policy.common.parameters.ParameterGroupImpl; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; -public class EmptyParameterGroup extends ParameterGroupImpl { +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Indicates that a field (i.e., String) identifies the name of a class in the classpath. + */ +@Retention(RUNTIME) +@Target({FIELD, TYPE_USE}) +public @interface ClassName { - public EmptyParameterGroup(String name) { - super(name); - } } diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Max.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Max.java index 1d8fd90f..f28fd2cf 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Max.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Max.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 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. @@ -21,13 +21,14 @@ package org.onap.policy.common.parameters.annotations; import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) -@Target(FIELD) +@Target({FIELD, TYPE_USE}) public @interface Max { /** diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Min.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Min.java index 9ad6d7e0..305d9810 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Min.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Min.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 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. @@ -21,13 +21,14 @@ package org.onap.policy.common.parameters.annotations; import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) -@Target(FIELD) +@Target({FIELD, TYPE_USE}) public @interface Min { /** diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotBlank.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotBlank.java index 169fa593..0744beb5 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotBlank.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotBlank.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 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. @@ -22,6 +22,7 @@ package org.onap.policy.common.parameters.annotations; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; @@ -31,7 +32,7 @@ import java.lang.annotation.Target; * Indicates that a field (i.e., String) may not be empty. */ @Retention(RUNTIME) -@Target({TYPE, FIELD}) +@Target({TYPE, FIELD, TYPE_USE}) public @interface NotBlank { } diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotNull.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotNull.java index 3c7bc8b7..81356005 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotNull.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/NotNull.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 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. @@ -22,6 +22,7 @@ package org.onap.policy.common.parameters.annotations; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; @@ -31,7 +32,7 @@ import java.lang.annotation.Target; * Indicates that a field may not be null. */ @Retention(RUNTIME) -@Target({TYPE, FIELD}) +@Target({TYPE, FIELD, TYPE_USE}) public @interface NotNull { } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithArray.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Pattern.java index e37b47ae..91a74d70 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithArray.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Pattern.java @@ -1,7 +1,8 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 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. @@ -14,23 +15,24 @@ * 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. - * - * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.policy.common.parameters.testclasses; +package org.onap.policy.common.parameters.annotations; -import org.onap.policy.common.parameters.ParameterGroupImpl; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; -public class ParameterGroupWithArray extends ParameterGroupImpl { - private int[] intArray = {1, 2, 3}; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; - public ParameterGroupWithArray(final String name) { - super(name); - } +@Retention(RUNTIME) +@Target({FIELD, TYPE_USE}) +public @interface Pattern { - public int[] getIntArray() { - return intArray; - } + /** + * Regular expression to be matched. + */ + String regexp(); } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullCollection.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Size.java index 35752c75..160e0124 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullCollection.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Size.java @@ -1,7 +1,8 @@ -/*- +/* * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * ONAP + * ================================================================================ + * Copyright (C) 2021 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. @@ -14,28 +15,29 @@ * 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. - * - * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.policy.common.parameters.testclasses; +package org.onap.policy.common.parameters.annotations; -import java.util.List; -import org.onap.policy.common.parameters.ParameterGroupImpl; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; -public class ParameterGroupWithNullCollection extends ParameterGroupImpl { - private List<Integer> nullList = null; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Indicates the size of a Map or Collection. + */ +@Retention(RUNTIME) +@Target({FIELD, TYPE_USE}) +public @interface Size { /** - * Create a test parameter group. - * @param name the parameter group name + * The minimum size allowed. + * + * @return the minimum size allowed */ - public ParameterGroupWithNullCollection(final String name) { - super(name); - } - - public List<Integer> getNullList() { - return nullList; - } + int min(); } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupMissingGetter.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Valid.java index e6c85923..227a726f 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupMissingGetter.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/annotations/Valid.java @@ -1,7 +1,8 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 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. @@ -14,27 +15,21 @@ * 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. - * - * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.policy.common.parameters.testclasses; - -import org.onap.policy.common.parameters.ParameterGroupImpl; +package org.onap.policy.common.parameters.annotations; -public class ParameterGroupMissingGetter extends ParameterGroupImpl { - private String value; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; - public ParameterGroupMissingGetter(final String name) { - super(name); - } +import java.lang.annotation.Retention; +import java.lang.annotation.Target; - public String getTheValue() { - return value; - } +@Retention(RUNTIME) +@Target({TYPE, FIELD, TYPE_USE}) +public @interface Valid { - public void setValue(String value) { - this.value = value; - } } diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupConstraint.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupConstraint.java new file mode 100644 index 00000000..c73d135a --- /dev/null +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupConstraint.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021, 2023 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters.validation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Constraint(validatedBy = ParameterGroupValidator.class) +@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface ParameterGroupConstraint { + + /** + * Get error Message. + * + * @return error Message + */ + String message() default "validation error(s) on parameters"; + + /** + * Get groups. + * + * @return Class arrays + */ + Class<?>[] groups() default {}; + + /** + * Get payload. + * + * @return Class arrays + */ + Class<? extends Payload>[] payload() default {}; +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullSubGroup.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupValidator.java index 7fe1402f..024ca139 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullSubGroup.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/validation/ParameterGroupValidator.java @@ -1,7 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * Copyright (C) 2021, 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,23 +18,25 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.common.parameters.testclasses; +package org.onap.policy.common.parameters.validation; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import org.onap.policy.common.parameters.BeanValidationResult; import org.onap.policy.common.parameters.ParameterGroup; -import org.onap.policy.common.parameters.ParameterGroupImpl; -public class ParameterGroupWithNullSubGroup extends ParameterGroupImpl { - private ParameterGroup subGroup = null; +public class ParameterGroupValidator implements ConstraintValidator<ParameterGroupConstraint, ParameterGroup> { - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithNullSubGroup(final String name) { - super(name); + @Override + public boolean isValid(ParameterGroup value, ConstraintValidatorContext context) { + if (value == null) { + return true; + } + final BeanValidationResult result = value.validate(); + if (!result.isValid()) { + context.buildConstraintViolationWithTemplate(result.getMessage()).addConstraintViolation(); + } + return result.isValid(); } - public ParameterGroup getSubGroup() { - return subGroup; - } } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java index b874db69..48d2f4b5 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ package org.onap.policy.common.parameters; import static org.junit.Assert.assertEquals; import java.io.IOException; - import org.junit.Test; public class ExceptionTest { diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestAbstractParameters.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestAbstractParameters.java deleted file mode 100644 index b568d7fb..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestAbstractParameters.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.EmptyParameterGroup; - -public class TestAbstractParameters { - - @Test - public void testAbstractParameters() { - final EmptyParameterGroup parameters = new EmptyParameterGroup("Empty Group"); - assertTrue(parameters.isValid()); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java index 12cd80cb..b7bea204 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java @@ -1,8 +1,8 @@ -/* +/*- * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 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. @@ -20,6 +20,7 @@ package org.onap.policy.common.parameters; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -27,17 +28,25 @@ import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TreeMap; +import java.util.function.BiConsumer; import org.junit.Before; import org.junit.Test; public class TestBeanValidationResult { + private static final String TEXT1 = "abc"; + private static final String TEXT2 = "def"; private static final String MY_LIST = "my-list"; + private static final String MY_MAP = "my-map"; private static final String OBJECT = "an object"; private static final String INITIAL_INDENT = "xx "; private static final String NEXT_INDENT = "yy "; private static final String MID_INDENT = "xx yy "; private static final String NAME = "my-name"; private static final String MY_LIST_INVALID = " 'my-list' INVALID, item has status INVALID\n "; + private static final String MY_MAP_INVALID = " 'my-map' INVALID, item has status INVALID\n "; private static final String BEAN_INVALID_MSG = requote("'my-name' INVALID, item has status INVALID\n"); private String cleanMsg; @@ -52,10 +61,10 @@ public class TestBeanValidationResult { */ @Before public void setUp() { - clean = new ObjectValidationResult("abc", 10); + clean = new ObjectValidationResult(TEXT1, 10); cleanMsg = clean.getResult("", "", true); - invalid = new ObjectValidationResult("def", 20); + invalid = new ObjectValidationResult(TEXT2, 20); invalid.setResult(ValidationStatus.INVALID, "invalid"); invalidMsg = invalid.getResult(); @@ -83,6 +92,10 @@ public class TestBeanValidationResult { assertEquals(INITIAL_INDENT + BEAN_INVALID_MSG + MID_INDENT + cleanMsg + MID_INDENT + invalidMsg, bean.getResult(INITIAL_INDENT, NEXT_INDENT, true)); + + bean = new BeanValidationResult(NAME, OBJECT); + assertFalse(bean.addResult(MY_LIST, "hello", ValidationStatus.INVALID, TEXT1)); + assertThat(bean.getResult()).contains("\"" + MY_LIST + "\" value \"hello\" INVALID, " + TEXT1); } @Test @@ -150,6 +163,50 @@ public class TestBeanValidationResult { } + @Test + public void testValidateMap() { + Map<String, ValidationResult> map = null; + bean = new BeanValidationResult(NAME, OBJECT); + assertTrue(bean.validateMap(MY_MAP, map, validMapEntry())); + assertTrue(bean.isValid()); + assertNull(bean.getResult()); + + map = Map.of(TEXT1, clean, TEXT2, clean); + bean = new BeanValidationResult(NAME, OBJECT); + assertTrue(bean.validateMap(MY_MAP, map, validMapEntry())); + assertTrue(bean.isValid()); + assertNull(bean.getResult()); + + // null value in the map + map = new TreeMap<>(); + map.put(TEXT1, clean); + map.put(TEXT2, null); + bean = new BeanValidationResult(NAME, OBJECT); + assertFalse(bean.validateMap(MY_MAP, map, validMapEntry())); + assertFalse(bean.isValid()); + assertEquals(requote(BEAN_INVALID_MSG + MY_MAP_INVALID + + "item 'def' value 'null' INVALID, is null\n"), bean.getResult()); + + map = Map.of(TEXT1, invalid, TEXT2, invalid); + bean = new BeanValidationResult(NAME, OBJECT); + assertFalse(bean.validateMap(MY_MAP, map, validMapEntry())); + assertFalse(bean.isValid()); + assertEquals(requote(BEAN_INVALID_MSG + MY_MAP_INVALID + invalidMsg + + " " + invalidMsg), bean.getResult()); + + } + + private BiConsumer<BeanValidationResult, Entry<String, ValidationResult>> validMapEntry() { + return (result, entry) -> { + var value = entry.getValue(); + if (value == null) { + result.validateNotNull(entry.getKey(), value); + } else { + result.addResult(value); + } + }; + } + private static String requote(String text) { return text.replace('\'', '"'); } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java new file mode 100644 index 00000000..83d0a7f9 --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java @@ -0,0 +1,664 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import lombok.Getter; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.annotations.ClassName; +import org.onap.policy.common.parameters.annotations.Max; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; +import org.onap.policy.common.parameters.annotations.Pattern; +import org.onap.policy.common.parameters.annotations.Size; +import org.onap.policy.common.parameters.annotations.Valid; + +public class TestBeanValidator { + private static final String TOP = "top"; + private static final String STR_FIELD = "strValue"; + private static final String INT_FIELD = "intValue"; + private static final String NUM_FIELD = "numValue"; + private static final String ITEMS_FIELD = "items"; + private static final String STRING_VALUE = "string value"; + private static final int INT_VALUE = 20; + + private BeanValidator validator; + + @Before + public void setUp() { + validator = new BeanValidator(); + } + + @Test + public void testValidateTop_testValidateFields() { + // validate null + assertTrue(validator.validateTop(TOP, null).isValid()); + + // validate something that has no annotations + assertTrue(validator.validateTop(TOP, validator).isValid()); + + @NotNull + @Getter + class Data { + String strValue; + } + + // one failure case + Data data = new Data(); + BeanValidationResult result = validator.validateTop(TOP, data); + assertInvalid("testValidateFields", result, STR_FIELD, "null"); + assertTrue(result.getResult().contains(TOP)); + + // one success case + data.strValue = STRING_VALUE; + assertTrue(validator.validateTop(TOP, data).isValid()); + + /** + * Repeat with a subclass. + */ + @Getter + class Derived extends Data { + @Min(10) + int intValue; + } + + Derived derived = new Derived(); + derived.strValue = STRING_VALUE; + derived.intValue = INT_VALUE; + + // success case + assertTrue(validator.validateTop(TOP, derived).isValid()); + + // failure cases + derived.strValue = null; + assertInvalid("testValidateFields", validator.validateTop(TOP, derived), STR_FIELD, "null"); + derived.strValue = STRING_VALUE; + + derived.intValue = 1; + assertInvalid("testValidateFields", validator.validateTop(TOP, derived), INT_FIELD, "minimum"); + derived.intValue = INT_VALUE; + + // both invalid + derived.strValue = null; + derived.intValue = 1; + result = validator.validateTop(TOP, derived); + assertInvalid("testValidateFields", result, STR_FIELD, "null"); + assertInvalid("testValidateFields", result, INT_FIELD, "minimum"); + derived.strValue = STRING_VALUE; + derived.intValue = INT_VALUE; + } + + @Test + public void testVerNotNull() { + class NotNullCheck { + @Getter + @Min(1) + @NotNull + Integer intValue; + } + + NotNullCheck notNullCheck = new NotNullCheck(); + assertInvalid("testVerNotNull", validator.validateTop(TOP, notNullCheck), INT_FIELD, "null"); + + notNullCheck.intValue = INT_VALUE; + assertTrue(validator.validateTop(TOP, notNullCheck).isValid()); + + notNullCheck.intValue = 0; + assertInvalid("testVerNotNull", validator.validateTop(TOP, notNullCheck), INT_FIELD, "minimum"); + } + + @Test + public void testVerNotBlank() { + class NotBlankCheck { + @Getter + @NotBlank + String strValue; + } + + NotBlankCheck notBlankCheck = new NotBlankCheck(); + + // null + assertTrue(validator.validateTop(TOP, notBlankCheck).isValid()); + + // empty + notBlankCheck.strValue = ""; + assertInvalid("testVerNotNull", validator.validateTop(TOP, notBlankCheck), STR_FIELD, "blank"); + + // spaces + notBlankCheck.strValue = " "; + assertInvalid("testVerNotNull", validator.validateTop(TOP, notBlankCheck), STR_FIELD, "blank"); + + // not blank + notBlankCheck.strValue = STRING_VALUE; + assertTrue(validator.validateTop(TOP, notBlankCheck).isValid()); + + /* + * Class with "blank" annotation on an integer. + */ + class NotBlankInt { + @Getter + @NotBlank + int intValue; + } + + NotBlankInt notBlankInt = new NotBlankInt(); + notBlankInt.intValue = 0; + assertTrue(validator.validateTop(TOP, notBlankInt).isValid()); + } + + /** + * Tests verSize with a collection. + */ + @Test + public void testVerSizeCollection() { + class CollectionSizeCheck { + @Getter + @Size(min = 3) + Collection<Integer> items; + } + + CollectionSizeCheck collCheck = new CollectionSizeCheck(); + + // valid length - exact + collCheck.items = List.of(1, 2, 3); + assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue(); + + // valid length - extra + collCheck.items = List.of(1, 2, 3, 4); + assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue(); + + // too few + collCheck.items = List.of(1, 2); + assertInvalid("testVerSize", validator.validateTop(TOP, collCheck), ITEMS_FIELD, "minimum", "3"); + + // null + collCheck.items = null; + assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue(); + } + + /** + * Tests verSize with a map. + */ + @Test + public void testVerSizeMap() { + class MapSizeCheck { + @Getter + @Size(min = 3) + Map<Integer, Integer> items; + } + + MapSizeCheck mapCheck = new MapSizeCheck(); + + // valid length - exact + mapCheck.items = Map.of(1, 10, 2, 20, 3, 30); + assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue(); + + // valid length - extra + mapCheck.items = Map.of(1, 10, 2, 20, 3, 30, 4, 40); + assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue(); + + // too few + mapCheck.items = Map.of(1, 10, 2, 20); + assertInvalid("testVerSize", validator.validateTop(TOP, mapCheck), ITEMS_FIELD, "minimum", "3"); + + // null + mapCheck.items = null; + assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue(); + } + + /** + * Tests verSize with an object for which it doesn't apply. + */ + @Test + public void testVerSizeOther() { + class OtherSizeCheck { + @Getter + @Size(min = 3) + Integer items; + } + + OtherSizeCheck otherCheck = new OtherSizeCheck(); + + otherCheck.items = 10; + assertThat(validator.validateTop(TOP, otherCheck).isValid()).isTrue(); + } + + @Test + public void testVerRegex() { + class RegexCheck { + @Getter + @Pattern(regexp = "[a-f]*") + String strValue; + } + + RegexCheck regexCheck = new RegexCheck(); + + // does not match + regexCheck.strValue = "xyz"; + assertInvalid("testVerRegex", validator.validateTop(TOP, regexCheck), STR_FIELD, + "does not match regular expression [a-f]"); + + // matches + regexCheck.strValue = "abcabc"; + assertTrue(validator.validateTop(TOP, regexCheck).isValid()); + + // invalid regex + class InvalidRegexCheck { + @Getter + @Pattern(regexp = "[a-f") + String strValue; + } + + InvalidRegexCheck invalidRegexCheck = new InvalidRegexCheck(); + + // does not match + invalidRegexCheck.strValue = "abc"; + assertInvalid("testVerRegex", validator.validateTop(TOP, invalidRegexCheck), STR_FIELD, + "does not match regular expression [a-f"); + + // matches + regexCheck.strValue = "abcabc"; + assertTrue(validator.validateTop(TOP, regexCheck).isValid()); + + /* + * Class with "regex" annotation on an integer. + */ + class RegexInt { + @Getter + @Pattern(regexp = "[a-f]*") + int intValue; + } + + RegexInt regexInt = new RegexInt(); + regexInt.intValue = 0; + assertInvalid("testVerRegex", validator.validateTop(TOP, regexInt), INT_FIELD, + "does not match regular expression [a-f]"); + } + + @Test + public void testVerMax() { + /* + * Field is not a number. + */ + class NonNumeric { + @Getter + @Max(100) + String strValue; + } + + NonNumeric nonNumeric = new NonNumeric(); + nonNumeric.strValue = STRING_VALUE; + assertTrue(validator.validateTop(TOP, nonNumeric).isValid()); + + /* + * Integer field. + */ + class IntField { + @Getter + @Max(100) + Integer intValue; + } + + // ok value + IntField intField = new IntField(); + assertNumeric("testVerMax-integer", intField, value -> { + intField.intValue = value; + }, INT_FIELD, "maximum", INT_VALUE, 100, 101); + + /* + * Long field. + */ + class LongField { + @Getter + @Max(100) + Long numValue; + } + + // ok value + LongField longField = new LongField(); + assertNumeric("testVerMax-long", longField, value -> { + longField.numValue = (long) value; + }, NUM_FIELD, "maximum", INT_VALUE, 100, 101); + + /* + * Float field. + */ + class FloatField { + @Getter + @Max(100) + Float numValue; + } + + // ok value + FloatField floatField = new FloatField(); + assertNumeric("testVerMax-float", floatField, value -> { + floatField.numValue = (float) value; + }, NUM_FIELD, "maximum", INT_VALUE, 100, 101); + + /* + * Double field. + */ + class DoubleField { + @Getter + @Max(100) + Double numValue; + } + + // ok value + DoubleField doubleField = new DoubleField(); + assertNumeric("testVerMax-double", doubleField, value -> { + doubleField.numValue = (double) value; + }, NUM_FIELD, "maximum", INT_VALUE, 100, 101); + + /* + * Atomic Integer field (which is a subclass of Number). + */ + class AtomIntValue { + @Getter + @Max(100) + AtomicInteger numValue; + } + + // ok value + AtomIntValue atomIntField = new AtomIntValue(); + atomIntField.numValue = new AtomicInteger(INT_VALUE); + assertTrue(validator.validateTop(TOP, atomIntField).isValid()); + + // invalid value - should be OK, because it isn't an Integer + atomIntField.numValue.set(101); + assertTrue(validator.validateTop(TOP, atomIntField).isValid()); + } + + @Test + public void testVerMin() { + /* + * Field is not a number. + */ + class NonNumeric { + @Getter + @Min(10) + String strValue; + } + + NonNumeric nonNumeric = new NonNumeric(); + nonNumeric.strValue = STRING_VALUE; + assertTrue(validator.validateTop(TOP, nonNumeric).isValid()); + + /* + * Integer field. + */ + class IntField { + @Getter + @Min(10) + Integer intValue; + } + + // ok value + IntField intField = new IntField(); + assertNumeric("testVerMin-integer", intField, value -> { + intField.intValue = value; + }, INT_FIELD, "minimum", INT_VALUE, 10, 1); + + /* + * Long field. + */ + class LongField { + @Getter + @Min(10) + Long numValue; + } + + // ok value + LongField longField = new LongField(); + assertNumeric("testVerMin-long", longField, value -> { + longField.numValue = (long) value; + }, NUM_FIELD, "minimum", INT_VALUE, 10, 1); + + /* + * Float field. + */ + class FloatField { + @Getter + @Min(10) + Float numValue; + } + + // ok value + FloatField floatField = new FloatField(); + assertNumeric("testVerMin-float", floatField, value -> { + floatField.numValue = (float) value; + }, NUM_FIELD, "minimum", INT_VALUE, 10, 1); + + /* + * Double field. + */ + class DoubleField { + @Getter + @Min(10) + Double numValue; + } + + // ok value + DoubleField doubleField = new DoubleField(); + assertNumeric("testVerMin-double", doubleField, value -> { + doubleField.numValue = (double) value; + }, NUM_FIELD, "minimum", INT_VALUE, 10, 1); + + /* + * Atomic Integer field (which is a subclass of Number). + */ + class AtomIntValue { + @Getter + @Min(10) + AtomicInteger numValue; + } + + // ok value + AtomIntValue atomIntField = new AtomIntValue(); + atomIntField.numValue = new AtomicInteger(INT_VALUE); + assertTrue(validator.validateTop(TOP, atomIntField).isValid()); + + // invalid value - should be OK, because it isn't an Integer + atomIntField.numValue.set(101); + assertTrue(validator.validateTop(TOP, atomIntField).isValid()); + } + + @Test + public void testVerClassName() { + class ClassNameCheck { + @Getter + @ClassName + String strValue; + } + + ClassNameCheck classCheck = new ClassNameCheck(); + + // null should be OK + classCheck.strValue = null; + assertTrue(validator.validateTop(TOP, classCheck).isValid()); + + // valid class name + classCheck.strValue = getClass().getName(); + assertTrue(validator.validateTop(TOP, classCheck).isValid()); + + // invalid class name + classCheck.strValue = "<unknown class>"; + assertInvalid("testVerClassName", validator.validateTop(TOP, classCheck), + STR_FIELD, "class is not in the classpath"); + } + + @Test + public void testVerCascade() { + class Item { + @Getter + @NotNull + Integer intValue; + } + + @Getter + class Container { + @Valid + Item checked; + + Item unchecked; + + @Valid + List<Item> items; + + @Valid + Map<String, Item> itemMap; + } + + Container cont = new Container(); + cont.unchecked = new Item(); + cont.items = List.of(new Item()); + cont.itemMap = Map.of(STRING_VALUE, new Item()); + + cont.checked = null; + assertTrue(validator.validateTop(TOP, cont).isValid()); + + cont.checked = new Item(); + + assertInvalid("testVerCascade", validator.validateTop(TOP, cont), INT_FIELD, "null"); + + cont.checked.intValue = INT_VALUE; + assertTrue(validator.validateTop(TOP, cont).isValid()); + } + + @Test + public void testVerCollection() { + @Getter + class Container { + List<@Min(5) Integer> items; + + // not a collection - should not be checked + @Valid + String strValue; + + String noAnnotations; + } + + Container cont = new Container(); + cont.strValue = STRING_VALUE; + cont.noAnnotations = STRING_VALUE; + + // null collection - always valid + assertTrue(validator.validateTop(TOP, cont).isValid()); + + // empty collection - always valid + cont.items = List.of(); + assertTrue(validator.validateTop(TOP, cont).isValid()); + + cont.items = List.of(-10, -20); + assertThat(validator.validateTop(TOP, cont).getResult()).contains("\"0\"", "-10", "\"1\"", "-20", "minimum"); + + cont.items = List.of(10, -30); + assertThat(validator.validateTop(TOP, cont).getResult()).contains("\"1\"", "-30", "minimum") + .doesNotContain("\"0\""); + + cont.items = List.of(10, 20); + assertTrue(validator.validateTop(TOP, cont).isValid()); + } + + @Test + public void testVerMap() { + @Getter + class Container { + Map<String, @Min(5) Integer> items; + + // not a map + @NotBlank + String strValue; + + String noAnnotations; + } + + Container cont = new Container(); + cont.strValue = STRING_VALUE; + cont.noAnnotations = STRING_VALUE; + + // null map - always valid + assertTrue(validator.validateTop(TOP, cont).isValid()); + + // empty map - always valid + cont.items = Map.of(); + assertTrue(validator.validateTop(TOP, cont).isValid()); + + cont.items = Map.of("abc", -10, "def", -20); + assertThat(validator.validateTop(TOP, cont).getResult()).contains("abc", "-10", "def", "-20", "minimum"); + + cont.items = Map.of("abc", 10, "def", -30); + assertThat(validator.validateTop(TOP, cont).getResult()).contains("def", "-30", "minimum") + .doesNotContain("abc"); + + cont.items = Map.of("abc", 10, "def", 20); + assertTrue(validator.validateTop(TOP, cont).isValid()); + } + + @Test + public void testGetEntryName() { + assertThat(validator.getEntryName(makeEntry(null, 0))).isEmpty(); + assertThat(validator.getEntryName(makeEntry("", 0))).isEmpty(); + assertThat(validator.getEntryName(makeEntry(STRING_VALUE, 0))).isEqualTo(STRING_VALUE); + } + + /** + * Makes a Map entry with the given key and value. + * + * @param key desired key + * @param value desired value + * @return a new Map entry + */ + private Map.Entry<String, Integer> makeEntry(String key, int value) { + HashMap<String, Integer> map = new HashMap<>(); + map.put(key, value); + return map.entrySet().iterator().next(); + } + + private <T> void assertNumeric(String testName, T object, Consumer<Integer> setter, String fieldName, + String expectedText, int inside, int edge, int outside) { + setter.accept(inside); + assertTrue(validator.validateTop(TOP, object).isValid()); + + // on the edge + setter.accept(edge); + assertTrue(validator.validateTop(TOP, object).isValid()); + + // invalid + setter.accept(outside); + assertInvalid("testVerNotNull", validator.validateTop(TOP, object), fieldName, expectedText); + } + + + private void assertInvalid(String testName, BeanValidationResult result, String... text) { + assertThat(result.getResult()).describedAs(testName).contains(text); + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java new file mode 100644 index 00000000..81a7b8ff --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java @@ -0,0 +1,379 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.gson.annotations.SerializedName; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Map; +import lombok.Getter; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +public class TestFieldValidator extends ValidatorUtil { + private static final String INT_LIST_FIELD = "intList"; + private static final String INT_MAP_FIELD = "intMap"; + private static final String UNANNOTATED_FIELD = "unannotated"; + private static final String INT_FIELD = "intValue"; + private static final int VALID_INT = 10; + private static final int INVALID_INT = -10; + + @Getter + private int unannotated; + + @Min(0) + @Getter + private int intValue; + + @Getter + private List<@Min(1) Integer> intList; + + @Getter + private Map<@NotBlank String, @Min(1) Integer> intMap; + + @SerializedName("annotated_key_map") + @Getter + private Map<@NotBlank String, Integer> annotatedKeyMap; + + @Getter + private Map<String, @Min(1) Integer> annotatedValueMap; + + @Getter + private List<Integer> unannotatedList; + + @Getter + private Map<String, Integer> unannotatedMap; + + @NotNull + @Getter + private boolean boolValue; + + @NotNull + @Getter + private String notNullValue; + + @Min(0) + @Getter + private static int staticField; + + /** + * Has no accessor. + */ + @Min(0) + private int noMethod; + + /** + * Accessor is {@link #getStaticMethod()}, which is static. + */ + @Min(0) + private int staticMethod; + + /** + * Accessor is {@link #getVoidMethod()}, which returns a void. + */ + @Min(0) + private int voidMethod; + + /** + * Accessor is {@link #getParameterizedMethod()}, which requires a parameter. + */ + @Min(0) + private int parameterizedMethod; + + /** + * Accessor is {@link #getExMethod()}, which throws an exception. + */ + @Min(0) + private int exMethod; + + + @Before + public void setUp() { + bean = new BeanValidator(); + } + + @Test + public void testGetAnnotation() { + // field-level annotation + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + + // class-level annotation + assertThat(new FieldValidator(bean, ClassAnnot.class, getField(ClassAnnot.class, "text")).isEmpty()).isFalse(); + } + + @Test + public void testFieldValidator() throws NoSuchFieldException, SecurityException { + /* + * Note: nested classes contain fields like "$this", thus the check for "$" in the + * variable name is already covered by the other tests. + */ + + /* + * Class with no annotations. + */ + @NotNull + class NoAnnotations { + @SuppressWarnings("unused") + String strValue; + } + + Field field = NoAnnotations.class.getDeclaredField("this$0"); + + assertThat(new FieldValidator(bean, NoAnnotations.class, field).isEmpty()).isTrue(); + + // unannotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("unannotated")).isEmpty()).isTrue(); + + // these are invalid for various reasons + + Field staticField2 = getField("staticField"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticField2)) + .isInstanceOf(IllegalArgumentException.class); + + Field noMethodField = getField("noMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, noMethodField)) + .isInstanceOf(IllegalArgumentException.class); + + // annotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + } + + @Test + public void testFieldValidator_SetNullAllowed() { + // default - null is allowed + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isNullAllowed()).isTrue(); + + // field-level NotNull + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("notNullValue")).isNullAllowed()) + .isFalse(); + + // class-level NotNull + assertThat(new FieldValidator(bean, ClassAnnot.class, getField(ClassAnnot.class, "noMethod")).isNullAllowed()) + .isFalse(); + } + + @Test + public void testAddListValidator() { + + // unannotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("unannotatedList")).isEmpty()).isTrue(); + + // annotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_LIST_FIELD)).isEmpty()).isFalse(); + } + + @Test + public void testAddMapValidator() { + + // unannotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("unannotatedMap")).isEmpty()).isTrue(); + + // annotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_MAP_FIELD)).isEmpty()).isFalse(); + + // only the key is annotated + FieldValidator validator = new FieldValidator(bean, TestFieldValidator.class, getField("annotatedKeyMap")); + assertThat(validator.isEmpty()).isFalse(); + + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + annotatedKeyMap = Map.of("abc", -10); + validator.validateField(result, this); + assertThat(result.getResult()).isNull(); + + annotatedKeyMap = Map.of(" ", -10); + validator.validateField(result, this); + assertThat(result.getResult()).contains("annotated_key_map", "blank").doesNotContain("-10"); + + // only the value is annotated + validator = new FieldValidator(bean, TestFieldValidator.class, getField("annotatedValueMap")); + assertThat(validator.isEmpty()).isFalse(); + + result = new BeanValidationResult(MY_NAME, this); + annotatedValueMap = Map.of(" ", 10); + validator.validateField(result, this); + assertThat(result.getResult()).isNull(); + + annotatedValueMap = Map.of(" ", -10); + validator.validateField(result, this); + assertThat(result.getResult()).doesNotContain("blank").contains("annotatedValueMap", "\" \"", "-10"); + } + + @SuppressWarnings("deprecation") + @Test + public void testValidateField_testGetValue() { + // unannotated + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + new FieldValidator(bean, getClass(), getField(UNANNOTATED_FIELD)).validateField(result, this); + assertThat(result.getResult()).isNull(); + + // valid + intValue = VALID_INT; + result = new BeanValidationResult(MY_NAME, this); + new FieldValidator(bean, getClass(), getField(INT_FIELD)).validateField(result, this); + assertThat(result.getResult()).isNull(); + + // invalid + intValue = INVALID_INT; + result = new BeanValidationResult(MY_NAME, this); + new FieldValidator(bean, getClass(), getField(INT_FIELD)).validateField(result, this); + assertThat(result.getResult()).contains(INT_FIELD); + + // throws an exception + FieldValidator validator = new FieldValidator(bean, TestFieldValidator.class, getField("exMethod")); + BeanValidationResult result2 = new BeanValidationResult(MY_NAME, this); + assertThatThrownBy(() -> validator.validateField(result2, this)).isInstanceOf(IllegalArgumentException.class) + .getCause().isInstanceOf(InvocationTargetException.class).getCause() + .hasMessage("expected exception"); + } + + @Test + public void testValidateField_testGetValue_ListField() { + // valid + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + intList = List.of(10, 20, 30, 40); + new FieldValidator(bean, getClass(), getField(INT_LIST_FIELD)).validateField(result, this); + assertThat(result.getResult()).isNull(); + + // invalid + result = new BeanValidationResult(MY_NAME, this); + intList = List.of(9, -8, 7, -6); + new FieldValidator(bean, getClass(), getField(INT_LIST_FIELD)).validateField(result, this); + assertThat(result.getResult()).doesNotContain("0", "9").contains("1", "-8").doesNotContain("2", "7") + .contains("3", "-6"); + } + + @Test + public void testValidateField_testGetValue_MapField() { + // valid + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + intMap = Map.of("ten", 10, "twenty", 20, "thirty", 30, "forty", 40); + new FieldValidator(bean, getClass(), getField(INT_MAP_FIELD)).validateField(result, this); + assertThat(result.getResult()).isNull(); + + // invalid + result = new BeanValidationResult(MY_NAME, this); + intMap = Map.of("ten", 9, "twenty", -8, "thirty", 7, "forty", -6); + new FieldValidator(bean, getClass(), getField(INT_MAP_FIELD)).validateField(result, this); + assertThat(result.getResult()).doesNotContain("ten", "9").contains("twenty", "-8").doesNotContain("thirty", "7") + .contains("forty", "-6"); + } + + @Test + public void testClassOnly() { + // class-level annotation has no bearing on a static field + assertThat(new FieldValidator(bean, ClassAnnot.class, getField(ClassAnnot.class, "staticValue")).isEmpty()) + .isTrue(); + + // field-level annotation on a static field + Field staticField2 = getField("staticField"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticField2)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void testGetAccessor() { + // uses "getXxx" + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + + // uses "isXxx" + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("boolValue")).isEmpty()).isFalse(); + } + + @Test + public void testGetMethod() { + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + + // these are invalid for various reasons + + Field noMethodField = getField("noMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, noMethodField)) + .isInstanceOf(IllegalArgumentException.class); + + Field staticMethodField = getField("staticMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticMethodField)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void testValidMethod() { + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + + // these are invalid for various reasons + + Field staticMethodField = getField("staticMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticMethodField)) + .isInstanceOf(IllegalArgumentException.class); + + Field voidMethodField = getField("voidMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, voidMethodField)) + .isInstanceOf(IllegalArgumentException.class); + + Field paramMethodField = getField("parameterizedMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, paramMethodField)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void testIsFieldAnnotated_testSetFieldAnnotated() { + // annotated at the field level + assertThat(new FieldValidator(bean, getClass(), getField(INT_FIELD)).isFieldAnnotated()).isTrue(); + + // unannotated + assertThat(new FieldValidator(bean, getClass(), getField(UNANNOTATED_FIELD)).isFieldAnnotated()).isFalse(); + } + + public static int getStaticMethod() { + return -1000; + } + + public void getVoidMethod() { + // do nothing + } + + public int getParameterizedMethod(boolean flag) { + return 0; + } + + public int getExMethod() { + throw new RuntimeException("expected exception"); + } + + @NotNull + public static class ClassAnnot { + @Getter + private String text; + + // no "get" method + @SuppressWarnings("unused") + private String noMethod; + + @Getter + private static int staticValue; + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java new file mode 100644 index 00000000..cadcfdee --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +public class TestItemValidator extends ValidatorUtil { + + // annotated fields - each field must have exactly one annotation + + /** + * This annotation does not contain a method returning an array. + */ + @Min(value = 0) + private int notArray; + + /** + * This annotation doesn't contain any annotations that the {@link BeanValidator} + * recognizes. + */ + @Simple + private int mismatch; + + /** + * No annotations. + */ + @SuppressWarnings("unused") + private int noAnnotations; + + /** + * One matching annotation. + */ + @NotNull + private int match; + + /** + * Multiple matching annotations. + */ + @NotNull + @NotBlank + private String multiMatch; + + + @Before + public void setUp() { + bean = new BeanValidator(); + } + + @Test + public void testGetAnnotation() { + // no matches + assertThat(new ItemValidator(bean, getAnnotType("noAnnotations"), true).isEmpty()).isTrue(); + + // had a match + assertThat(new ItemValidator(bean, getAnnotType("match"), true).checkers).hasSize(1); + + // multiple matches + ItemValidator validator = new ItemValidator(bean, getAnnotType("multiMatch"), true); + assertThat(validator.checkers).hasSize(2); + + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + validator.validateValue(result, MY_FIELD, HELLO); + assertThat(result.getResult()).isNull(); + + result = new BeanValidationResult(MY_NAME, this); + validator.validateValue(result, MY_FIELD, null); + assertThat(result.getResult()).isNotNull(); + + result = new BeanValidationResult(MY_NAME, this); + validator.validateValue(result, MY_FIELD, ""); + assertThat(result.getResult()).isNotNull(); + } + + @Test + public void testItemValidatorBeanValidatorAnnotation() { + assertThat(new ItemValidator(bean, getAnnotType("match")).isEmpty()).isFalse(); + } + + @Test + public void testItemValidatorBeanValidatorAnnotationBoolean() { + assertThat(new ItemValidator(bean, getAnnotType("match"), true).isEmpty()).isFalse(); + + assertThat(new ItemValidator(bean, getAnnotType("match"), false).isEmpty()).isTrue(); + } + + // these annotations are not recognized by the BeanValidator + + @Retention(RUNTIME) + @Target(FIELD) + public @interface Simple { + + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java deleted file mode 100644 index abef5528..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import java.io.FileReader; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.TestParametersL00; - - -public class TestJsonInput { - - @Test - public void testJsonInput() throws IOException { - TestParametersL00 testParameterGroup = null; - - // Read the parameters from JSON using Gson - final Gson gson = new GsonBuilder().create(); - testParameterGroup = gson.fromJson(new FileReader("src/test/resources/parameters/TestParameters.json"), - TestParametersL00.class); - - GroupValidationResult validationResult = testParameterGroup.validate(); - assertTrue(validationResult.isValid()); - assertEquals("l00NameFromFile", testParameterGroup.getName()); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt"))) - .replaceAll("\\s+", ""); - assertEquals(expectedResult, validationResult.getResult("", " ", true).replaceAll("\\s+", "")); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java deleted file mode 100644 index fda37816..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.EmptyParameterGroup; - -public class TestParameterService { - private static final String EMPTY_GROUP = "Empty Group"; - - @Test - public void testParameterService() { - ParameterService.clear(); - - assertFalse(ParameterService.contains("EmptyGroup")); - - assertThatThrownBy(() -> ParameterService.get("EmptyGroup")) - .hasMessage("\"EmptyGroup\" not found in parameter service"); - - ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP)); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - assertNotNull(ParameterService.get(EMPTY_GROUP)); - - assertThatThrownBy(() -> ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP))) - .hasMessage("\"Empty Group\" already registered in parameter service"); - - assertThatThrownBy(() -> ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), false)) - .hasMessage("\"Empty Group\" already registered in parameter service"); - - ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), true); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - - ParameterService.deregister(EMPTY_GROUP); - assertFalse(ParameterService.contains(EMPTY_GROUP)); - - ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), true); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - - ParameterService.deregister(EMPTY_GROUP); - assertFalse(ParameterService.contains(EMPTY_GROUP)); - - EmptyParameterGroup epg = new EmptyParameterGroup(EMPTY_GROUP); - ParameterService.register(epg); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - assertNotNull(ParameterService.get(EMPTY_GROUP)); - - ParameterService.deregister(epg); - assertFalse(ParameterService.contains(EMPTY_GROUP)); - - assertThatThrownBy(() -> ParameterService.deregister(EMPTY_GROUP)) - .hasMessage("\"Empty Group\" not registered in parameter service"); - - assertThatThrownBy(() -> ParameterService.get(EMPTY_GROUP)) - .hasMessage("\"Empty Group\" not found in parameter service"); - - ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP)); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - assertNotNull(ParameterService.get(EMPTY_GROUP)); - - assertEquals(1, ParameterService.getAll().size()); - ParameterService.clear(); - assertEquals(0, ParameterService.getAll().size()); - assertFalse(ParameterService.contains(EMPTY_GROUP)); - - assertThatThrownBy(() -> ParameterService.get(EMPTY_GROUP)) - .hasMessage("\"Empty Group\" not found in parameter service"); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java index 9e7121cd..b19b92da 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019, 2021 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. @@ -21,25 +21,17 @@ package org.onap.policy.common.parameters; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; import org.junit.Test; import org.onap.policy.common.parameters.annotations.Max; import org.onap.policy.common.parameters.annotations.Min; import org.onap.policy.common.parameters.annotations.NotBlank; import org.onap.policy.common.parameters.annotations.NotNull; -import org.onap.policy.common.parameters.testclasses.TestParametersL00; -import org.onap.policy.common.parameters.testclasses.TestParametersL10; +import org.onap.policy.common.parameters.annotations.Valid; public class TestValidation { - private static final String L0_PARAMETERS = "l0Parameters"; - private static final String NOT_BLANK_STRING_MESSAGE = "field 'notBlankString' type 'java.lang.String' value '' INVALID, must be a non-blank string\n" .replace('\'', '"'); @@ -74,177 +66,15 @@ public class TestValidation { private long maxLong; @Test - public void testValidationOk() throws IOException { - TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS); - - GroupValidationResult validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertTrue(validationResult.isClean()); - assertNull(validationResult.getResult()); - assertEquals(l0Parameters, validationResult.getParameterGroup()); - assertEquals(l0Parameters.getName(), validationResult.getName()); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt"))) - .replaceAll("\\s+", ""); - assertEquals(expectedResult, validationResult.getResult("", " ", true).replaceAll("\\s+", "")); - } - - @Test - public void testValidationObservation() throws IOException { - TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS); - - l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 3); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt"))) - .replaceAll("\\s+", ""); - - GroupValidationResult validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertFalse(validationResult.isClean()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 2); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 1); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 0); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(null, validationResult.getResult()); - } - - @Test - public void testValidationWarning() throws IOException { - TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS); - - l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 3); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt"))) - .replaceAll("\\s+", ""); - - GroupValidationResult validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 2); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 1); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 0); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(null, validationResult.getResult()); - } - - @Test - public void testValidationInvalid() throws IOException { - TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS); - - l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 3); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt"))) - .replaceAll("\\s+", ""); - - GroupValidationResult validationResult = l0Parameters.validate(); - assertFalse(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 2); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertFalse(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 1); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertFalse(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 0); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(null, validationResult.getResult()); - } - - @Test - public void testValidationEmptySubGroup() { - TestParametersL10 l10Parameters = new TestParametersL10("l10Parameters"); - - l10Parameters.setL10LGenericNested0(null); - - GroupValidationResult validationResult = l10Parameters.validate(); - assertTrue(validationResult.isValid()); - - assertTrue(validationResult.getResult("", "", true).contains("UNDEFINED")); - } - - @Test public void testGetValidationResult() { Contained item = new Contained(); item.setName("item"); Container cont = new Container(); cont.item = item; - GroupValidationResult result = cont.validate(); + BeanValidationResult result = cont.validate(); assertEquals(ValidationStatus.INVALID, result.getStatus()); - assertTrue(result.getResult().contains(">= 1")); + assertThat(result.getResult()).contains("minimum"); item.minInt = 1000; result = cont.validate(); @@ -253,7 +83,7 @@ public class TestValidation { cont.item = null; result = cont.validate(); assertEquals(ValidationStatus.INVALID, result.getStatus()); - assertTrue(result.getResult().contains("is null")); + assertThat(result.getResult()).contains("is null"); } @Test @@ -429,6 +259,7 @@ public class TestValidation { private static class Container extends ParameterGroupImpl { @NotNull + @Valid private Contained item; public Container() { diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java deleted file mode 100644 index b02022d7..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.ParameterGroupMissingGetter; -import org.onap.policy.common.parameters.testclasses.ParameterGroupPrivateGetter; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithArray; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithCollection; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithIllegalMapKey; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithIllegalMapValue; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithNullCollection; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithNullMapValue; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithNullSubGroup; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithParameterGroupCollection; - -public class TestValidationErrors { - @Test - public void testBadArrayValidation() { - ParameterGroupWithArray groupWithArray = new ParameterGroupWithArray("Illegal Array Group"); - assertTrue(groupWithArray.isValid()); - } - - @Test - public void testCollectionValidation() { - ParameterGroupWithCollection legalCollection = new ParameterGroupWithCollection("Legal Collection"); - assertTrue(legalCollection.isValid()); - - ParameterGroupWithParameterGroupCollection illegalCollection = new ParameterGroupWithParameterGroupCollection( - "Illegal Collection"); - - assertThatThrownBy(illegalCollection::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("collection parameter \"parameterGroupArrayList\" is illegal," - + " parameter groups are not allowed as collection members"); - } - - @Test - public void testNullCollection() { - ParameterGroupWithNullCollection nullCollection = new ParameterGroupWithNullCollection("Null Collection"); - - assertThatThrownBy(nullCollection::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("collection parameter \"nullList\" is null"); - } - - @Test - public void testMapNullSubGroupValidation() { - ParameterGroupWithNullSubGroup nullSub = new ParameterGroupWithNullSubGroup("Null sub group value"); - - nullSub.isValid(); - assertNull(nullSub.getSubGroup()); - } - - @Test - public void testMapNullValueValidation() { - ParameterGroupWithNullMapValue nullMap = new ParameterGroupWithNullMapValue("Null Map value"); - - assertThatThrownBy(nullMap::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("map parameter \"nullMap\" is null"); - } - - @Test - public void testBadMapKeyValidation() { - ParameterGroupWithIllegalMapKey illegalMap = new ParameterGroupWithIllegalMapKey("Illegal Map"); - - assertThatThrownBy(illegalMap::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("map entry is not a parameter group keyed by a string, key \"1\" " - + "in map \"badMap\" is not a string"); - } - - @Test - public void testBadMapValueValidation() { - ParameterGroupWithIllegalMapValue illegalMap = new ParameterGroupWithIllegalMapValue("Illegal Map"); - - assertThatThrownBy(illegalMap::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("map entry is not a parameter group keyed by a string, value \"1\" in " - + "map \"intMap\" is not a parameter group"); - } - - @Test - public void testMissingGetter() { - ParameterGroupMissingGetter badGetterName = new ParameterGroupMissingGetter("BGN"); - - assertThatThrownBy(badGetterName::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("could not get getter method for parameter \"value\""); - } - - @Test - public void testPrivateGetter() { - ParameterGroupPrivateGetter privateGetter = new ParameterGroupPrivateGetter("privateGetter"); - - assertThatThrownBy(privateGetter::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("could not get getter method for parameter \"value\""); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java deleted file mode 100644 index 46360ef9..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java +++ /dev/null @@ -1,143 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.LinkedHashMap; -import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.TestParametersL10; -import org.onap.policy.common.parameters.testclasses.TestParametersLGeneric; - -public class TestValidationResults { - private static final String NON_EXISTANT_PARAMETER = "nonExistantParameter"; - private static final String L10L_GENERIC_NESTED_MAP_VAL0 = "l10LGenericNestedMapVal0"; - private static final String L10_INT_FIELD = "l10IntField"; - private static final String ENTRY0 = "entry0"; - private static final String THIS_VALUE_IS_INVALID = "This value is invalid"; - private static final String SOMETHING_WAS_OBSERVED = "Something was observed"; - private static final String PG_MAP = "pgMap"; - - private Map<String, ParameterGroup> pgMap = new LinkedHashMap<>(); - private ParameterGroup pg = new TestParametersL10("pg"); - - @Before - public void initMap() { - pgMap.put(ENTRY0, new TestParametersLGeneric(ENTRY0)); - } - - @Test - public void testGroupMapValidationResult() throws NoSuchFieldException { - GroupMapValidationResult result = new GroupMapValidationResult(this.getClass().getDeclaredField(PG_MAP), - pgMap); - - assertTrue(result.isValid()); - assertEquals(PG_MAP, result.getName()); - - result.setResult(ValidationStatus.OBSERVATION); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - - // Once the status is stepped, it can't be reset back because it is the status of map members - result.setResult(ValidationStatus.CLEAN); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - - result.setResult(ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - assertEquals("parameter group map \"pgMap\" OBSERVATION, Something was observed", result.getResult().trim()); - - result.setResult(ENTRY0, new GroupValidationResult(pgMap.get(ENTRY0))); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - assertEquals("parameter group map \"pgMap\" OBSERVATION, Something was observed", result.getResult().trim()); - - assertThatThrownBy(() -> result.setResult("nonExistantEntry", new GroupValidationResult(pgMap.get(ENTRY0)))) - .hasMessage("no entry with name \"nonExistantEntry\" exists"); - } - - @Test - public void testGroupValidationResult() throws NoSuchFieldException { - GroupValidationResult result = new GroupValidationResult(pg); - - assertTrue(result.isValid()); - assertEquals(pg, result.getParameterGroup()); - assertEquals("pg", result.getName()); - - result.setResult(ValidationStatus.OBSERVATION); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - - // Once the status is stepped, it can't be reset back because it is the status of map members - result.setResult(ValidationStatus.CLEAN); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - - result.setResult(ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - assertEquals("parameter group \"pg\" type \"org.onap.policy.common.parameters.testclasses.TestParametersL10\"" - + " OBSERVATION, Something was observed", result.getResult().trim()); - - assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, ValidationStatus.OBSERVATION, - SOMETHING_WAS_OBSERVED)) - .hasMessage("no parameter field exists for parameter: nonExistantParameter"); - - result.setResult(L10_INT_FIELD, ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED); - assertTrue(result.isValid()); - - assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, new GroupValidationResult(pg))) - .hasMessage("no nested parameter field exists for parameter: nonExistantParameter"); - - assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, new GroupValidationResult(pg))) - .hasMessage("parameter is not a nested group parameter: l10IntField"); - - GroupMapValidationResult groupMapResult = new GroupMapValidationResult( - this.getClass().getDeclaredField(PG_MAP), pgMap); - - assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, ENTRY0, groupMapResult)) - .hasMessage("no group map parameter field exists for parameter: nonExistantParameter"); - - assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, ENTRY0, groupMapResult)) - .hasMessage("parameter is not a nested group map parameter: l10IntField"); - - result.setResult("l10LGenericNestedMap", L10L_GENERIC_NESTED_MAP_VAL0, ValidationStatus.INVALID, - THIS_VALUE_IS_INVALID); - assertEquals(ValidationStatus.INVALID, result.getStatus()); - - assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, L10L_GENERIC_NESTED_MAP_VAL0, ValidationStatus.INVALID, - THIS_VALUE_IS_INVALID)) - .hasMessage("parameter is not a nested group map parameter: l10IntField"); - - assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, L10L_GENERIC_NESTED_MAP_VAL0, - ValidationStatus.INVALID, THIS_VALUE_IS_INVALID)).hasMessage( - "no group map parameter field exists for parameter: nonExistantParameter"); - - assertThatThrownBy(() -> result.setResult("l10LGenericNestedMap", "NonExistantKey", ValidationStatus.INVALID, - THIS_VALUE_IS_INVALID)).hasMessage("no entry with name \"NonExistantKey\" exists"); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java new file mode 100644 index 00000000..dcf08695 --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.annotation.Annotation; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +public class TestValueValidator extends ValidatorUtil { + + private ValueValidator validator; + + // these fields just provide place-holders for annotations + + @NotNull + @NotBlank + private final int annotField = 1; + + + @Before + public void setUp() { + validator = new MyValueValidator(); + } + + @Test + public void testIsEmpty() { + assertThat(validator.isEmpty()).isTrue(); + + validator.addAnnotation(NotNull.class, (result2, fieldName, value) -> true); + assertThat(validator.isEmpty()).isFalse(); + } + + @Test + public void testValidateValue_NullValue() { + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + + validator.validateValue(result, MY_FIELD, null); + assertThat(result.getResult()).isNull(); + + validator.addAnnotation(NotNull.class, + (result2, fieldName, value) -> result2.validateNotNull(fieldName, value)); + validator.validateValue(result, MY_FIELD, null); + assertThat(result.getResult()).contains(MY_FIELD, "null"); + } + + @Test + public void testValidateValue_NotNullValue() { + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + + validator.validateValue(result, MY_FIELD, HELLO); + assertThat(result.getResult()).isNull(); + + validator.addAnnotation(NotNull.class, + (result2, fieldName, value) -> result2.validateNotNull(fieldName, value)); + validator.validateValue(result, MY_FIELD, HELLO); + assertThat(result.getResult()).isNull(); + } + + @Test + public void testAddAnnotationClassOfTChecker() { + // the field does not have this annotation + validator.addAnnotation(Min.class, (result2, fieldName, value) -> true); + assertThat(validator.isEmpty()).isTrue(); + + // "null" flag should stay true with this annotation + assertThat(validator.isNullAllowed()).isTrue(); + validator.addAnnotation(NotBlank.class, (result2, fieldName, value) -> true); + assertThat(validator.isNullAllowed()).isTrue(); + + // "null" flag should become false with this annotation + assertThat(validator.isNullAllowed()).isTrue(); + validator.addAnnotation(NotNull.class, (result2, fieldName, value) -> true); + assertThat(validator.isNullAllowed()).isFalse(); + } + + @Test + public void testAddAnnotationClassOfTCheckerWithAnnotOfT() { + // the field does not have this annotation + validator.addAnnotation(Min.class, (result2, fieldName, annot, value) -> true); + assertThat(validator.isEmpty()).isTrue(); + + // indicates the annotation value + AtomicBoolean wasNull = new AtomicBoolean(false); + + // the field DOES have this annotation + validator.addAnnotation(NotNull.class, (result2, fieldName, annot, value) -> { + wasNull.set(annot instanceof NotNull); + return result2.validateNotNull(fieldName, value); + }); + assertThat(validator.isEmpty()).isFalse(); + + // ensure that the checker is invoked + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + validator.validateValue(result, MY_FIELD, HELLO); + assertThat(result.getResult()).isNull(); + + assertThat(wasNull.get()).isTrue(); + } + + @Test + public void testGetAnnotation() { + assertThat(new ValueValidator().getAnnotation(NotNull.class)).isNull(); + } + + /** + * Checks for annotations on the "annotField" field. + */ + private static class MyValueValidator extends ValueValidator { + @Override + public <T extends Annotation> T getAnnotation(Class<T> annotClass) { + try { + return TestValueValidator.class.getDeclaredField("annotField").getAnnotation(annotClass); + } catch (NoSuchFieldException | SecurityException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java deleted file mode 100644 index 66656844..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.FileReader; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.TestParametersL00; -import org.yaml.snakeyaml.Yaml; - -public class TestYamlInput { - @Test - public void testYamlInput() throws IOException { - TestParametersL00 testParameterGroup = null; - - // Read the parameters from JSON using Gson - final Yaml yaml = new Yaml(); - testParameterGroup = yaml.loadAs(new FileReader("src/test/resources/parameters/TestParameters.yaml"), - TestParametersL00.class); - - GroupValidationResult validationResult = testParameterGroup.validate(); - assertTrue(validationResult.isValid()); - assertEquals("l00NameFromFile", testParameterGroup.getName()); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt"))) - .replaceAll("\\s+", ""); - assertEquals(expectedResult, validationResult.getResult("", " ", true).replaceAll("\\s+", "")); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java new file mode 100644 index 00000000..e39b5b86 --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import java.lang.annotation.Annotation; +import java.lang.reflect.AnnotatedType; +import java.lang.reflect.Field; + +/** + * Utilities for validator tests. + */ +public class ValidatorUtil { + protected static final String MY_NAME = "My-Name"; + protected static final String MY_FIELD = "My-Field"; + protected static final String HELLO = "hello"; + + protected BeanValidator bean; + + /** + * Gets the single annotation for a given field. + * + * @param fieldName name of the field having the desired annotation + * @return the given field's annotation + */ + protected Annotation getAnnot(String fieldName) { + return getField(fieldName).getAnnotations()[0]; + } + + /** + * Gets the annotated type for a given field. + * + * @param fieldName name of the field of interest + * @return the given field's annotated type + */ + protected AnnotatedType getAnnotType(String fieldName) { + return getField(fieldName).getAnnotatedType(); + } + + /** + * Gets a field from this object. + * + * @param fieldName name of the field of interest + * @return the given field + */ + protected Field getField(String fieldName) { + return getField(getClass(), fieldName); + } + + /** + * Gets a field from a given class. + * + * @param clazz class containing the field + * @param fieldName name of the field of interest + * @return the given field + */ + protected Field getField(Class<?> clazz, String fieldName) { + try { + return clazz.getDeclaredField(fieldName); + + } catch (NoSuchFieldException | SecurityException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java deleted file mode 100644 index 1d90ca1f..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupPrivateGetter extends ParameterGroupImpl { - private String value; - - public ParameterGroupPrivateGetter(final String name) { - super(name); - } - - public String getTheValue() { - return getValue(); - } - - private String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java deleted file mode 100644 index ee7c1715..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.ArrayList; -import java.util.List; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithCollection extends ParameterGroupImpl { - private List<Integer> intArrayList = new ArrayList<>(); - - /** - * Create a test parameter group. - * - * @param name the parameter group name - */ - public ParameterGroupWithCollection(final String name) { - super(name); - - intArrayList.add(1); - intArrayList.add(2); - intArrayList.add(3); - } - - public List<Integer> getIntArrayList() { - return intArrayList; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java deleted file mode 100644 index b3c7d1b7..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.LinkedHashMap; -import java.util.Map; -import org.onap.policy.common.parameters.ParameterGroup; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithIllegalMapKey extends ParameterGroupImpl { - private Map<Integer, ParameterGroup> badMap = new LinkedHashMap<>(); - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithIllegalMapKey(final String name) { - super(name); - - badMap.put(1, new TestParametersLGeneric("One")); - badMap.put(2, new TestParametersLGeneric("Two")); - badMap.put(3, new TestParametersLGeneric("Three")); - } - - public Map<Integer, ParameterGroup> getBadMap() { - return badMap; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java deleted file mode 100644 index 4df708a4..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.LinkedHashMap; -import java.util.Map; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithIllegalMapValue extends ParameterGroupImpl { - private Map<String, Integer> intMap = new LinkedHashMap<>(); - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithIllegalMapValue(final String name) { - super(name); - - intMap.put("One", 1); - intMap.put("Two", 2); - intMap.put("Three", 3); - } - - public Map<String, Integer> getIntMap() { - return intMap; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullMapValue.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullMapValue.java deleted file mode 100644 index 1a640023..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullMapValue.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.Map; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithNullMapValue extends ParameterGroupImpl { - private Map<String, Integer> nullMap = null; - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithNullMapValue(final String name) { - super(name); - } - - public Map<String, Integer> getNullMap() { - return nullMap; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java deleted file mode 100644 index 08c799f5..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.ArrayList; -import java.util.List; -import org.onap.policy.common.parameters.ParameterGroup; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithParameterGroupCollection extends ParameterGroupImpl { - private List<ParameterGroup> parameterGroupArrayList = new ArrayList<>(); - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithParameterGroupCollection(final String name) { - super(name); - - parameterGroupArrayList.add(new TestParametersLGeneric("Generic0")); - parameterGroupArrayList.add(new TestParametersLGeneric("Generic1")); - parameterGroupArrayList.add(new TestParametersLGeneric("Generic2")); - } - - public List<ParameterGroup> getParameterGroupArrayList() { - return parameterGroupArrayList; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java deleted file mode 100644 index 51440546..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java +++ /dev/null @@ -1,208 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import org.apache.commons.lang3.StringUtils; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ParameterConstants; -import org.onap.policy.common.parameters.ParameterGroupImpl; -import org.onap.policy.common.parameters.ValidationStatus; - -public class TestParametersL00 extends ParameterGroupImpl { - private static final String L00_INT_FIELD = "l00IntField"; - private static final String L00_STRING_FIELD = "l00StringField"; - - private static final String A_CONSTANT = "A Constant"; - - private int l00IntField = 0; - private String l00StringField = "Legal " + this.getClass().getName(); - private TestParametersL10 l00L10Nested = new TestParametersL10("l00L10Nested"); - private TestParametersLGeneric l00LGenericNested = new TestParametersLGeneric("l00LGenericNested"); - private Map<String, TestParametersLGeneric> l00LGenericNestedMap = new LinkedHashMap<>(); - private boolean isSomeFlag; - private boolean someNonIsFlag; - - /** - * Default constructor. - */ - public TestParametersL00() { - super(A_CONSTANT); - } - - /** - * Create a test parameter group. - * - * @param name the parameter group name - */ - public TestParametersL00(final String name) { - super(name); - - TestParametersLGeneric l00LGenericNestedMapVal0 = new TestParametersLGeneric("l00LGenericNestedMapVal0"); - l00LGenericNestedMap.put(l00LGenericNestedMapVal0.getName(), l00LGenericNestedMapVal0); - TestParametersLGeneric l00LGenericNestedMapVal1 = new TestParametersLGeneric("l00LGenericNestedMapVal1"); - l00LGenericNestedMap.put(l00LGenericNestedMapVal1.getName(), l00LGenericNestedMapVal1); - } - - public int getL00IntField() { - return l00IntField; - } - - public String getL00StringField() { - return l00StringField; - } - - public TestParametersL10 getL00L10Nested() { - return l00L10Nested; - } - - public TestParametersLGeneric getL00LGenericNested() { - return l00LGenericNested; - } - - public Map<String, TestParametersLGeneric> getL00LGenericNestedMap() { - return l00LGenericNestedMap; - } - - public boolean isSomeFlag() { - return isSomeFlag; - } - - public boolean isSomeNonIsFlag() { - return someNonIsFlag; - } - - public void setSomeFlag(boolean isSomeFlag) { - this.isSomeFlag = isSomeFlag; - } - - public void setL00IntField(int l00IntField) { - this.l00IntField = l00IntField; - } - - public void setL00StringField(String l00StringField) { - this.l00StringField = l00StringField; - } - - public void setL00L10Nested(TestParametersL10 l00l10Nested) { - l00L10Nested = l00l10Nested; - } - - public void setL00LGenericNested(TestParametersLGeneric l00lGenericNested) { - l00LGenericNested = l00lGenericNested; - } - - public void setL00LGenericNestedMap(Map<String, TestParametersLGeneric> l00lGenericNestedMap) { - l00LGenericNestedMap = l00lGenericNestedMap; - } - - /** - * Trigger a validation message. - * - * @param triggerStatus Validation status to trigger - * @param level Number of levels to recurse before stopping - */ - public void triggerValidationStatus(final ValidationStatus triggerStatus, int level) { - if (level == 0) { - return; - } else { - level--; - } - - switch (triggerStatus) { - case CLEAN: - l00StringField = "Legal " + this.getClass().getName(); - l00IntField = 0; - break; - case OBSERVATION: - l00StringField = "aString"; - l00IntField = 2; - break; - case WARNING: - l00StringField = L00_STRING_FIELD; - l00IntField = 3; - break; - case INVALID: - l00StringField = ""; - l00IntField = -1; - break; - default: - break; - } - - l00L10Nested.triggerValidationStatus(triggerStatus, level); - l00LGenericNested.triggerValidationStatus(triggerStatus, level); - - for (TestParametersLGeneric nestedParameterGroup : l00LGenericNestedMap.values()) { - nestedParameterGroup.triggerValidationStatus(triggerStatus, level); - } - - } - - @Override - public GroupValidationResult validate() { - GroupValidationResult validationResult = super.validate(); - - if (StringUtils.isBlank(getName())) { - validationResult.setResult("name", ValidationStatus.INVALID, "name must be a non-blank string"); - } - - if (StringUtils.isBlank(l00StringField)) { - validationResult.setResult(L00_STRING_FIELD, ValidationStatus.INVALID, - "l00StringField must be a non-blank string"); - } else if (l00StringField.equals(L00_STRING_FIELD)) { - validationResult.setResult(L00_STRING_FIELD, ValidationStatus.WARNING, - "using the field name for the parameter value is dangerous"); - } else if (l00StringField.equals("aString")) { - validationResult.setResult(L00_STRING_FIELD, ValidationStatus.OBSERVATION, - "this value for name is unhelpful"); - } else { - validationResult.setResult(L00_STRING_FIELD, ValidationStatus.CLEAN, - ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString()); - } - - if (l00IntField < 0) { - validationResult.setResult(L00_INT_FIELD, ValidationStatus.INVALID, - "l00IntField must be a positive integer"); - } else if (l00IntField > 2) { - validationResult.setResult(L00_INT_FIELD, ValidationStatus.WARNING, - "values greater than 2 are not recommended"); - } else if (l00IntField == 2) { - validationResult.setResult(L00_INT_FIELD, ValidationStatus.OBSERVATION, "this field has been set to 2"); - } else { - validationResult.setResult(L00_INT_FIELD, ValidationStatus.CLEAN, - ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString()); - } - - validationResult.setResult("l00L10Nested", l00L10Nested.validate()); - validationResult.setResult("l00LGenericNested", l00LGenericNested.validate()); - - for (Entry<String, TestParametersLGeneric> nestedGroupEntry : l00LGenericNestedMap.entrySet()) { - validationResult.setResult("l00LGenericNestedMap", nestedGroupEntry.getKey(), - nestedGroupEntry.getValue().validate()); - } - - return validationResult; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java deleted file mode 100644 index 7276b504..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import org.apache.commons.lang3.StringUtils; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ParameterConstants; -import org.onap.policy.common.parameters.ParameterGroupImpl; -import org.onap.policy.common.parameters.ValidationStatus; - -public class TestParametersL10 extends ParameterGroupImpl { - private static final String L10_INT_FIELD = "l10IntField"; - private static final String L10_STRING_FIELD = "l10StringField"; - - private int l10IntField = 0; - private String l10StringField = "Legal " + this.getClass().getName(); - private TestParametersLGeneric l10LGenericNested0 = new TestParametersLGeneric("l10LGenericNested0"); - private TestParametersLGeneric l10LGenericNested1 = new TestParametersLGeneric("l10LGenericNested1"); - private Map<String, TestParametersLGeneric> l10LGenericNestedMap = new LinkedHashMap<>(); - - /** - * Default constructor. - */ - public TestParametersL10() { - // Default Constructor - } - - /** - * Create a test parameter group. - * - * @param name the parameter group name - */ - public TestParametersL10(final String name) { - super(name); - - TestParametersLGeneric l10LGenericNestedMapVal0 = new TestParametersLGeneric("l10LGenericNestedMapVal0"); - l10LGenericNestedMap.put(l10LGenericNestedMapVal0.getName(), l10LGenericNestedMapVal0); - TestParametersLGeneric l10LGenericNestedMapVal1 = new TestParametersLGeneric("l10LGenericNestedMapVal1"); - l10LGenericNestedMap.put(l10LGenericNestedMapVal1.getName(), l10LGenericNestedMapVal1); - } - - public int getL10IntField() { - return l10IntField; - } - - public String getL10StringField() { - return l10StringField; - } - - public TestParametersLGeneric getL10LGenericNested0() { - return l10LGenericNested0; - } - - public TestParametersLGeneric getL10LGenericNested1() { - return l10LGenericNested1; - } - - public Map<String, TestParametersLGeneric> getL10LGenericNestedMap() { - return l10LGenericNestedMap; - } - - public void setL10IntField(int l10IntField) { - this.l10IntField = l10IntField; - } - - public void setL10StringField(String l10StringField) { - this.l10StringField = l10StringField; - } - - public void setL10LGenericNested0(TestParametersLGeneric l10lGenericNested0) { - l10LGenericNested0 = l10lGenericNested0; - } - - public void setL10LGenericNested1(TestParametersLGeneric l10lGenericNested1) { - l10LGenericNested1 = l10lGenericNested1; - } - - public void setL10LGenericNestedMap(Map<String, TestParametersLGeneric> l10lGenericNestedMap) { - l10LGenericNestedMap = l10lGenericNestedMap; - } - - /** - * Trigger a validation message. - * - * @param level Number of levels to recurse before stopping - */ - public void triggerValidationStatus(final ValidationStatus triggerStatus, int level) { - if (level == 0) { - return; - } - else { - level--; - } - - switch (triggerStatus) { - case CLEAN: - l10StringField = "Legal " + this.getClass().getName(); - l10IntField = 0; - break; - case OBSERVATION: - l10StringField = "aString"; - l10IntField = 2; - break; - case WARNING: - l10StringField = L10_STRING_FIELD; - l10IntField = 3; - break; - case INVALID: - l10StringField = ""; - l10IntField = -1; - break; - default: - break; - } - - l10LGenericNested0.triggerValidationStatus(triggerStatus, level); - l10LGenericNested1.triggerValidationStatus(triggerStatus, level); - - for (TestParametersLGeneric nestedParameterGroup : l10LGenericNestedMap.values()) { - nestedParameterGroup.triggerValidationStatus(triggerStatus, level); - } - } - - @Override - public GroupValidationResult validate() { - GroupValidationResult validationResult = super.validate(); - - if (StringUtils.isBlank(l10StringField)) { - validationResult.setResult(L10_STRING_FIELD, ValidationStatus.INVALID, - "l10StringField must be a non-blank string"); - } else if (l10StringField.equals(L10_STRING_FIELD)) { - validationResult.setResult(L10_STRING_FIELD, ValidationStatus.WARNING, - "using the field name for the parameter value is dangerous"); - } else if (l10StringField.equals("aString")) { - validationResult.setResult(L10_STRING_FIELD, ValidationStatus.OBSERVATION, - "this value for name is unhelpful"); - } else { - validationResult.setResult(L10_STRING_FIELD, ValidationStatus.CLEAN, - ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString()); - } - - if (l10IntField < 0) { - validationResult.setResult(L10_INT_FIELD, ValidationStatus.INVALID, - "l10IntField must be a positive integer"); - } else if (l10IntField > 2) { - validationResult.setResult(L10_INT_FIELD, ValidationStatus.WARNING, - "values greater than 2 are not recommended"); - } else if (l10IntField == 2) { - validationResult.setResult(L10_INT_FIELD, ValidationStatus.OBSERVATION, "this field has been set to 2"); - } else { - validationResult.setResult(L10_INT_FIELD, ValidationStatus.CLEAN, - ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString()); - } - - if (l10LGenericNested0 != null) { - validationResult.setResult("l10LGenericNested0", l10LGenericNested0.validate()); - } - validationResult.setResult("l10LGenericNested1", l10LGenericNested1.validate()); - - for (Entry<String, TestParametersLGeneric> nestedGroupEntry : l10LGenericNestedMap.entrySet()) { - validationResult.setResult("l10LGenericNestedMap", nestedGroupEntry.getKey(), - nestedGroupEntry.getValue().validate()); - } - - return validationResult; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java deleted file mode 100644 index f9d6cdc4..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ParameterGroupImpl; -import org.onap.policy.common.parameters.ValidationStatus; -import org.onap.policy.common.parameters.annotations.NotBlank; -import org.onap.policy.common.parameters.annotations.NotNull; - -public class TestParametersLGeneric extends ParameterGroupImpl { - private static final String LGENERIC_INT_FIELD = "lgenericIntField"; - private static final String LGENERIC_STRING_FIELD = "lgenericStringField"; - - private int lgenericIntField = 0; - - @NotNull @NotBlank - private String lgenericStringField = "Legal " + this.getClass().getName(); - - /** - * Default constructor. - */ - public TestParametersLGeneric() { - // Default Constructor - } - - /** - * Create a test parameter group. - * - * @param name the parameter group name - */ - public TestParametersLGeneric(final String name) { - super(name); - } - - public int getLgenericIntField() { - return lgenericIntField; - } - - public String getLgenericStringField() { - return lgenericStringField; - } - - public void setLgenericIntField(int lgenericIntField) { - this.lgenericIntField = lgenericIntField; - } - - public void setLgenericStringField(String lgenericStringField) { - this.lgenericStringField = lgenericStringField; - } - - /** - * Trigger a validation message. - * - * @param level Number of levels to recurse before stopping - */ - public void triggerValidationStatus(final ValidationStatus triggerStatus, int level) { - if (level == 0) { - return; - } - - switch (triggerStatus) { - case CLEAN: - lgenericStringField = "Legal " + this.getClass().getName(); - lgenericIntField = 0; - break; - case OBSERVATION: - lgenericStringField = "aString"; - lgenericIntField = 2; - break; - case WARNING: - lgenericStringField = LGENERIC_STRING_FIELD; - lgenericIntField = 3; - break; - case INVALID: - lgenericStringField = ""; - lgenericIntField = -1; - break; - default: - break; - } - - } - - @Override - public GroupValidationResult validate() { - GroupValidationResult validationResult = super.validate(); - - if (LGENERIC_STRING_FIELD.equals(lgenericStringField)) { - validationResult.setResult(LGENERIC_STRING_FIELD, ValidationStatus.WARNING, - "using the field name for the parameter value is dangerous"); - } else if ("aString".equals(lgenericStringField)) { - validationResult.setResult(LGENERIC_STRING_FIELD, ValidationStatus.OBSERVATION, - "this value for name is unhelpful"); - } - - if (lgenericIntField < 0) { - validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.INVALID, - "lgenericIntField must be a positive integer"); - } else if (lgenericIntField > 2) { - validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.WARNING, - "values greater than 2 are not recommended"); - } else if (lgenericIntField == 2) { - validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.OBSERVATION, - "this field has been set to 2"); - } - - return validationResult; - } -} diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt b/common-parameters/src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt deleted file mode 100644 index 64af7247..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt +++ /dev/null @@ -1,41 +0,0 @@ -parameter group "l00NameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" CLEAN, parameter group has status CLEAN - field "l00IntField" type "int" value "1" CLEAN, parameter has status CLEAN - field "l00StringField" type "java.lang.String" value "l00 string field value from file" CLEAN, parameter has status CLEAN - parameter group "l00L10NestedNameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" CLEAN, parameter group has status CLEAN - field "l10IntField" type "int" value "1" CLEAN, parameter has status CLEAN - field "l10StringField" type "java.lang.String" value "l00 L10 nested string field value from file" CLEAN, parameter has status CLEAN - parameter group "l10LGenericNested0NameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "l10 generic nested 0 string field value from file" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l10LGenericNested0NameFromFile" CLEAN, parameter has status CLEAN - parameter group "l10LGenericNested1NameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "l10 generic nested 1 string field value from file" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l10LGenericNested1NameFromFile" CLEAN, parameter has status CLEAN - parameter group map "l10LGenericNestedMap" CLEAN, parameter group map has status CLEAN - parameter group "L10Entry0Name" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "L10Entry0 value from file" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "L10Entry0Name" CLEAN, parameter has status CLEAN - parameter group "L10Entry1Name" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "L10Entry1 value from file" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "L10Entry1Name" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l00L10NestedNameFromFile" CLEAN, parameter has status CLEAN - parameter group "l00GenericNestedNameFromFile" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "l00 generic nested string field value from file" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l00GenericNestedNameFromFile" CLEAN, parameter has status CLEAN - parameter group map "l00LGenericNestedMap" CLEAN, parameter group map has status CLEAN - parameter group "L00Entry0Name" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "L00Entry0 value from file" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "L00Entry0Name" CLEAN, parameter has status CLEAN - parameter group "L00Entry1Name" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "1" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "L00Entry1 value from file" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "L00Entry1Name" CLEAN, parameter has status CLEAN - field "isSomeFlag" type "boolean" value "false" CLEAN, parameter has status CLEAN - field "someNonIsFlag" type "boolean" value "false" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l00NameFromFile" CLEAN, parameter has status CLEAN -
\ No newline at end of file diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt deleted file mode 100644 index d6b43312..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt +++ /dev/null @@ -1,41 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" CLEAN, parameter group has status CLEAN - field "l00IntField" type "int" value "0" CLEAN, parameter has status CLEAN - field "l00StringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersL00" CLEAN, parameter has status CLEAN - parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" CLEAN, parameter group has status CLEAN - field "l10IntField" type "int" value "0" CLEAN, parameter has status CLEAN - field "l10StringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersL10" CLEAN, parameter has status CLEAN - parameter group "l10LGenericNested0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l10LGenericNested0" CLEAN, parameter has status CLEAN - parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l10LGenericNested1" CLEAN, parameter has status CLEAN - parameter group map "l10LGenericNestedMap" CLEAN, parameter group map has status CLEAN - parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l10LGenericNestedMapVal0" CLEAN, parameter has status CLEAN - parameter group "l10LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l10LGenericNestedMapVal1" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l00L10Nested" CLEAN, parameter has status CLEAN - parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l00LGenericNested" CLEAN, parameter has status CLEAN - parameter group map "l00LGenericNestedMap" CLEAN, parameter group map has status CLEAN - parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l00LGenericNestedMapVal0" CLEAN, parameter has status CLEAN - parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter group has status CLEAN - field "lgenericIntField" type "int" value "0" CLEAN, parameter has status CLEAN - field "lgenericStringField" type "java.lang.String" value "Legal org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l00LGenericNestedMapVal1" CLEAN, parameter has status CLEAN - field "isSomeFlag" type "boolean" value "false" CLEAN, parameter has status CLEAN - field "someNonIsFlag" type "boolean" value "false" CLEAN, parameter has status CLEAN - field "name" type "java.lang.String" value "l0Parameters" CLEAN, parameter has status CLEAN -
\ No newline at end of file diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt deleted file mode 100644 index dcc3cee3..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt +++ /dev/null @@ -1,3 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" INVALID, parameter group has status INVALID - field "l00IntField" type "int" value "-1" INVALID, l00IntField must be a positive integer - field "l00StringField" type "java.lang.String" value "" INVALID, l00StringField must be a non-blank string diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt deleted file mode 100644 index ae627926..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt +++ /dev/null @@ -1,3 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" OBSERVATION, parameter group has status OBSERVATION - field "l00IntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "l00StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt deleted file mode 100644 index 14a65aa8..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt +++ /dev/null @@ -1,3 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" WARNING, parameter group has status WARNING - field "l00IntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "l00StringField" type "java.lang.String" value "l00StringField" WARNING, using the field name for the parameter value is dangerous diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt deleted file mode 100644 index 412a36c1..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt +++ /dev/null @@ -1,16 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" INVALID, parameter group has status INVALID - field "l00IntField" type "int" value "-1" INVALID, l00IntField must be a positive integer - field "l00StringField" type "java.lang.String" value "" INVALID, l00StringField must be a non-blank string - parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" INVALID, parameter group has status INVALID - field "l10IntField" type "int" value "-1" INVALID, l10IntField must be a positive integer - field "l10StringField" type "java.lang.String" value "" INVALID, l10StringField must be a non-blank string - parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group map "l00LGenericNestedMap" INVALID, parameter group map has status INVALID - parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
\ No newline at end of file diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt deleted file mode 100644 index c1989226..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt +++ /dev/null @@ -1,16 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" OBSERVATION, parameter group has status OBSERVATION - field "l00IntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "l00StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" OBSERVATION, parameter group has status OBSERVATION - field "l10IntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "l10StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group map "l00LGenericNestedMap" OBSERVATION, parameter group map has status OBSERVATION - parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt deleted file mode 100644 index 380ded8f..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt +++ /dev/null @@ -1,16 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" WARNING, parameter group has status WARNING - field "l00IntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "l00StringField" type "java.lang.String" value "l00StringField" WARNING, using the field name for the parameter value is dangerous - parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" WARNING, parameter group has status WARNING - field "l10IntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "l10StringField" type "java.lang.String" value "l10StringField" WARNING, using the field name for the parameter value is dangerous - parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group map "l00LGenericNestedMap" WARNING, parameter group map has status WARNING - parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
\ No newline at end of file diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt deleted file mode 100644 index 12bce5c3..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt +++ /dev/null @@ -1,29 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" INVALID, parameter group has status INVALID - field "l00IntField" type "int" value "-1" INVALID, l00IntField must be a positive integer - field "l00StringField" type "java.lang.String" value "" INVALID, l00StringField must be a non-blank string - parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" INVALID, parameter group has status INVALID - field "l10IntField" type "int" value "-1" INVALID, l10IntField must be a positive integer - field "l10StringField" type "java.lang.String" value "" INVALID, l10StringField must be a non-blank string - parameter group "l10LGenericNested0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group map "l10LGenericNestedMap" INVALID, parameter group map has status INVALID - parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group "l10LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group map "l00LGenericNestedMap" INVALID, parameter group map has status INVALID - parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID - field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer - field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string
\ No newline at end of file diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt deleted file mode 100644 index 36517cef..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt +++ /dev/null @@ -1,29 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" OBSERVATION, parameter group has status OBSERVATION - field "l00IntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "l00StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" OBSERVATION, parameter group has status OBSERVATION - field "l10IntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "l10StringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group "l10LGenericNested0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group map "l10LGenericNestedMap" OBSERVATION, parameter group map has status OBSERVATION - parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group "l10LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group map "l00LGenericNestedMap" OBSERVATION, parameter group map has status OBSERVATION - parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION - field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 - field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt deleted file mode 100644 index 28747670..00000000 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt +++ /dev/null @@ -1,29 +0,0 @@ -parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclasses.TestParametersL00" WARNING, parameter group has status WARNING - field "l00IntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "l00StringField" type "java.lang.String" value "l00StringField" WARNING, using the field name for the parameter value is dangerous - parameter group "l00L10Nested" type "org.onap.policy.common.parameters.testclasses.TestParametersL10" WARNING, parameter group has status WARNING - field "l10IntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "l10StringField" type "java.lang.String" value "l10StringField" WARNING, using the field name for the parameter value is dangerous - parameter group "l10LGenericNested0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group map "l10LGenericNestedMap" WARNING, parameter group map has status WARNING - parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group "l10LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group map "l00LGenericNestedMap" WARNING, parameter group map has status WARNING - parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group "l00LGenericNestedMapVal1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING - field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended - field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous
\ No newline at end of file |